Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/context_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,8 +323,10 @@ pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec<u8> {
} else {
TimestampStyle::Iso
};
let from_modified_time = get_modification_time(&params.from.to_string_lossy(), style);
let to_modified_time = get_modification_time(&params.to.to_string_lossy(), style);
let from_modified_time =
get_modification_time(&params.from.to_string_lossy(), style, params.from_missing);
let to_modified_time =
get_modification_time(&params.to.to_string_lossy(), style, params.to_missing);
let mut output = Vec::new();
write_file_header(&mut output, "***", &params.from, &from_modified_time);
write_file_header(&mut output, "---", &params.to, &to_modified_time);
Expand Down
10 changes: 10 additions & 0 deletions src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(&params.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) => {
Expand All @@ -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) => {
Expand Down Expand Up @@ -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<u8> = match params.format {
Format::Normal => normal_diff::diff(&from_content, &to_content, params),
Expand Down
6 changes: 6 additions & 0 deletions src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ pub struct Params {
pub starting_file: Option<OsString>,
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.
Expand Down Expand Up @@ -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,
}
}
}
Expand Down
13 changes: 10 additions & 3 deletions src/unified_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,9 +242,16 @@ fn make_diff(

#[must_use]
pub fn diff(expected: &[u8], actual: &[u8], params: &Params) -> Vec<u8> {
let from_modified_time =
get_modification_time(&params.from.to_string_lossy(), TimestampStyle::Iso);
let to_modified_time = get_modification_time(&params.to.to_string_lossy(), TimestampStyle::Iso);
let from_modified_time = get_modification_time(
&params.from.to_string_lossy(),
TimestampStyle::Iso,
params.from_missing,
);
let to_modified_time = get_modification_time(
&params.to.to_string_lossy(),
TimestampStyle::Iso,
params.to_missing,
);
let mut output = Vec::new();
write_file_header(&mut output, "---", &params.from, &from_modified_time);
write_file_header(&mut output, "+++", &params.to, &to_modified_time);
Expand Down
24 changes: 15 additions & 9 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Local> = modification_time.into();
let format = match style {
Expand Down Expand Up @@ -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)
);
}

Expand All @@ -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<Local> = SystemTime::now().into();
let m_time: DateTime<Local> = get_modification_time(invalid_file, TimestampStyle::Iso)
.parse()
.unwrap();
let m_time: DateTime<Local> =
get_modification_time(invalid_file, TimestampStyle::Iso, false)
.parse()
.unwrap();

assert!(m_time > current_time);
}
Expand Down
118 changes: 118 additions & 0 deletions tests/by-util/test_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,124 @@ fn missing_file_as_empty() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}

// TZ is not honored on Windows.
#[cfg(unix)]
#[test]
fn missing_file_header_timestamp() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
let tmp_dir = tempdir()?;
Expand Down
Loading