diff --git a/src/context_diff.rs b/src/context_diff.rs index f0f27108..0762bcb8 100644 --- a/src/context_diff.rs +++ b/src/context_diff.rs @@ -323,8 +323,10 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { } else { TimestampStyle::Iso }; - let from_modified_time = get_modification_time(¶ms.from.to_string_lossy(), style); - let to_modified_time = get_modification_time(¶ms.to.to_string_lossy(), style); + let from_modified_time = + get_modification_time(¶ms.from.to_string_lossy(), style, params.from_missing); + let to_modified_time = + get_modification_time(¶ms.to.to_string_lossy(), style, params.to_missing); let mut output = Vec::new(); write_file_header(&mut output, "***", ¶ms.from, &from_modified_time); write_file_header(&mut output, "---", ¶ms.to, &to_modified_time); diff --git a/src/diff.rs b/src/diff.rs index cc67c1f6..2cc546cf 100644 --- a/src/diff.rs +++ b/src/diff.rs @@ -97,11 +97,14 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome { } } let mut io_error = false; + let mut from_missing = false; + let mut to_missing = false; let from_content = match read_file_contents(¶ms.from) { Ok(from_content) => from_content, Err(e) if e.kind() == io::ErrorKind::NotFound && params.missing_file != MissingFile::Error => { + from_missing = true; vec![] } Err(e) => { @@ -115,6 +118,7 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome { Err(e) if e.kind() == io::ErrorKind::NotFound && params.missing_file == MissingFile::Empty => { + to_missing = true; vec![] } Err(e) => { @@ -143,6 +147,12 @@ pub fn compare_files(params: &Params, header: Option<&[u8]>) -> Outcome { return Outcome::Different; } + let params = &Params { + from_missing, + to_missing, + ..params.clone() + }; + // run diff let result: Vec = match params.format { Format::Normal => normal_diff::diff(&from_content, &to_content, params), diff --git a/src/params.rs b/src/params.rs index b13c0b36..9d4777cc 100644 --- a/src/params.rs +++ b/src/params.rs @@ -58,6 +58,10 @@ pub struct Params { pub starting_file: Option, pub ignore_file_name_case: bool, pub no_dereference: bool, + /// Set when `from` did not exist and was compared as an empty file. + pub from_missing: bool, + /// Set when `to` did not exist and was compared as an empty file. + pub to_missing: bool, } /// The pattern of `-p`, matching the first line of C functions. @@ -86,6 +90,8 @@ impl Default for Params { starting_file: None, ignore_file_name_case: false, no_dereference: false, + from_missing: false, + to_missing: false, } } } diff --git a/src/unified_diff.rs b/src/unified_diff.rs index e30da1dd..28eaf8f9 100644 --- a/src/unified_diff.rs +++ b/src/unified_diff.rs @@ -242,9 +242,16 @@ fn make_diff( #[must_use] pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { - let from_modified_time = - get_modification_time(¶ms.from.to_string_lossy(), TimestampStyle::Iso); - let to_modified_time = get_modification_time(¶ms.to.to_string_lossy(), TimestampStyle::Iso); + let from_modified_time = get_modification_time( + ¶ms.from.to_string_lossy(), + TimestampStyle::Iso, + params.from_missing, + ); + let to_modified_time = get_modification_time( + ¶ms.to.to_string_lossy(), + TimestampStyle::Iso, + params.to_missing, + ); let mut output = Vec::new(); write_file_header(&mut output, "---", ¶ms.from, &from_modified_time); write_file_header(&mut output, "+++", ¶ms.to, &to_modified_time); diff --git a/src/utils.rs b/src/utils.rs index 408e13b2..29ab93df 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -242,15 +242,20 @@ pub fn is_posix_locale(category: &str) -> bool { } /// Retrieves the modification time of the input file specified by file path +/// A file that was `missing` and compared as empty is dated at the Unix Epoch. /// If an error occurs, it returns the current system time -pub fn get_modification_time(file_path: &str, style: TimestampStyle) -> String { +pub fn get_modification_time(file_path: &str, style: TimestampStyle, missing: bool) -> String { use chrono::{DateTime, Local}; use std::fs; - use std::time::SystemTime; + use std::time::{SystemTime, UNIX_EPOCH}; - let modification_time: SystemTime = fs::metadata(file_path) - .and_then(|m| m.modified()) - .unwrap_or(SystemTime::now()); + let modification_time: SystemTime = if missing { + UNIX_EPOCH + } else { + fs::metadata(file_path) + .and_then(|m| m.modified()) + .unwrap_or(SystemTime::now()) + }; let modification_time: DateTime = modification_time.into(); let format = match style { @@ -521,7 +526,7 @@ mod tests { // verify assert_eq!( current, - get_modification_time(&temp.path().to_string_lossy(), TimestampStyle::Iso) + get_modification_time(&temp.path().to_string_lossy(), TimestampStyle::Iso, false) ); } @@ -536,9 +541,10 @@ mod tests { // Because the file is invalid, it will return SystemTime::now() // which will be greater than previously saved time let current_time: DateTime = SystemTime::now().into(); - let m_time: DateTime = get_modification_time(invalid_file, TimestampStyle::Iso) - .parse() - .unwrap(); + let m_time: DateTime = + get_modification_time(invalid_file, TimestampStyle::Iso, false) + .parse() + .unwrap(); assert!(m_time > current_time); } diff --git a/tests/by-util/test_diff.rs b/tests/by-util/test_diff.rs index 71bfcad2..f25c21e5 100644 --- a/tests/by-util/test_diff.rs +++ b/tests/by-util/test_diff.rs @@ -246,6 +246,124 @@ fn missing_file_as_empty() -> Result<(), Box> { Ok(()) } +// TZ is not honored on Windows. +#[cfg(unix)] +#[test] +fn missing_file_header_timestamp() -> Result<(), Box> { + let tmp_dir = tempdir()?; + let left = tmp_dir.path().join("left"); + let right = tmp_dir.path().join("right"); + std::fs::create_dir(&left)?; + std::fs::create_dir_all(right.join("nested"))?; + let absent = left.join("nested/file"); + let present = right.join("nested/file"); + std::fs::write(&present, "kiwi\n")?; + let mtime = std::time::UNIX_EPOCH + std::time::Duration::from_millis(1_234_567_890_250); + File::options() + .write(true) + .open(&present)? + .set_modified(mtime)?; + + for (format, locale, markers, epoch, timestamp) in [ + ( + "-u", + "C", + ["---", "+++"], + "1970-01-01 00:00:00.000000000 +0000", + "2009-02-13 23:31:30.250000000 +0000", + ), + ( + "-c", + "en_US.UTF-8", + ["***", "---"], + "1970-01-01 00:00:00.000000000 +0000", + "2009-02-13 23:31:30.250000000 +0000", + ), + ( + "-c", + "C", + ["***", "---"], + "Thu Jan 1 00:00:00 1970", + "Fri Feb 13 23:31:30 2009", + ), + ] { + for option in ["-N", "--new-file", "--unidirectional-new-file"] { + for reverse in [false, true] { + if reverse && option == "--unidirectional-new-file" { + continue; + } + let headers = if reverse { + format!( + "{} {}\t{timestamp}\n{} {}\t{epoch}\n", + markers[0], + present.display(), + markers[1], + absent.display() + ) + } else { + format!( + "{} {}\t{epoch}\n{} {}\t{timestamp}\n", + markers[0], + absent.display(), + markers[1], + present.display() + ) + }; + for recursive in [false, true] { + let (from, to) = if recursive { + (&left, &right) + } else { + (&absent, &present) + }; + let mut cmd = cargo_bin_cmd!("diffutils"); + cmd.env("TZ", "UTC0") + .env("LC_ALL", locale) + .arg("diff") + .arg(format) + .arg(option); + if recursive { + cmd.arg("-r"); + } + cmd.arg(if reverse { to } else { from }) + .arg(if reverse { from } else { to }); + cmd.assert() + .code(predicate::eq(1)) + .stderr(predicate::str::is_empty()) + .stdout(predicate::str::contains(&headers)); + } + } + } + } + Ok(()) +} + +#[test] +fn missing_file_as_empty_keeps_stdin_timestamp() -> Result<(), Box> { + let mut file = NamedTempFile::new()?; + file.write_all(b"file\n")?; + + let stdin = std::ffi::OsStr::new("-"); + let file = file.path().as_os_str(); + for format in ["-u", "-c"] { + for (from, to) in [(stdin, file), (file, stdin)] { + let mut cmd = cargo_bin_cmd!("diffutils"); + cmd.env("TZ", "UTC0") + .env("LC_ALL", "C") + .arg("diff") + .arg(format) + .arg("-N") + .arg(from) + .arg(to) + .write_stdin("stdin\n"); + cmd.assert() + .code(predicate::eq(1)) + .stderr(predicate::str::is_empty()) + .stdout(predicate::str::contains("1970").not()); + } + } + Ok(()) +} + #[test] fn binary_files() -> Result<(), Box> { let tmp_dir = tempdir()?;