anodizer-core 0.15.3

Core configuration, context, and template engine for the anodizer release tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
use std::collections::{HashMap, HashSet, VecDeque};
use std::fs;
use std::path::Path;
use std::time::{Duration, SystemTime};

use anyhow::{Context as _, Result};

/// Compile a regex, panicking with a diagnostic if the pattern is invalid.
/// Intended for `LazyLock::new(…)` initializers where the pattern is a
/// hardcoded literal (or built from `format!` over known-safe fragments).
/// A compile failure means a programmer bug surfaced at first use, not a
/// runtime-path user-input error. Exists because the anti-pattern hook
/// forbids bare panicking error helpers in lib code, and `Regex::new` on
/// a trusted literal is inherently infallible.
pub fn static_regex(pattern: &str) -> regex::Regex {
    regex::Regex::new(pattern)
        .unwrap_or_else(|e| panic!("invalid static regex literal `{}`: {}", pattern, e))
}

// ---------------------------------------------------------------------------
// Topological sort (Kahn's algorithm)
// ---------------------------------------------------------------------------

/// Topologically sort items by their dependency lists.
///
/// Input: slice of `(name, depends_on)` pairs.
/// Output: names in dependency order (dependencies before dependents).
///
/// - Dependencies that are not in the input set are silently ignored.
/// - Deterministic: zero-in-degree nodes are sorted alphabetically.
/// - On cycles: sorted nodes are returned followed by remaining nodes in
///   their original order.
pub fn topological_sort(items: &[(impl AsRef<str>, impl AsRef<[String]>)]) -> Vec<String> {
    let names: HashSet<&str> = items.iter().map(|(n, _)| n.as_ref()).collect();

    let mut in_degree: HashMap<&str, usize> = items
        .iter()
        .map(|(n, deps)| {
            let deg = deps
                .as_ref()
                .iter()
                .filter(|d| names.contains(d.as_str()))
                .count();
            (n.as_ref(), deg)
        })
        .collect();

    // edges: dep → list of dependents
    let mut edges: HashMap<&str, Vec<&str>> = HashMap::new();
    for (n, deps) in items {
        for dep in deps.as_ref() {
            if names.contains(dep.as_str()) {
                edges.entry(dep.as_str()).or_default().push(n.as_ref());
            }
        }
    }

    // Kahn's algorithm with deterministic seed ordering
    let mut queue: VecDeque<&str> = {
        let mut v: Vec<&str> = in_degree
            .iter()
            .filter(|(_, d)| **d == 0)
            .map(|(&n, _)| n)
            .collect();
        v.sort_unstable();
        VecDeque::from(v)
    };

    let mut result = Vec::with_capacity(items.len());
    while let Some(node) = queue.pop_front() {
        result.push(node.to_string());
        if let Some(dependents) = edges.get(node) {
            let mut next: Vec<&str> = dependents
                .iter()
                .filter_map(|&dep| {
                    let deg = in_degree.get_mut(dep)?;
                    *deg -= 1;
                    if *deg == 0 { Some(dep) } else { None }
                })
                .collect();
            next.sort_unstable();
            for n in next {
                queue.push_back(n);
            }
        }
    }

    // Append remaining (cycle case) in original order.
    if result.len() < items.len() {
        let in_result: HashSet<String> = result.iter().cloned().collect();
        for (n, _) in items {
            if !in_result.contains(n.as_ref()) {
                result.push(n.as_ref().to_string());
            }
        }
    }

    result
}

// ---------------------------------------------------------------------------
// apply_mod_timestamp
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// mod_timestamp helpers
// ---------------------------------------------------------------------------

