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
36 changes: 21 additions & 15 deletions src/dir_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,29 +37,36 @@ pub fn compare(params: &Params, option_args: &[OsString]) -> Outcome {
struct DirectoryWalker<'a> {
params: &'a Params,
option_args: &'a [OsString],
/// Canonical paths of the directories being compared, from the top, to
/// detect symbolic links looping back to one of them.
ancestors: Vec<PathBuf>,
/// Canonical paths of the pairs of directories being compared, from the
/// top, to detect symbolic links looping back to one of them. A directory
/// missing on purpose (-N) has none.
ancestors: Vec<[Option<PathBuf>; 2]>,
}

impl DirectoryWalker<'_> {
fn compare_directories(&mut self, from_dir: &OsStr, to_dir: &OsStr) -> Outcome {
let mut outcome = Outcome::Identical;
let mut canonical_dirs = Vec::new();
for dir in [from_dir, to_dir] {
let Ok(canonical) = fs::canonicalize(dir) else {
// A directory missing on purpose (-N) has no entries.
continue;
};
if self.ancestors.contains(&canonical) {
let dirs = [from_dir, to_dir];
let canonical_dirs = dirs.map(|dir| fs::canonicalize(dir).ok());
// A side is checked against its own ancestors only. As long as the
// other side is a directory that is not one of its ancestors, that
// side's finite tree ends the recursion.
let loops = |side: usize| {
canonical_dirs[side].as_ref().is_none_or(|dir| {
let mut ancestors = self.ancestors.iter().map(|pair| pair[side].as_ref());
ancestors.any(|ancestor| ancestor == Some(dir))
})
};
if loops(0) && loops(1) {
// Named after the first side that exists, as one may be missing (-N)
if let Some(side) = canonical_dirs.iter().position(Option::is_some) {
eprintln!(
"{}: {}: recursive directory loop",
self.params.executable.to_string_lossy(),
dir.to_string_lossy()
dirs[side].to_string_lossy()
);
return Outcome::Trouble;
}
canonical_dirs.push(canonical);
}
let (Some(mut from_names), Some(mut to_names)) = (self.list(from_dir), self.list(to_dir))
else {
Expand All @@ -71,8 +78,7 @@ impl DirectoryWalker<'_> {
from_names.retain(|name| *self.name_key(name) >= *start);
to_names.retain(|name| *self.name_key(name) >= *start);
}
let ancestors_len = self.ancestors.len();
self.ancestors.extend(canonical_dirs);
self.ancestors.push(canonical_dirs);

let entries = pair_entries(&from_names, &to_names, |from, to| {
self.name_key(from).cmp(&self.name_key(to))
Expand All @@ -95,7 +101,7 @@ impl DirectoryWalker<'_> {
};
outcome = outcome.max(entry_outcome);
}
self.ancestors.truncate(ancestors_len);
self.ancestors.pop();
outcome
}

Expand Down
51 changes: 51 additions & 0 deletions tests/by-util/test_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,57 @@ fn compare_directories_special_entries() -> Result<(), Box<dyn std::error::Error
Ok(())
}

// A link back to a parent is only a loop when the other side loops too, or
// has nothing there: a real directory on the other side ends the recursion.
#[cfg(unix)]
#[test]
fn recursive_loop_on_one_side_only() -> Result<(), Box<dyn std::error::Error>> {
use std::os::unix::fs::symlink;

let tmp_dir = tempdir()?;
let dir = tmp_dir.path();
std::fs::create_dir_all(dir.join("one/sub"))?;
std::fs::create_dir_all(dir.join("two/sub/loop"))?;
symlink("..", dir.join("one/sub/loop"))?;

for (from, to) in [("one", "two"), ("two", "one")] {
let mut cmd = cargo_bin_cmd!("diffutils");
cmd.current_dir(dir).arg("diff").arg("-r").arg(from).arg(to);
cmd.assert()
.code(predicate::eq(1))
.stdout("Only in one/sub/loop: sub\n")
.stderr("");
}

// With -N a missing directory is compared as an empty one, which would
// never end the recursion.
std::fs::remove_dir(dir.join("two/sub/loop"))?;
for (from, to) in [("one", "two"), ("two", "one")] {
let mut cmd = cargo_bin_cmd!("diffutils");
cmd.current_dir(dir).arg("diff").arg("-r").arg("-N");
cmd.arg(from).arg(to);
cmd.assert()
.code(predicate::eq(2))
.stderr("diff: one/sub/loop: recursive directory loop\n");
}

// Each side is checked against its own ancestors: here the links lead to
// the top of the other side, and only loop one level further down.
std::fs::remove_file(dir.join("one/sub/loop"))?;
symlink("../../two", dir.join("one/sub/loop"))?;
symlink("../../one", dir.join("two/sub/loop"))?;
let mut cmd = cargo_bin_cmd!("diffutils");
cmd.current_dir(dir)
.arg("diff")
.arg("-r")
.arg("one")
.arg("two");
cmd.assert()
.code(predicate::eq(2))
.stderr("diff: one/sub/loop/sub/loop: recursive directory loop\n");
Ok(())
}

#[test]
fn directory_name_matching() -> Result<(), Box<dyn std::error::Error>> {
let tmp_dir = tempdir()?;
Expand Down
Loading