From 4288a5dd5f0a1f5875c4fb88abc37852ea523b2b Mon Sep 17 00:00:00 2001 From: Nurlan Mammadli Date: Mon, 9 Nov 2026 11:51:37 -0500 Subject: [PATCH 1/2] diff: date a missing file at the Unix Epoch with -N With -N/--new-file the header of a missing file now shows 1970-01-01 instead of the current time, which is what patch relies on to detect creation and deletion. Covers -u, -c and -r. Fixes #361. Co-Authored-By: Claude Sonnet 5.5 --- src/context_diff.rs | 14 ++++-- src/unified_diff.rs | 15 +++++-- src/utils.rs | 27 +++++++---- tests/by-util/test_diff.rs | 91 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 132 insertions(+), 15 deletions(-) diff --git a/src/context_diff.rs b/src/context_diff.rs index f0f27108..6f8999cb 100644 --- a/src/context_diff.rs +++ b/src/context_diff.rs @@ -6,7 +6,7 @@ use std::collections::VecDeque; use std::io::Write; -use crate::params::Params; +use crate::params::{MissingFile, Params}; use crate::utils::do_write_line; use crate::utils::{ get_modification_time, is_posix_locale, write_file_header, FunctionLineFinder, TimestampStyle, @@ -323,8 +323,16 @@ 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.missing_file != MissingFile::Error, + ); + let to_modified_time = get_modification_time( + ¶ms.to.to_string_lossy(), + style, + params.missing_file == MissingFile::Empty, + ); 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/unified_diff.rs b/src/unified_diff.rs index e30da1dd..92631355 100644 --- a/src/unified_diff.rs +++ b/src/unified_diff.rs @@ -6,7 +6,7 @@ use std::collections::VecDeque; use std::io::Write; -use crate::params::Params; +use crate::params::{MissingFile, Params}; use crate::utils::do_write_line; use crate::utils::{get_modification_time, write_file_header, FunctionLineFinder, TimestampStyle}; @@ -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.missing_file != MissingFile::Error, + ); + let to_modified_time = get_modification_time( + ¶ms.to.to_string_lossy(), + TimestampStyle::Iso, + params.missing_file == MissingFile::Empty, + ); 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..fa5bd20f 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -242,15 +242,25 @@ pub fn is_posix_locale(category: &str) -> bool { } /// Retrieves the modification time of the input file specified by file path -/// If an error occurs, it returns the current system time -pub fn get_modification_time(file_path: &str, style: TimestampStyle) -> String { +/// Missing files treated as empty use the Unix Epoch; other errors use the current system time. +pub fn get_modification_time( + file_path: &str, + style: TimestampStyle, + missing_as_empty: 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()); + .unwrap_or_else(|error| { + if missing_as_empty && error.kind() == std::io::ErrorKind::NotFound { + UNIX_EPOCH + } else { + SystemTime::now() + } + }); let modification_time: DateTime = modification_time.into(); let format = match style { @@ -521,7 +531,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 +546,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..1e88774e 100644 --- a/tests/by-util/test_diff.rs +++ b/tests/by-util/test_diff.rs @@ -246,6 +246,97 @@ 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 binary_files() -> Result<(), Box> { let tmp_dir = tempdir()?; From e57e23fc08b662e216d506b0b951861bb551a6e5 Mon Sep 17 00:00:00 2001 From: Nurlan Mammadli Date: Mon, 9 Nov 2026 16:05:22 -0500 Subject: [PATCH 2/2] diff: use the epoch only for operands that really were missing Record in compare_files whether an operand was absent instead of inferring it from fs::metadata in each formatter, so stdin keeps its current time with -N. Co-Authored-By: Claude Opus 5.5 --- src/context_diff.rs | 16 +++++----------- src/diff.rs | 10 ++++++++++ src/params.rs | 6 ++++++ src/unified_diff.rs | 6 +++--- src/utils.rs | 25 ++++++++++--------------- tests/by-util/test_diff.rs | 27 +++++++++++++++++++++++++++ 6 files changed, 61 insertions(+), 29 deletions(-) diff --git a/src/context_diff.rs b/src/context_diff.rs index 6f8999cb..0762bcb8 100644 --- a/src/context_diff.rs +++ b/src/context_diff.rs @@ -6,7 +6,7 @@ use std::collections::VecDeque; use std::io::Write; -use crate::params::{MissingFile, Params}; +use crate::params::Params; use crate::utils::do_write_line; use crate::utils::{ get_modification_time, is_posix_locale, write_file_header, FunctionLineFinder, TimestampStyle, @@ -323,16 +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, - params.missing_file != MissingFile::Error, - ); - let to_modified_time = get_modification_time( - ¶ms.to.to_string_lossy(), - style, - params.missing_file == MissingFile::Empty, - ); + 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 92631355..28eaf8f9 100644 --- a/src/unified_diff.rs +++ b/src/unified_diff.rs @@ -6,7 +6,7 @@ use std::collections::VecDeque; use std::io::Write; -use crate::params::{MissingFile, Params}; +use crate::params::Params; use crate::utils::do_write_line; use crate::utils::{get_modification_time, write_file_header, FunctionLineFinder, TimestampStyle}; @@ -245,12 +245,12 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec { let from_modified_time = get_modification_time( ¶ms.from.to_string_lossy(), TimestampStyle::Iso, - params.missing_file != MissingFile::Error, + params.from_missing, ); let to_modified_time = get_modification_time( ¶ms.to.to_string_lossy(), TimestampStyle::Iso, - params.missing_file == MissingFile::Empty, + params.to_missing, ); let mut output = Vec::new(); write_file_header(&mut output, "---", ¶ms.from, &from_modified_time); diff --git a/src/utils.rs b/src/utils.rs index fa5bd20f..29ab93df 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -242,25 +242,20 @@ pub fn is_posix_locale(category: &str) -> bool { } /// Retrieves the modification time of the input file specified by file path -/// Missing files treated as empty use the Unix Epoch; other errors use the current system time. -pub fn get_modification_time( - file_path: &str, - style: TimestampStyle, - missing_as_empty: bool, -) -> String { +/// 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, missing: bool) -> String { use chrono::{DateTime, Local}; use std::fs; use std::time::{SystemTime, UNIX_EPOCH}; - let modification_time: SystemTime = fs::metadata(file_path) - .and_then(|m| m.modified()) - .unwrap_or_else(|error| { - if missing_as_empty && error.kind() == std::io::ErrorKind::NotFound { - UNIX_EPOCH - } else { - 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 { diff --git a/tests/by-util/test_diff.rs b/tests/by-util/test_diff.rs index 1e88774e..f25c21e5 100644 --- a/tests/by-util/test_diff.rs +++ b/tests/by-util/test_diff.rs @@ -337,6 +337,33 @@ fn missing_file_header_timestamp() -> Result<(), Box> { 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()?;