/// Parse a `mod_timestamp` string into a `SystemTime`.
///
/// Accepts:
///   - Unix epoch seconds as an integer (e.g. `"1704067200"`)
///   - RFC 3339 / ISO 8601 datetime (e.g. `"2024-01-01T00:00:00Z"`)
pub fn parse_mod_timestamp(raw: &str) -> Result<SystemTime> {
    // Try Unix epoch integer first (most common in CI)
    if let Ok(epoch_secs) = raw.parse::<u64>() {
        return Ok(SystemTime::UNIX_EPOCH + Duration::from_secs(epoch_secs));
    }
    // Try RFC 3339 / ISO 8601 via chrono
    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(raw) {
        let epoch_secs = dt.timestamp() as u64;
        return Ok(SystemTime::UNIX_EPOCH + Duration::from_secs(epoch_secs));
    }
    // Try chrono's more lenient parsing for formats like "2024-01-01T00:00:00"
    if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M:%S") {
        let epoch_secs = dt.and_utc().timestamp() as u64;
        return Ok(SystemTime::UNIX_EPOCH + Duration::from_secs(epoch_secs));
    }
    anyhow::bail!(
        "mod_timestamp value '{raw}' is not a valid timestamp. \
         Accepted formats: Unix epoch seconds (e.g. \"1704067200\") or \
         RFC 3339 datetime (e.g. \"2024-01-01T00:00:00Z\")"
    )
}

/// Apply `mod_timestamp` to every regular file in a directory tree.
///
/// Parses the timestamp via `parse_mod_timestamp`, then recurses into
/// subdirectories, setting the mtime on every regular file. Symlinks are not
/// followed and directory mtimes are left untouched (files-only semantics,
/// matching [`pin_dir_mtimes_epoch`], the SDE reproducibility floor this
/// override is layered on top of). A nested staged file — e.g. a
/// `templated_extra_files` entry whose dst is `docs/README.txt` — must receive
/// the user's `mod_timestamp`, not the SDE epoch left by the floor.
pub fn apply_mod_timestamp(dir: &Path, raw: &str, log: &crate::log::StageLogger) -> Result<()> {
    let mtime = parse_mod_timestamp(raw)?;

    let mut stack: Vec<std::path::PathBuf> = vec![dir.to_path_buf()];
    while let Some(p) = stack.pop() {
        for entry in
            fs::read_dir(&p).with_context(|| format!("read staging dir {}", p.display()))?
        {
            let entry = entry?;
            let path = entry.path();
            let ft = entry.file_type()?;
            if ft.is_dir() {
                stack.push(path);
            } else if ft.is_file() {
                set_file_mtime(&path, mtime)?;
            }
        }
    }

    log.status(&format!("applied mod_timestamp={raw} to staging files"));
    Ok(())
}

/// Set the modification time on a single file.
pub fn set_file_mtime(path: &Path, mtime: SystemTime) -> Result<()> {
    let file = std::fs::OpenOptions::new()
        .write(true)
        .open(path)
        .with_context(|| format!("open {} for mtime update", path.display()))?;
    file.set_times(
        std::fs::FileTimes::new()
            .set_accessed(mtime)
            .set_modified(mtime),
    )
    .with_context(|| format!("set mtime on {}", path.display()))?;
    Ok(())
}

/// Set the modification time on a single file from a Unix epoch (seconds).
///
/// Thin wrapper over `set_file_mtime` that accepts `SOURCE_DATE_EPOCH`-style
/// `i64` seconds (signed to permit pre-1970 values per the spec).
pub fn set_file_mtime_epoch(path: &Path, epoch_secs: i64) -> Result<()> {
    let mtime = if epoch_secs >= 0 {
        SystemTime::UNIX_EPOCH + Duration::from_secs(epoch_secs as u64)
    } else {
        SystemTime::UNIX_EPOCH - Duration::from_secs((-epoch_secs) as u64)
    };
    set_file_mtime(path, mtime)
}

/// Recursively pin every regular file's mtime under `dir` to `epoch_secs`
/// (SOURCE_DATE_EPOCH seconds). Packaging tools (makeself's tar, NSIS's `File`)
/// embed each input file's on-disk mtime; `fs::copy` stamps the wall clock, so
/// two harness runs with identical contents drift the packed bytes. Pinning to
/// the build epoch removes that variance.
///
/// Subdirectories are walked; only regular files have their mtime set (mirrors
/// the mtime semantics relevant to the archive headers these tools emit).
pub fn pin_dir_mtimes_epoch(dir: &Path, epoch_secs: i64) -> Result<()> {
    let mut stack: Vec<std::path::PathBuf> = vec![dir.to_path_buf()];
    while let Some(p) = stack.pop() {
        for entry in
            fs::read_dir(&p).with_context(|| format!("read_dir {} for mtime pin", p.display()))?
        {
            let entry = entry?;
            let path = entry.path();
            let ft = entry.file_type()?;
            if ft.is_dir() {
                stack.push(path);
            } else if ft.is_file() {
                set_file_mtime_epoch(&path, epoch_secs)
                    .with_context(|| format!("pin mtime on {}", path.display()))?;
            }
        }
    }
    Ok(())
}

