fix(tools): h5rs diff compares soft links by target, like h5diff

An OBJ that was a soft link was resolved and its target object compared,
so two files whose /g/s both point at /z differed when /z did: exit 1,
where h5diff (without --follow-symlinks) compares the links' target paths
and exits 0.

A soft link is now compared as a link wherever it is, OBJ included.
--follow-symlinks compares the objects soft links lead to instead, walks
into soft-linked groups, resolves relative targets against the link's
group, and treats two dangling links as the same; exit codes equal
h5diff's on 14 cases. External links are never followed (documented).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
osobh
2026-09-26 01:18:13 -05:00
co-authored by Claude Opus 5.5
parent f325d111f3
commit b5e43bacd7
5 changed files with 155 additions and 17 deletions
+79 -7
View File
@@ -18,10 +18,14 @@ usage: h5rs diff [options] FILE1 FILE2 [OBJ1 [OBJ2]]
Compare FILE1 and FILE2 (or OBJ1 in FILE1 with OBJ2 in FILE2, and everything
below them): the objects present, their kinds, datatypes, shapes, attribute
sets and values, and soft/external link targets.
sets and values, and soft/external link targets (an OBJ that is itself a
soft link is compared as a link, as h5diff does, unless --follow-symlinks).
-r, --report list every differing element (position, values, difference)
-q, --quiet print nothing; only the exit status
--follow-symlinks compare the objects soft links lead to (and walk into
soft-linked groups) instead of the links' target paths;
two dangling links are the same
-d, --delta D numbers differ only when |a - b| > D
-p, --relative R numbers differ only when |a - b| / |a| > R (an R below
the f64 epsilon, 2.2e-16, compares exactly, as h5diff)
@@ -46,6 +50,8 @@ struct Opts {
quiet: bool,
tol: Tol,
count: usize,
/// Compare the objects soft links lead to, not the links' targets.
follow: bool,
}
/// What a relative path names in one file.
@@ -108,6 +114,7 @@ pub fn run(args: &mut Args, out: &mut Out) -> std::io::Result<i32> {
quiet: false,
tol: Tol::Exact,
count: usize::MAX,
follow: false,
};
let mut max_bytes = None;
let mut pos = Vec::new();
@@ -115,6 +122,7 @@ pub fn run(args: &mut Args, out: &mut Out) -> std::io::Result<i32> {
match a.as_str() {
"-r" | "--report" => opts.report = true,
"-q" | "--quiet" => opts.quiet = true,
"--follow-symlinks" => opts.follow = true,
"-d" | "--delta" => match args.number::<f64>() {
Some(d) if d >= 0.0 => opts.tol = Tol::Delta(d),
_ => return args.usage_error(out, "--delta needs a number >= 0", USAGE),
@@ -171,8 +179,8 @@ pub fn run(args: &mut Args, out: &mut Out) -> std::io::Result<i32> {
let obj2 = pos.get(3).cloned().unwrap_or_else(|| obj1.clone());
let mut sides = Vec::new();
for (h5, (obj, f)) in files.iter().zip([(&obj1, &pos[0]), (&obj2, &pos[1])]) {
let addr = match h5.resolve(obj) {
Ok(a) => a,
let start = match start(h5, obj, opts.follow) {
Ok(x) => x,
Err(_) => {
writeln!(
out.e,
@@ -187,7 +195,11 @@ pub fn run(args: &mut Args, out: &mut Out) -> std::io::Result<i32> {
} else {
format!("/{base}")
};
let entries = match collect(h5, addr) {
let collected = match start {
Start::Obj(addr) => collect(h5, addr, &base, opts.follow),
Start::Link(e) => Ok(BTreeMap::from([(String::new(), e)])),
};
let entries = match collected {
Ok(e) => e,
Err(e) => {
writeln!(out.e, "h5rs diff: {f}: {e}")?;
@@ -246,6 +258,51 @@ pub fn run(args: &mut Args, out: &mut Out) -> std::io::Result<i32> {
})
}
/// What OBJ1/OBJ2 names.
enum Start {
Obj(u64),
/// A soft (not followed, or dangling), external or user-defined link.
Link(Entry),
}
/// Resolve OBJ1/OBJ2. Soft links on the way to it are followed, as in any
/// HDF5 path; a soft link that *is* the named object is compared as a link
/// (its target path), as h5diff does, unless `follow`.
fn start(h5: &H5, obj: &str, follow: bool) -> crate::h5::Result<Start> {
let p = obj.trim_matches('/');
if !p.is_empty() {
let (parent, name) = p.rsplit_once('/').unwrap_or(("", p));
let link = h5
.resolve(parent)
.and_then(|a| h5.header(a))
.and_then(|h| h5.links(&h))
.ok()
.and_then(|ls| ls.into_iter().find(|l| l.name == name));
if let Some(l) = link {
return Ok(match l.kind {
LinkKind::Hard(a) => Start::Obj(a),
LinkKind::Soft(t) if follow => match soft_target(h5, &format!("/{parent}"), &t) {
Ok(a) => Start::Obj(a),
Err(_) => Start::Link(Entry::Soft(t)),
},
LinkKind::Soft(t) => Start::Link(Entry::Soft(t)),
LinkKind::External { file, path } => Start::Link(Entry::External(file, path)),
LinkKind::UserDefined(t) => Start::Link(Entry::UserDefined(t)),
});
}
}
h5.resolve(obj).map(Start::Obj)
}
/// The object a soft link in group `parent` (an absolute path) leads to.
fn soft_target(h5: &H5, parent: &str, target: &str) -> crate::h5::Result<u64> {
if target.starts_with('/') {
h5.resolve(target)
} else {
h5.resolve(&format!("{}/{target}", parent.trim_end_matches('/')))
}
}
/// One object as the path walk sees it: what its paths compare as, and
/// (for a group) its links.
struct Node {
@@ -258,8 +315,15 @@ struct Node {
/// names is compared under both, with everything below it: two files that
/// hold the same values are equal whether one shares an object between
/// names and the other stores copies. A hard link back to an ancestor (a
/// cycle) is recorded, not descended into.
fn collect(h5: &H5, start: u64) -> crate::h5::Result<BTreeMap<String, Entry>> {
/// cycle) is recorded, not descended into. With `follow`, a soft link is
/// walked like a hard link to its target (a dangling one stays a link);
/// `base` is the absolute path of `start`, for relative link targets.
fn collect(
h5: &H5,
start: u64,
base: &str,
follow: bool,
) -> crate::h5::Result<BTreeMap<String, Entry>> {
let mut cache: HashMap<u64, Rc<Node>> = HashMap::new();
let mut node = |addr: u64| -> Rc<Node> {
cache
@@ -313,6 +377,12 @@ fn collect(h5: &H5, start: u64) -> crate::h5::Result<BTreeMap<String, Entry>> {
let child = format!("{path}/{}", l.name);
match &l.kind {
LinkKind::Hard(a) => stack.push((*a, child, chain.clone())),
LinkKind::Soft(t) if follow => match soft_target(h5, &format!("{base}{path}"), t) {
Ok(a) => stack.push((a, child, chain.clone())),
Err(_) => {
entries.insert(child, Entry::Soft(t.clone()));
}
},
LinkKind::Soft(t) => {
entries.insert(child, Entry::Soft(t.clone()));
}
@@ -365,7 +435,9 @@ impl Diff {
(Entry::Broken(e), _) => self.error(out, &format!("<{pa}> in <{}>: {e}", a.label)),
(_, Entry::Broken(e)) => self.error(out, &format!("<{pb}> in <{}>: {e}", b.label)),
(Entry::Soft(x), Entry::Soft(y)) => {
if x != y {
// Followed links that are left are dangling on both sides,
// which h5diff counts as the same.
if x != y && !self.opts.follow {
self.diffs += 1;
self.say(out, &format!("soft link: <{pa}> -> {x} and <{pb}> -> {y}"))?;
}