ctb_io_csc/
diff_engine.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Filesystem diffing engine comparing two filesystem trees or files using
21//! the exact same strictness and metadata verification rules as `csc copy`.
22
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use crate::args::{CscDiffArgs, VerifyOutputFormat};
31use crate::verifier::{
32    EntryDiff, VerificationReport, VerificationReportKind,
33    audit_entries_against_target, build_audit_caveats,
34    check_cache_flush_privileges, normalize_rel_path, scan_disk_entries,
35};
36use ctb_io::file::entity::{FileEntity, FileEntityKind};
37use ctb_io::file::identity::extract_file_identity;
38use ctb_io::file::link_path::LinkPath;
39use ctb_io::file::verifier::{
40    DiffKind, audit_entity_detailed, try_drop_system_caches,
41};
42use ctb_utilities::cli::ToolResult;
43use std::collections::{HashMap, HashSet};
44use std::path::{Path, PathBuf};
45
46/// Compares two filesystem paths and generates a `VerificationReport` with `VerificationReportKind::PathDiff`.
47#[expect(
48    clippy::too_many_lines,
49    reason = "Comprehensive diff covering file-vs-file, dir-vs-dir, and file-vs-dir"
50)]
51pub fn diff_paths(args: &CscDiffArgs) -> Result<VerificationReport> {
52    let path_a = &args.path_a;
53    let path_b = &args.path_b;
54
55    let meta_a = std::fs::symlink_metadata(path_a).with_context(|| {
56        format!("Path A does not exist: {}", path_a.display())
57    })?;
58    let meta_b = std::fs::symlink_metadata(path_b).with_context(|| {
59        format!("Path B does not exist: {}", path_b.display())
60    })?;
61
62    if args.should_drop_caches() {
63        check_cache_flush_privileges();
64        try_drop_system_caches();
65    }
66
67    let audit_options = args.to_audit_options();
68    let apple_read_options = args.resolve_apple_read_options();
69    let is_best_effort = args.best_effort && !args.strict;
70
71    let is_dir_a = meta_a.is_dir();
72    let is_dir_b = meta_b.is_dir();
73
74    match (is_dir_a, is_dir_b) {
75        // Case 1: Both paths are directory trees
76        (true, true) => {
77            let traversal_opts = ctb_io::file::TraversalOptions::new()
78                .yield_root(true)
79                .one_file_system(args.one_file_system)
80                .error_policy(ctb_io::file::OnTraversalError::Bail)
81                .apple_read_options(apple_read_options);
82
83            let mut expected_entries: Vec<(PathBuf, FileEntity)> = Vec::new();
84            let mut seen_hardlinks: HashMap<ctb_io::file::InodeKey, PathBuf> =
85                HashMap::new();
86
87            for item in ctb_io::file::traverse_dir(path_a, traversal_opts)? {
88                let item = item.with_context(|| {
89                    format!(
90                        "Failed during traversal of Path A: {}",
91                        path_a.display()
92                    )
93                })?;
94                let rel = item.relative_path().to_path_buf();
95
96                if rel.as_os_str().is_empty() || rel == Path::new(".") {
97                    let root_entity = FileEntity::from_filesystem_metadata_only_with_apple_options(
98                        path_a,
99                        None,
100                        &apple_read_options,
101                    )?;
102                    expected_entries.push((PathBuf::from("."), root_entity));
103                    continue;
104                }
105
106                let full_item_path = item.path();
107                let sym_meta = item.symlink_metadata.as_ref();
108
109                // Track hardlinks in tree A
110                let mut is_hardlink_to = None;
111                if item.is_dir {
112                    // Directories are not hardlinked
113                } else if let Some(m) = sym_meta {
114                    if let Ok(ident) = extract_file_identity(full_item_path, m)
115                    {
116                        if let Some(first_rel) = seen_hardlinks.get(&ident) {
117                            is_hardlink_to = Some(first_rel.clone());
118                        } else {
119                            seen_hardlinks.insert(ident, rel.clone());
120                        }
121                    }
122                }
123
124                if let Some(first_rel) = is_hardlink_to {
125                    let mut hardlink_entity = FileEntity::from_filesystem_metadata_only_with_apple_options(
126                        full_item_path,
127                        Some(path_a),
128                        &apple_read_options,
129                    )?;
130                    hardlink_entity.kind = FileEntityKind::Hardlink {
131                        target_relative_path: LinkPath::from_relative_path(
132                            &first_rel,
133                        )?,
134                    };
135                    expected_entries.push((rel, hardlink_entity));
136                } else {
137                    let entity =
138                        FileEntity::from_filesystem_with_apple_options(
139                            full_item_path,
140                            Some(path_a),
141                            &apple_read_options,
142                        )?;
143                    expected_entries.push((rel, entity));
144                }
145            }
146
147            let total_manifest_entries = expected_entries
148                .iter()
149                .filter(|(rel, entity)| {
150                    if matches!(entity.kind, FileEntityKind::Directory) {
151                        !rel.as_os_str().is_empty() && rel != Path::new(".")
152                    } else {
153                        true
154                    }
155                })
156                .count();
157
158            let pass = audit_entries_against_target(
159                path_b,
160                expected_entries,
161                &audit_options,
162                !is_best_effort,
163            )?;
164
165            let mut changed_entries = pass.changed_entries;
166            let mut missing_entries = pass.missing_entries;
167            let matched_entries = pass.matched_entries;
168            let verified_paths = pass.verified_paths;
169            let total_ignored = pass.total_ignored;
170
171            // Untracked / extra entries in Path B
172            let mut untracked_entries = Vec::new();
173            let mut total_disk_scanned = 0_usize;
174
175            if !args.should_ignore_untracked() {
176                let disk_entries = scan_disk_entries(path_b, None)?;
177                total_disk_scanned = disk_entries.len();
178
179                for disk_rel in disk_entries {
180                    let norm = normalize_rel_path(&disk_rel);
181                    if !verified_paths.contains(&norm) {
182                        untracked_entries.push(disk_rel);
183                    }
184                }
185            }
186
187            changed_entries
188                .sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
189            missing_entries.sort();
190            untracked_entries.sort();
191
192            let caveats = build_audit_caveats(
193                &audit_options,
194                args.should_ignore_untracked(),
195                args.should_drop_caches(),
196                is_best_effort,
197                &total_ignored,
198            );
199
200            Ok(VerificationReport {
201                report_kind: VerificationReportKind::PathDiff,
202                target_directory: path_b.clone(),
203                manifest_path: path_a.clone(),
204                total_manifest_entries,
205                total_disk_entries_scanned: total_disk_scanned,
206                matched_entries,
207                changed_entries,
208                missing_entries,
209                untracked_entries,
210                ignored_differences: total_ignored,
211                best_effort: is_best_effort,
212                caveats,
213                recorded_errors: Vec::new(),
214            })
215        }
216
217        // Case 2: Both paths are non-directories (regular files, symlinks, FIFOs)
218        (false, false) => {
219            let entity_a = FileEntity::from_filesystem_with_apple_options(
220                path_a,
221                None,
222                &apple_read_options,
223            )?;
224
225            let (diffs, ignored) =
226                audit_entity_detailed(path_b, &entity_a, &audit_options)?;
227
228            let mut matched_entries = 0_usize;
229            let mut changed_entries = Vec::new();
230
231            if diffs.is_empty() {
232                matched_entries = 1;
233            } else {
234                changed_entries.push(EntryDiff {
235                    relative_path: path_b.clone(),
236                    differences: diffs,
237                });
238            }
239
240            let caveats = build_audit_caveats(
241                &audit_options,
242                args.should_ignore_untracked(),
243                args.should_drop_caches(),
244                is_best_effort,
245                &ignored,
246            );
247
248            Ok(VerificationReport {
249                report_kind: VerificationReportKind::PathDiff,
250                target_directory: path_b.clone(),
251                manifest_path: path_a.clone(),
252                total_manifest_entries: 1,
253                total_disk_entries_scanned: 1,
254                matched_entries,
255                changed_entries,
256                missing_entries: Vec::new(),
257                untracked_entries: Vec::new(),
258                ignored_differences: ignored,
259                best_effort: is_best_effort,
260                caveats,
261                recorded_errors: Vec::new(),
262            })
263        }
264
265        // Case 3: Path A is a file and Path B is a container directory
266        (false, true) => {
267            let file_name = path_a
268                .file_name()
269                .context("Path A has no file name component")?;
270            let target_in_b = path_b.join(file_name);
271
272            let entity_a = FileEntity::from_filesystem_with_apple_options(
273                path_a,
274                None,
275                &apple_read_options,
276            )?;
277
278            let mut matched_entries = 0_usize;
279            let mut changed_entries = Vec::new();
280            let mut missing_entries = Vec::new();
281            let mut total_ignored =
282                crate::verifier::IgnoredDifferences::default();
283
284            if target_in_b.exists() {
285                let (diffs, ignored) = audit_entity_detailed(
286                    &target_in_b,
287                    &entity_a,
288                    &audit_options,
289                )?;
290                total_ignored = ignored;
291                if diffs.is_empty() {
292                    matched_entries = 1;
293                } else {
294                    changed_entries.push(EntryDiff {
295                        relative_path: PathBuf::from(file_name),
296                        differences: diffs,
297                    });
298                }
299            } else {
300                missing_entries.push(PathBuf::from(file_name));
301            }
302
303            let mut untracked_entries = Vec::new();
304            let mut total_disk_scanned = 0_usize;
305
306            if !args.should_ignore_untracked() {
307                let disk_entries = scan_disk_entries(path_b, None)?;
308                total_disk_scanned = disk_entries.len();
309                let expected_rel = PathBuf::from(file_name);
310                for disk_rel in disk_entries {
311                    if disk_rel != expected_rel {
312                        untracked_entries.push(disk_rel);
313                    }
314                }
315                untracked_entries.sort();
316            }
317
318            let caveats = build_audit_caveats(
319                &audit_options,
320                args.should_ignore_untracked(),
321                args.should_drop_caches(),
322                is_best_effort,
323                &total_ignored,
324            );
325
326            Ok(VerificationReport {
327                report_kind: VerificationReportKind::PathDiff,
328                target_directory: path_b.clone(),
329                manifest_path: path_a.clone(),
330                total_manifest_entries: 1,
331                total_disk_entries_scanned: total_disk_scanned,
332                matched_entries,
333                changed_entries,
334                missing_entries,
335                untracked_entries,
336                ignored_differences: total_ignored,
337                best_effort: is_best_effort,
338                caveats,
339                recorded_errors: Vec::new(),
340            })
341        }
342
343        // Case 4: Path A is a directory and Path B is a file (incompatible types)
344        (true, false) => {
345            let caveats = build_audit_caveats(
346                &audit_options,
347                args.should_ignore_untracked(),
348                args.should_drop_caches(),
349                is_best_effort,
350                &crate::verifier::IgnoredDifferences::default(),
351            );
352
353            Ok(VerificationReport {
354                report_kind: VerificationReportKind::PathDiff,
355                target_directory: path_b.clone(),
356                manifest_path: path_a.clone(),
357                total_manifest_entries: 1,
358                total_disk_entries_scanned: 1,
359                matched_entries: 0,
360                changed_entries: vec![EntryDiff {
361                    relative_path: PathBuf::from("."),
362                    differences: vec![DiffKind::TypeMismatch {
363                        expected: "directory".to_string(),
364                        actual: "regular file".to_string(),
365                    }],
366                }],
367                missing_entries: Vec::new(),
368                untracked_entries: Vec::new(),
369                ignored_differences:
370                    crate::verifier::IgnoredDifferences::default(),
371                best_effort: is_best_effort,
372                caveats,
373                recorded_errors: Vec::new(),
374            })
375        }
376    }
377}
378
379/// Main orchestration entry point for the `csc-diff` CLI command.
380pub fn run_csc_diff(args: &CscDiffArgs) -> Result<ToolResult> {
381    let _env_scope = if args.full_provenance {
382        ctb_io_environment::GlobalEnvironmentScope::enter_full()
383    } else {
384        ctb_io_environment::GlobalEnvironmentScope::enter_fresh()
385    };
386
387    let report = diff_paths(args)?;
388
389    let exit_code = i32::from(!report.is_clean());
390
391    if args.quiet && report.is_clean() {
392        return Ok(ToolResult::Immediate {
393            stdout: Vec::new(),
394            stderr: Vec::new(),
395            exit_code: 0,
396        });
397    }
398
399    let output_str = match args.format {
400        VerifyOutputFormat::Text => report.format_human_report(),
401        VerifyOutputFormat::Json => report.format_json_report()?,
402    };
403
404    Ok(ToolResult::Immediate {
405        stdout: output_str.into_bytes(),
406        stderr: Vec::new(),
407        exit_code,
408    })
409}
410
411#[cfg(test)]
412#[allow(
413    clippy::panic,
414    clippy::expect_used,
415    clippy::unwrap_used,
416    clippy::unwrap_in_result,
417    clippy::panic_in_result_fn,
418    clippy::indexing_slicing,
419    clippy::arithmetic_side_effects,
420    reason = "Standard repository test boilerplate"
421)]
422mod tests {
423    use super::*;
424    use crate::args::default_diff_args;
425    use std::fs;
426    use tempfile::tempdir;
427
428    /// Synchronizes timestamps (including Windows `CreationTime` / `birthtime`)
429    /// from `src` onto `dst` so independently created test fixtures do not fail
430    /// strict `birthtime` checks when a clock tick separates two `fs::write`s.
431    fn sync_fixture_timestamps(src: &Path, dst: &Path) {
432        let entity =
433            FileEntity::from_filesystem_metadata_only(src, None).unwrap();
434        ctb_io::file::apply_entity_metadata(
435            dst,
436            None,
437            &entity.metadata,
438            false,
439            false,
440            false,
441            cfg!(windows),
442        )
443        .unwrap();
444    }
445
446    #[crate::ctb_test]
447    fn test_diff_identical_files() {
448        let temp = tempdir().unwrap();
449        let file_a = temp.path().join("a.txt");
450        let file_b = temp.path().join("b.txt");
451        fs::write(&file_a, b"content 123").unwrap();
452        fs::write(&file_b, b"content 123").unwrap();
453
454        sync_fixture_timestamps(&file_a, &file_b);
455
456        let args = default_diff_args(file_a, file_b);
457        let report = diff_paths(&args).unwrap();
458        assert!(report.is_clean());
459        assert_eq!(report.matched_entries, 1);
460        assert_eq!(report.changed_entries.len(), 0);
461    }
462
463    #[crate::ctb_test]
464    fn test_diff_modified_file_payload() {
465        let temp = tempdir().unwrap();
466        let file_a = temp.path().join("a.txt");
467        let file_b = temp.path().join("b.txt");
468        fs::write(&file_a, b"content 123").unwrap();
469        fs::write(&file_b, b"content 456").unwrap();
470
471        let args = default_diff_args(file_a, file_b);
472        let report = diff_paths(&args).unwrap();
473        assert!(!report.is_clean());
474        assert_eq!(report.changed_entries.len(), 1);
475        let diffs = &report.changed_entries[0].differences;
476        assert!(
477            diffs
478                .iter()
479                .any(|d| matches!(d, DiffKind::ContentHashMismatch { .. }))
480        );
481    }
482
483    #[crate::ctb_test]
484    fn test_diff_identical_directories() {
485        let temp = tempdir().unwrap();
486        let dir_a = temp.path().join("dir_a");
487        let dir_b = temp.path().join("dir_b");
488        fs::create_dir(&dir_a).unwrap();
489        fs::create_dir(&dir_b).unwrap();
490
491        fs::write(dir_a.join("f1.txt"), b"file 1").unwrap();
492        fs::write(dir_b.join("f1.txt"), b"file 1").unwrap();
493
494        sync_fixture_timestamps(&dir_a.join("f1.txt"), &dir_b.join("f1.txt"));
495        sync_fixture_timestamps(&dir_a, &dir_b);
496
497        let mut args = default_diff_args(dir_a, dir_b);
498        args.criteria.ignore_mtime = true;
499
500        let report = diff_paths(&args).unwrap();
501        assert!(report.is_clean());
502        assert_eq!(report.matched_entries, 1);
503        assert_eq!(report.missing_entries.len(), 0);
504        assert_eq!(report.untracked_entries.len(), 0);
505    }
506
507    #[crate::ctb_test]
508    fn test_diff_directories_with_missing_and_extra_entries() {
509        let temp = tempdir().unwrap();
510        let dir_a = temp.path().join("dir_a");
511        let dir_b = temp.path().join("dir_b");
512        fs::create_dir(&dir_a).unwrap();
513        fs::create_dir(&dir_b).unwrap();
514
515        fs::write(dir_a.join("common.txt"), b"common").unwrap();
516        fs::write(dir_b.join("common.txt"), b"common").unwrap();
517        fs::write(dir_a.join("only_in_a.txt"), b"a").unwrap();
518        fs::write(dir_b.join("only_in_b.txt"), b"b").unwrap();
519
520        sync_fixture_timestamps(
521            &dir_a.join("common.txt"),
522            &dir_b.join("common.txt"),
523        );
524        sync_fixture_timestamps(&dir_a, &dir_b);
525
526        let mut args = default_diff_args(dir_a, dir_b);
527        args.criteria.ignore_mtime = true;
528
529        let report = diff_paths(&args).unwrap();
530        assert!(!report.is_clean());
531        assert_eq!(report.matched_entries, 1);
532        assert_eq!(
533            report.missing_entries,
534            vec![PathBuf::from("only_in_a.txt")]
535        );
536        assert_eq!(
537            report.untracked_entries,
538            vec![PathBuf::from("only_in_b.txt")]
539        );
540    }
541
542    #[crate::ctb_test]
543    fn test_diff_directory_ignore_untracked() {
544        let temp = tempdir().unwrap();
545        let dir_a = temp.path().join("dir_a");
546        let dir_b = temp.path().join("dir_b");
547        fs::create_dir(&dir_a).unwrap();
548        fs::create_dir(&dir_b).unwrap();
549
550        fs::write(dir_a.join("common.txt"), b"common").unwrap();
551        fs::write(dir_b.join("common.txt"), b"common").unwrap();
552        fs::write(dir_b.join("extra.txt"), b"extra").unwrap();
553
554        sync_fixture_timestamps(
555            &dir_a.join("common.txt"),
556            &dir_b.join("common.txt"),
557        );
558        sync_fixture_timestamps(&dir_a, &dir_b);
559
560        let mut args = default_diff_args(dir_a, dir_b);
561        args.criteria.ignore_mtime = true;
562        args.criteria.ignore_untracked = true;
563
564        let report = diff_paths(&args).unwrap();
565        assert!(report.is_clean());
566        assert_eq!(report.untracked_entries.len(), 0);
567    }
568
569    #[cfg(unix)]
570    #[crate::ctb_test]
571    fn test_diff_hardlink_preservation() {
572        let temp = tempdir().unwrap();
573        let dir_a = temp.path().join("dir_a");
574        let dir_b = temp.path().join("dir_b");
575        fs::create_dir(&dir_a).unwrap();
576        fs::create_dir(&dir_b).unwrap();
577
578        let f1_a = dir_a.join("file1");
579        let f2_a = dir_a.join("file2");
580        fs::write(&f1_a, b"hardlink data").unwrap();
581        fs::hard_link(&f1_a, &f2_a).unwrap();
582
583        // In dir_b, create two separate files (not hardlinks) with same content
584        let f1_b = dir_b.join("file1");
585        let f2_b = dir_b.join("file2");
586        fs::write(&f1_b, b"hardlink data").unwrap();
587        fs::write(&f2_b, b"hardlink data").unwrap();
588
589        let mut args = default_diff_args(dir_a, dir_b);
590        args.criteria.ignore_mtime = true;
591
592        let report = diff_paths(&args).unwrap();
593        assert!(!report.is_clean());
594        // file2 should fail hardlink check because in B they are separate inodes
595        assert!(report.changed_entries.iter().any(|e| {
596            e.differences
597                .iter()
598                .any(|d| matches!(d, DiffKind::HardlinkMismatch { .. }))
599        }));
600    }
601
602    #[crate::ctb_test]
603    fn test_run_csc_diff_exit_codes_and_formatting() {
604        let temp = tempdir().unwrap();
605        let f_a = temp.path().join("a.txt");
606        let f_b = temp.path().join("b.txt");
607        fs::write(&f_a, b"match").unwrap();
608        fs::write(&f_b, b"match").unwrap();
609        sync_fixture_timestamps(&f_a, &f_b);
610
611        let mut args = default_diff_args(f_a.clone(), f_b.clone());
612        args.criteria.ignore_mtime = true;
613
614        let res = run_csc_diff(&args).unwrap();
615        match res {
616            ToolResult::Immediate {
617                exit_code, stdout, ..
618            } => {
619                assert_eq!(exit_code, 0);
620                let out = String::from_utf8_lossy(&stdout);
621                assert!(out.contains("--- CSC Diff Report ---"));
622                assert!(out.contains("Status:           OK - Paths match."));
623            }
624            ToolResult::Streaming { .. } => {
625                panic!("Expected Immediate ToolResult")
626            }
627        }
628
629        // Test quiet mode
630        args.quiet = true;
631        let res_quiet = run_csc_diff(&args).unwrap();
632        match res_quiet {
633            ToolResult::Immediate {
634                exit_code, stdout, ..
635            } => {
636                assert_eq!(exit_code, 0);
637                assert!(stdout.is_empty());
638            }
639            ToolResult::Streaming { .. } => {
640                panic!("Expected Immediate ToolResult")
641            }
642        }
643
644        // Alter file B
645        fs::write(&f_b, b"changed").unwrap();
646        args.quiet = false;
647        let res_fail = run_csc_diff(&args).unwrap();
648        match res_fail {
649            ToolResult::Immediate {
650                exit_code, stdout, ..
651            } => {
652                assert_eq!(exit_code, 1);
653                let out = String::from_utf8_lossy(&stdout);
654                assert!(out.contains("Status:           FAILED - Discrepancies detected between paths."));
655                assert!(out.contains("Changed Entries (1):"));
656            }
657            ToolResult::Streaming { .. } => {
658                panic!("Expected Immediate ToolResult")
659            }
660        }
661    }
662}