/// Recursively copy the directory tree rooted at `src` into `dst`, recreating
/// subdirectories, copying regular files (with [`fs::copy`], which preserves
/// the Unix mode bits — including the executable bit), and recreating symlinks
/// as symlinks rather than dereferencing them.
///
/// Preserving symlinks matters for macOS app bundles, which embed framework
/// version symlinks (`Versions/Current -> A`); a dereferencing copy would
/// flatten them and bloat the bundle. `dst` (and any missing parents) is
/// created if absent. On non-Unix hosts, where creating a symlink needs
/// elevated rights, the link target's contents are copied instead so the tree
/// stays complete.
pub fn copy_dir_tree(src: &Path, dst: &Path) -> Result<()> {
    fs::create_dir_all(dst).with_context(|| format!("create dir {}", dst.display()))?;
    for entry in fs::read_dir(src).with_context(|| format!("read dir {}", src.display()))? {
        let entry = entry.with_context(|| format!("read entry under {}", src.display()))?;
        let from = entry.path();
        let to = dst.join(entry.file_name());
        // symlink_metadata (via DirEntry::file_type) so a symlink is recreated
        // as a link rather than dereferenced.
        let file_type = entry
            .file_type()
            .with_context(|| format!("stat {}", from.display()))?;
        if file_type.is_symlink() {
            #[cfg(unix)]
            {
                let target = fs::read_link(&from)
                    .with_context(|| format!("read symlink {}", from.display()))?;
                std::os::unix::fs::symlink(&target, &to).with_context(|| {
                    format!("recreate symlink {} -> {}", to.display(), target.display())
                })?;
            }
            #[cfg(not(unix))]
            {
                if from.is_dir() {
                    copy_dir_tree(&from, &to)?;
                } else {
                    fs::copy(&from, &to)
                        .with_context(|| format!("copy {} to {}", from.display(), to.display()))?;
                }
            }
        } else if file_type.is_dir() {
            copy_dir_tree(&from, &to)?;
        } else {
            fs::copy(&from, &to)
                .with_context(|| format!("copy {} to {}", from.display(), to.display()))?;
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// collect_replace_archives
// ---------------------------------------------------------------------------

/// Collect archive artifact paths for a given crate + target, for removal by `replace` options.
pub fn collect_replace_archives(
    artifacts: &crate::artifact::ArtifactRegistry,
    crate_name: &str,
    target: Option<&str>,
) -> Vec<std::path::PathBuf> {
    artifacts
        .by_kind_and_crate(crate::artifact::ArtifactKind::Archive, crate_name)
        .iter()
        .filter(|a| a.target.as_deref() == target)
        .map(|a| a.path.clone())
        .collect()
}

/// Gated variant of [`collect_replace_archives`]: returns the matching
/// archive paths only when `replace` is `Some(true)`. Used by packaging
/// stages (dmg, msi, flatpak, snapcraft, nsis, pkg, appbundle) to
/// replace a source archive with the packaged output when the user
/// opts in via `replace: true` on the config. Returns an empty vec
/// when `replace` is unset or `false`.
pub fn collect_if_replace(
    replace: Option<bool>,
    artifacts: &crate::artifact::ArtifactRegistry,
    crate_name: &str,
    target: Option<&str>,
) -> Vec<std::path::PathBuf> {
    if replace.unwrap_or(false) {
        collect_replace_archives(artifacts, crate_name, target)
    } else {
        Vec::new()
    }
}

/// Convert any Windows-style backslash separators in `s` to forward
/// slashes. Cross-platform path string normalization for cases where the
/// downstream consumer (artifact-manifest JSON, MSYS subprocess env var)
/// is sensitive to separator drift between Linux/macOS and Windows hosts.
pub fn normalize_path_separators(s: &str) -> String {
    s.replace('\\', "/")
}

/// Apply a "minimal trusted" environment to a `Command` after `env_clear()`.
///
/// Stage subprocess invocations (sbom, source-archive, …) clear the env to
/// stop accidental token leakage but still need a small set of platform-
/// neutral keys so that `git`, `tar`, `syft`, etc. behave normally — HOME
/// for tool config, USER for git author fallback, USERPROFILE/LOCALAPPDATA
/// for the Windows equivalents, TMPDIR/TMP/TEMP so temp-file allocation
/// doesn't land in a forbidden directory, and PATH so the tool itself can
/// find its dependencies. Keeping this list in core means any new entry
/// (e.g. SSL_CERT_DIR for syft pulling enrich data) is added once.
pub fn apply_minimal_env(command: &mut std::process::Command) {
    const PASSTHROUGH: &[&str] = &[
        "HOME",
        "USER",
        "USERPROFILE",
        "TMPDIR",
        "TMP",
        "TEMP",
        "PATH",
        "LOCALAPPDATA",
    ];
    for key in PASSTHROUGH {
        if let Ok(val) = std::env::var(key) {
            command.env(key, val);
        }
    }
}

/// Cargo build-intermediate subdirectories that sit under a profile dir
/// (`target/<triple>/release/`) and hold no shippable or hashed artifact.
///
/// The final binary and any sibling files live directly under the profile
/// dir; everything reproducibility cares about (the produced binary, the
/// `dist/` archives/installers built from it) is downstream of these. These
/// four are pure cargo scratch — object files, build-script outputs,
/// incremental-compilation state, and fingerprints — that cargo regenerates
/// on demand if a later build touches the same triple.
const CARGO_BUILD_INTERMEDIATE_DIRS: &[&str] = &["deps", "build", "incremental", ".fingerprint"];

/// Free cargo build intermediates under a profile directory
/// (`target/<triple>/release/`) once its binary has been produced, lowering
/// peak disk for multi-target builds that share one `target/` tree.
///
/// Removes only [`CARGO_BUILD_INTERMEDIATE_DIRS`] (`deps`, `build`,
/// `incremental`, `.fingerprint`). The final binary and every other file
/// directly under `profile_dir` are left untouched, so neither a shipped
/// artifact nor a determinism-hashed binary can change.
///
/// Best-effort: a missing subdir is the normal case (not every triple has
/// `incremental/`), and a failed remove must never fail the build — both are
/// reported at verbose and swallowed. Returns the list of subdir names
/// actually removed so callers can log a precise per-triple line.
///
/// Guard: this only operates when `profile_dir`'s basename is a real cargo
/// profile (`release` / `debug`). Handed anything else (a workspace root,
/// `target/` itself, an empty/root path), it is a hard no-op — the scratch
/// names are generic enough that a future miswire pointing at the wrong dir
/// would otherwise delete a real `build`/`deps` tree.
pub fn free_cargo_build_intermediates(
    profile_dir: &Path,
    log: &crate::log::StageLogger,
) -> Vec<&'static str> {
    let is_cargo_profile_dir = profile_dir
        .file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|n| n == "release" || n == "debug");
    if !is_cargo_profile_dir {
        log.verbose(&format!(
            "refusing to free build intermediates under non-profile dir {}",
            profile_dir.display()
        ));
        return Vec::new();
    }
    let mut freed = Vec::new();
    for sub in CARGO_BUILD_INTERMEDIATE_DIRS {
        let path = profile_dir.join(sub);
        if !path.exists() {
            continue;
        }
        match fs::remove_dir_all(&path) {
            Ok(()) => freed.push(*sub),
            Err(err) => log.verbose(&format!(
                "could not free build intermediate {}: {err}",
                path.display()
            )),
        }
    }
    freed
}

#[cfg(test)]
mod tests {
    use super::*;

    // -----------------------------------------------------------------------
    // topological_sort tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_topo_sort_simple_chain() {
        let items = vec![
            ("c".to_string(), vec!["b".to_string()]),
            ("b".to_string(), vec!["a".to_string()]),
            ("a".to_string(), vec![]),
        ];
        let sorted = topological_sort(&items);
        assert_eq!(sorted, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_topo_sort_no_deps() {
        let items = vec![("b".to_string(), vec![]), ("a".to_string(), vec![])];
        // Deterministic: alphabetical
        let sorted = topological_sort(&items);
        assert_eq!(sorted, vec!["a", "b"]);
    }

    #[test]
    fn test_topo_sort_ignores_external_deps() {
        let items = vec![
            (
                "b".to_string(),
                vec!["a".to_string(), "external".to_string()],
            ),
            ("a".to_string(), vec![]),
        ];
        let sorted = topological_sort(&items);
        assert_eq!(sorted, vec!["a", "b"]);
    }

    #[test]
    fn test_topo_sort_diamond() {
        let items = vec![
            ("d".to_string(), vec!["b".to_string(), "c".to_string()]),
            ("b".to_string(), vec!["a".to_string()]),
            ("c".to_string(), vec!["a".to_string()]),
            ("a".to_string(), vec![]),
        ];
        let sorted = topological_sort(&items);
        // a must come first, d must come last, b and c in between
        assert_eq!(sorted[0], "a");
        assert_eq!(sorted[3], "d");
    }

    #[test]
    fn test_topo_sort_cycle_appends_remaining() {
        let items = vec![
            ("a".to_string(), vec!["b".to_string()]),
            ("b".to_string(), vec!["a".to_string()]),
            ("c".to_string(), vec![]),
        ];
        let sorted = topological_sort(&items);
        assert_eq!(sorted.len(), 3);
        // c has no deps, should come first; a and b are in a cycle
        assert_eq!(sorted[0], "c");
    }

    #[test]
    fn test_topo_sort_empty() {
        let items: Vec<(String, Vec<String>)> = vec![];
        let sorted = topological_sort(&items);
        assert!(sorted.is_empty());
    }

    // -----------------------------------------------------------------------
    // parse_mod_timestamp tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_parse_mod_timestamp_epoch_integer() {
        let t = parse_mod_timestamp("1704067200").unwrap();
        let epoch = t.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
        assert_eq!(epoch, 1704067200);
    }

    #[test]
    fn test_parse_mod_timestamp_rfc3339() {
        let t = parse_mod_timestamp("2024-01-01T00:00:00Z").unwrap();
        let epoch = t.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
        assert_eq!(epoch, 1704067200);
    }

    #[test]
    fn test_parse_mod_timestamp_rfc3339_with_offset() {
        let t = parse_mod_timestamp("2024-01-01T01:00:00+01:00").unwrap();
        let epoch = t.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
        // 2024-01-01T01:00:00+01:00 is the same instant as 2024-01-01T00:00:00Z
        assert_eq!(epoch, 1704067200);
    }

    #[test]
    fn test_parse_mod_timestamp_naive_datetime() {
        let t = parse_mod_timestamp("2024-01-01T00:00:00").unwrap();
        let epoch = t.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
        assert_eq!(epoch, 1704067200);
    }

    #[test]
    fn test_parse_mod_timestamp_invalid() {
        let err = parse_mod_timestamp("not-a-timestamp").unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("not a valid timestamp"),
            "unexpected error: {msg}"
        );
        // The parse error must include
        // the offending mtime value so misconfigurations are diagnosable.
        assert!(
            msg.contains("not-a-timestamp"),
            "error must include the bad value, got: {msg}"
        );
    }

    #[test]
    fn test_parse_mod_timestamp_zero() {
        let t = parse_mod_timestamp("0").unwrap();
        assert_eq!(t, SystemTime::UNIX_EPOCH);
    }

    // -----------------------------------------------------------------------
    // set_file_mtime tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_set_file_mtime_sets_both_atime_and_mtime() {
        let dir = tempfile::tempdir().unwrap();
        let dir = dir.path();

        let file_path = dir.join("test.txt");
        std::fs::write(&file_path, "hello").unwrap();

        // Set mtime to a known epoch: 2024-01-01T00:00:00Z = 1704067200
        let target = SystemTime::UNIX_EPOCH + Duration::from_secs(1704067200);
        set_file_mtime(&file_path, target).unwrap();

        let meta = std::fs::metadata(&file_path).unwrap();
        let actual_mtime = meta.modified().unwrap();

        // Allow 1-second tolerance for filesystem granularity
        let diff = if actual_mtime > target {
            actual_mtime.duration_since(target).unwrap()
        } else {
            target.duration_since(actual_mtime).unwrap()
        };
        assert!(
            diff.as_secs() <= 1,
            "mtime should be within 1s of target, diff={:?}",
            diff
        );

        // Also verify atime was set (on Linux, accessed() is available)
        let actual_atime = meta.accessed().unwrap();
        let diff_a = if actual_atime > target {
            actual_atime.duration_since(target).unwrap()
        } else {
            target.duration_since(actual_atime).unwrap()
        };
        assert!(
            diff_a.as_secs() <= 1,
            "atime should be within 1s of target, diff={:?}",
            diff_a
        );
    }

    #[test]
    fn test_pin_dir_mtimes_epoch_recurses_into_subdirs() {
        let dir = tempfile::tempdir().unwrap();
        let dir = dir.path();
        let sub = dir.join("nested");
        std::fs::create_dir_all(&sub).unwrap();

        let top = dir.join("top.txt");
        let nested = sub.join("nested.txt");
        std::fs::write(&top, "top").unwrap();
        std::fs::write(&nested, "nested").unwrap();

        let epoch: i64 = 1704067200;
        pin_dir_mtimes_epoch(dir, epoch).unwrap();

        let target = SystemTime::UNIX_EPOCH + Duration::from_secs(epoch as u64);
        for path in [&top, &nested] {
            let mtime = std::fs::metadata(path).unwrap().modified().unwrap();
            assert_eq!(
                mtime,
                target,
                "{}: mtime must equal the pinned epoch exactly",
                path.display()
            );
        }
    }

    #[test]
    fn test_set_file_mtime_nonexistent_file() {
        let result = set_file_mtime(Path::new("/nonexistent/file.txt"), SystemTime::UNIX_EPOCH);
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // apply_mod_timestamp tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_apply_mod_timestamp_sets_mtime_on_regular_files() {
        let dir = tempfile::tempdir().unwrap();
        let dir = dir.path();

        // Create two regular files and a subdirectory (the dir itself is not stamped)
        std::fs::write(dir.join("a.txt"), "aaa").unwrap();
        std::fs::write(dir.join("b.txt"), "bbb").unwrap();
        std::fs::create_dir(dir.join("subdir")).unwrap();

        let log = crate::log::StageLogger::new("test", crate::log::Verbosity::Quiet);
        apply_mod_timestamp(dir, "1704067200", &log).unwrap();

        let target = SystemTime::UNIX_EPOCH + Duration::from_secs(1704067200);
        for name in &["a.txt", "b.txt"] {
            let meta = std::fs::metadata(dir.join(name)).unwrap();
            let mtime = meta.modified().unwrap();
            let diff = if mtime > target {
                mtime.duration_since(target).unwrap()
            } else {
                target.duration_since(mtime).unwrap()
            };
            assert!(
                diff.as_secs() <= 1,
                "{name}: mtime should be within 1s of target, diff={:?}",
                diff
            );
        }
    }

    #[test]
    fn test_apply_mod_timestamp_recurses_into_subdirs() {
        let dir = tempfile::tempdir().unwrap();
        let dir = dir.path();
        let sub = dir.join("docs");
        std::fs::create_dir_all(&sub).unwrap();

        let top = dir.join("top.txt");
        let nested = sub.join("README.txt");
        std::fs::write(&top, "top").unwrap();
        std::fs::write(&nested, "nested").unwrap();

        let log = crate::log::StageLogger::new("test", crate::log::Verbosity::Quiet);
        apply_mod_timestamp(dir, "1704067200", &log).unwrap();

        let target = SystemTime::UNIX_EPOCH + Duration::from_secs(1704067200);
        for path in [&top, &nested] {
            let mtime = std::fs::metadata(path).unwrap().modified().unwrap();
            let diff = if mtime > target {
                mtime.duration_since(target).unwrap()
            } else {
                target.duration_since(mtime).unwrap()
            };
            assert!(
                diff.as_secs() <= 1,
                "{}: nested file must receive mod_timestamp, diff={:?}",
                path.display(),
                diff
            );
        }
    }

    #[test]
    fn test_apply_mod_timestamp_invalid_timestamp_errors() {
        let dir = tempfile::tempdir().unwrap();

        let log = crate::log::StageLogger::new("test", crate::log::Verbosity::Quiet);
        let result = apply_mod_timestamp(dir.path(), "not-valid", &log);
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // free_cargo_build_intermediates tests
    // -----------------------------------------------------------------------

    /// Build a `target/<triple>/release/` profile dir under `root` so the
    /// helper's profile-dir guard (basename must be `release`/`debug`) is
    /// satisfied, mirroring cargo's real layout.
    fn mk_release_dir(root: &Path) -> std::path::PathBuf {
        let profile = root
            .join("target")
            .join("x86_64-unknown-linux-gnu")
            .join("release");
        std::fs::create_dir_all(&profile).unwrap();
        profile
    }

    #[test]
    fn test_free_cargo_build_intermediates_removes_transient_keeps_binary() {
        let tmp = tempfile::tempdir().unwrap();
        let profile = mk_release_dir(tmp.path());

        // Scaffold the four transient subdirs (each with a file inside so the
        // remove is non-trivial), the final binary, and a sibling regular file
        // directly under the profile dir.
        for sub in ["deps", "build", "incremental", ".fingerprint"] {
            let d = profile.join(sub);
            std::fs::create_dir_all(&d).unwrap();
            std::fs::write(d.join("scratch.o"), "obj").unwrap();
        }
        std::fs::write(profile.join("myapp"), b"\x7fELF binary").unwrap();
        std::fs::write(profile.join("myapp.d"), "depinfo").unwrap();

        let log = crate::log::StageLogger::new("test", crate::log::Verbosity::Quiet);
        let mut freed = free_cargo_build_intermediates(&profile, &log);
        freed.sort_unstable();
        assert_eq!(freed, vec![".fingerprint", "build", "deps", "incremental"]);

        for sub in ["deps", "build", "incremental", ".fingerprint"] {
            assert!(
                !profile.join(sub).exists(),
                "transient subdir {sub} should be removed"
            );
        }
        assert!(profile.join("myapp").exists(), "binary must be retained");
        assert_eq!(
            std::fs::read(profile.join("myapp")).unwrap(),
            b"\x7fELF binary"
        );
        assert!(
            profile.join("myapp.d").exists(),
            "sibling regular file must be retained"
        );
    }

    #[test]
    fn test_free_cargo_build_intermediates_missing_dirs_is_noop() {
        let tmp = tempfile::tempdir().unwrap();
        let profile = mk_release_dir(tmp.path());
        // Only a binary present — no transient subdirs at all.
        std::fs::write(profile.join("myapp"), "bin").unwrap();

        let log = crate::log::StageLogger::new("test", crate::log::Verbosity::Quiet);
        let freed = free_cargo_build_intermediates(&profile, &log);
        assert!(freed.is_empty(), "nothing to free when no subdirs exist");
        assert!(profile.join("myapp").exists());
    }

    #[test]
    fn test_free_cargo_build_intermediates_partial_subset() {
        let tmp = tempfile::tempdir().unwrap();
        let profile = mk_release_dir(tmp.path());
        // Only `deps/` and `incremental/` present — the helper frees exactly
        // those and leaves the absent ones as no-ops.
        std::fs::create_dir_all(profile.join("deps")).unwrap();
        std::fs::create_dir_all(profile.join("incremental")).unwrap();
        std::fs::write(profile.join("myapp"), "bin").unwrap();

        let log = crate::log::StageLogger::new("test", crate::log::Verbosity::Quiet);
        let mut freed = free_cargo_build_intermediates(&profile, &log);
        freed.sort_unstable();
        assert_eq!(freed, vec!["deps", "incremental"]);
        assert!(profile.join("myapp").exists());
    }

    /// Guard: handed a NON-profile dir (basename not `release`/`debug`), the
    /// helper is a hard no-op even if scratch-named subdirs are present, so a
    /// future miswire can't delete a real `build`/`deps` tree elsewhere.
    #[test]
    fn test_free_cargo_build_intermediates_non_profile_dir_is_noop() {
        let tmp = tempfile::tempdir().unwrap();
        // A workspace-root-shaped dir whose basename is `target`, not a profile.
        let not_profile = tmp.path().join("target");
        std::fs::create_dir_all(not_profile.join("deps")).unwrap();
        std::fs::create_dir_all(not_profile.join("build")).unwrap();

        let log = crate::log::StageLogger::new("test", crate::log::Verbosity::Quiet);
        let freed = free_cargo_build_intermediates(&not_profile, &log);
        assert!(
            freed.is_empty(),
            "non-profile dir must free nothing (guard)"
        );
        assert!(
            not_profile.join("deps").exists() && not_profile.join("build").exists(),
            "guard must leave a non-profile dir's contents untouched"
        );
    }
}