autumn-cli 0.10.0

CLI tool for the Autumn web framework
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
//! The orphan sweep of `autumn destroy` (issue #2557).
//!
//! `destroy` builds the plan again from the current templates. A file that an
//! older template wrote, and that the current templates renamed or dropped, is
//! in no action. The manifest still names it. This module finds such entries
//! and decides, for each one, to delete it, to keep it with a warning, or to
//! drop the stale entry.
//!
//! The paths come from the manifest, which is project content. Every check
//! here treats them as untrusted. See `docs/adr/0021-destroy-orphan-sweep.md`.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};

use super::emit::{Action, split_migration_dir_name};
use super::provenance::{self, MANIFEST_PATH, Provenance, Recorded, Scope};
use super::spelling::{self, has_exact_entry};

/// Files the sweep never deletes, lowercase. Generators edit them in place
/// and never own them, so the sweep does not trust an `owned` entry for one.
const PROTECTED_FILES: &[&str] = &[
    "autumn.toml",
    "build.rs",
    "cargo.lock",
    "cargo.toml",
    "src/lib.rs",
    "src/main.rs",
];

/// What `revert` does with the swept entries.
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct Sweep {
    /// Untouched owned files to delete.
    pub remove: Vec<PathBuf>,
    /// The recorded digest of each file in `remove`. `revert` checks it again
    /// just before the delete.
    pub digests: HashMap<PathBuf, String>,
    /// Entries whose file is gone. Drop them from the manifest.
    pub forget: Vec<PathBuf>,
    /// Files kept, and why.
    pub warnings: Vec<String>,
}

/// Find the entries `invocation` wrote that no action in `actions` names.
///
/// Delete an `owned` file only when its digest still matches and the plan
/// creates a file in the same directory. Keep every other file, with a
/// warning that names it. `--force` has no effect here: these paths come
/// from the manifest, not from the plan.
pub(super) fn plan_sweep(
    project_root: &Path,
    recorded: &Provenance,
    invocation: &str,
    actions: &[Action],
    revert_targets: &[&Path],
) -> Sweep {
    let mut planned = Planned::new(project_root, actions);
    // A revert can rewrite or delete its target. Leave that file to it.
    for path in revert_targets {
        if let Some(key) = provenance::key(project_root, path) {
            planned.files.insert(key, path);
        }
    }
    let mut sweep = Sweep::default();
    for entry in recorded.recorded_by(invocation) {
        sweep_one(project_root, entry, &planned, &mut sweep);
    }
    sweep
}

/// What the plan names, in the forms the sweep compares against.
struct Planned {
    /// The path of each action and revert.
    files: Spellings,
    /// The parent directory of each `Create`/`CreateBytes`.
    owned_dirs: Spellings,
    /// The suffix of each migration directory, lowercase.
    migration_suffixes: HashSet<String>,
}

impl Planned {
    fn new(project_root: &Path, actions: &[Action]) -> Self {
        let mut planned = Self {
            files: Spellings::default(),
            owned_dirs: Spellings::default(),
            migration_suffixes: HashSet::new(),
        };
        for action in actions {
            let path = action.path();
            let Some(key) = provenance::key(project_root, path) else {
                continue;
            };
            if matches!(action, Action::Create { .. } | Action::CreateBytes { .. })
                && let Some(dir) = path.parent()
            {
                planned.owned_dirs.insert(parent_key(&key).to_owned(), dir);
            }
            let lower = key.to_ascii_lowercase();
            if let ["migrations", dir, _] = lower.split('/').collect::<Vec<_>>().as_slice() {
                planned.migration_suffixes.insert(migration_suffix(dir));
            }
            planned.files.insert(key, path);
        }
        planned
    }
}

/// A set of project keys, each with its path.
#[derive(Default)]
struct Spellings(HashMap<String, PathBuf>);

impl Spellings {
    fn insert(&mut self, key: String, path: &Path) {
        self.0.entry(key).or_insert_with(|| path.to_path_buf());
    }

    /// Whether the set holds `key`, the key of `path`.
    ///
    /// An exact match does. Another spelling of the same directory entry does
    /// too, as on a case-insensitive file system (issue #3382). Two entries
    /// are two names, even when they are hard links to one file.
    fn holds(&self, key: &str, path: &Path) -> bool {
        self.0.contains_key(key)
            || self
                .0
                .iter()
                .any(|(k, other)| k.eq_ignore_ascii_case(key) && spelling::one_entry(path, other))
    }
}

/// The directory part of a key, or `""` for a top-level file.
fn parent_key(key: &str) -> &str {
    key.rsplit_once('/').map_or("", |(dir, _)| dir)
}

/// Decide what to do with one entry.
fn sweep_one(project_root: &Path, entry: Recorded<'_>, planned: &Planned, sweep: &mut Sweep) {
    let Some(parts) = plain_parts(entry.key) else {
        sweep.warnings.push(format!(
            "{:?} in {MANIFEST_PATH} is not a plain project path. autumn destroy does not \
             use it.",
            entry.key
        ));
        return;
    };
    let shown = entry.key;
    let lower = shown.to_ascii_lowercase();
    let path = parts
        .iter()
        .fold(project_root.to_path_buf(), |p, part| p.join(part));
    if planned.files.holds(shown, &path) {
        return;
    }
    let found = inspect(project_root, &parts);
    if matches!(found, Inspect::Missing) {
        // Dropping the entry of a missing file deletes nothing.
        sweep.forget.push(path);
        return;
    }
    let warn = |sweep: &mut Sweep, why: &str| sweep.warnings.push(format!("{shown}: {why}"));
    if lower.starts_with("migrations/") {
        // The plan matches migrations by suffix, not by timestamp. Only the
        // applied-migration guard of that pass may remove one.
        let matched = parts.len() == 3
            && planned
                .migration_suffixes
                .contains(&migration_suffix(parts[1]));
        if !matched {
            warn(
                sweep,
                "the current templates do not make this migration file. autumn destroy \
                 never sweeps migrations. Remove it by hand if no database uses it.",
            );
        }
        return;
    }
    // A dot segment (`.env`, `.git/`, `.autumn/`) or `target/` is never a
    // generator's own output to sweep, whatever the manifest says.
    if PROTECTED_FILES.contains(&lower.as_str())
        || parts.iter().any(|part| part.starts_with('.'))
        || parts[0].eq_ignore_ascii_case("target")
    {
        warn(sweep, "autumn destroy never sweeps this file.");
        return;
    }
    if let Inspect::Refused(reason) = found {
        warn(
            sweep,
            &format!("autumn destroy does not sweep this file, because {reason}."),
        );
        return;
    }
    let dir = path.parent().unwrap_or(project_root);
    match entry.scope {
        None => warn(
            sweep,
            "an older Autumn CLI recorded this file for this command, and the current \
             templates do not make it. autumn destroy cannot prove that only this resource \
             uses it, so it keeps the file. Delete it by hand if nothing uses it.",
        ),
        Some(Scope::Shared) => warn(
            sweep,
            "this command made this shared file, and the current templates do not make it. \
             Other resources can use it, so autumn destroy keeps it. Delete it by hand if \
             nothing uses it.",
        ),
        // The manifest is project content, so a forged entry can name any
        // file and its digest. Delete only in a directory where the current
        // templates also create a file. Then a forged entry cannot reach a
        // file outside the generator's own directories.
        Some(Scope::Owned) if !planned.owned_dirs.holds(parent_key(shown), dir) => warn(
            sweep,
            "the current templates do not make this file, and they create no file in its \
             directory. autumn destroy keeps it. Delete it by hand if you do not need it.",
        ),
        Some(Scope::Owned) if !untouched(&path, entry.digest) => warn(
            sweep,
            "the current templates do not make this file, and it changed after generate \
             wrote it. autumn destroy keeps it. Delete it by hand if you do not need it.",
        ),
        // The reverts come from the current templates, so they do not remove
        // the `mod` line an older template added for this file. Deleting a
        // file that other code still names can stop the build.
        Some(Scope::Owned)
            if path.extension().is_some_and(|e| e == "rs")
                && still_named(project_root, &path, &parts) =>
        {
            warn(
                sweep,
                "the current templates do not make this file, but other Rust code still \
                 names it. autumn destroy keeps it. Remove the references and the file by \
                 hand if you do not need them.",
            );
        }
        Some(Scope::Owned) => {
            sweep.digests.insert(path.clone(), entry.digest.to_owned());
            sweep.remove.push(path);
        }
    }
}

/// Whether any other Rust file in the project still names the Rust file at
/// `parts`.
///
/// No parser: Rust lets a comment, an attribute, a raw string or a macro
/// stand between `mod` and the name, and a parent module can be inline in
/// any file. So any whole-word mention of the module name counts, and so does
/// the file name anywhere (a `#[path]`, an `include!`). This errs on the side
/// of "still used": a same-named item elsewhere also keeps the file, which
/// costs a warning, never a broken build.
fn still_named(project_root: &Path, path: &Path, parts: &[&str]) -> bool {
    let Some((file, dirs)) = parts.split_last() else {
        return false;
    };
    let Some(stem) = file.strip_suffix(".rs") else {
        return false;
    };
    // `mod teams;` loads `src/teams/mod.rs`: the module takes the directory's
    // name, not `mod`.
    let stem = match (stem, dirs.last()) {
        ("mod", Some(dir)) => *dir,
        _ => stem,
    };
    any_rust_file(project_root, path, |text| {
        mentions(text, stem) || text.contains(file)
    })
}

/// Whether `text` holds `word` with no identifier character on either side.
fn mentions(text: &str, word: &str) -> bool {
    let ident = |c: char| c.is_alphanumeric() || c == '_';
    text.match_indices(word).any(|(at, _)| {
        text[..at].chars().next_back().is_none_or(|c| !ident(c))
            && text[at + word.len()..]
                .chars()
                .next()
                .is_none_or(|c| !ident(c))
    })
}

/// Whether any Rust file in the project other than `skip` satisfies `test`.
fn any_rust_file(project_root: &Path, skip: &Path, test: impl Fn(&str) -> bool) -> bool {
    let mut pending = vec![project_root.to_path_buf()];
    while let Some(dir) = pending.pop() {
        let Ok(entries) = fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.filter_map(Result::ok) {
            let name = entry.file_name();
            let name = name.to_string_lossy();
            let Ok(kind) = entry.file_type() else {
                continue;
            };
            if kind.is_dir() {
                // Build output and hidden directories hold no project source.
                if !name.starts_with('.') && name != "target" && name != "node_modules" {
                    pending.push(entry.path());
                }
            } else if kind.is_file()
                && name.ends_with(".rs")
                && entry.path() != skip
                && fs::read_to_string(entry.path()).is_ok_and(|text| test(&text))
            {
                return true;
            }
        }
    }
    false
}

/// The suffix of a migration directory name, lowercase.
fn migration_suffix(dir: &str) -> String {
    split_migration_dir_name(dir).1.to_ascii_lowercase()
}

/// The segments of `key`, when every one is a plain file name.
///
/// Refuses an empty segment, `.`, `..`, a backslash, a colon (a Windows drive
/// or stream), a NUL, a `~` (a Windows short name), and a trailing dot or
/// space (Windows drops them). A key that passes cannot leave the project.
fn plain_parts(key: &str) -> Option<Vec<&str>> {
    let parts: Vec<&str> = key.split('/').collect();
    let plain = |part: &&str| {
        !part.is_empty()
            && *part != "."
            && *part != ".."
            && !part.contains(['\\', ':', '\0', '~'])
            && !part.ends_with(['.', ' '])
            && matches!(
                Path::new(part).components().collect::<Vec<_>>().as_slice(),
                [std::path::Component::Normal(_)]
            )
    };
    parts.iter().all(plain).then_some(parts)
}

/// What is on disk at an entry's path.
enum Inspect {
    /// A regular file, reached through no symlink.
    File,
    /// Nothing.
    Missing,
    /// Something the sweep must not touch.
    Refused(String),
}

/// Walk to the entry one segment at a time, without following a symlink.
///
/// A symlinked directory on the way could point outside the project, and a
/// symlinked file is not the file `generate` wrote. Each segment must also be
/// the exact name on disk: a case-insensitive or Windows file system can
/// resolve another spelling to the same file, which would let one file pass
/// a check under one name and go under another.
fn inspect(project_root: &Path, parts: &[&str]) -> Inspect {
    let mut cursor = project_root.to_path_buf();
    for (i, part) in parts.iter().enumerate() {
        let parent = cursor.clone();
        cursor.push(part);
        let last = i + 1 == parts.len();
        match fs::symlink_metadata(&cursor) {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Inspect::Missing,
            Err(e) => return Inspect::Refused(format!("it cannot be read ({e})")),
            Ok(_) if !has_exact_entry(&parent, part) => {
                return Inspect::Refused("its name on disk is spelled differently".to_owned());
            }
            Ok(m) if m.file_type().is_symlink() => {
                return Inspect::Refused("it is reached through a symlink".to_owned());
            }
            Ok(m) if last && !m.is_file() => {
                return Inspect::Refused("it is not a regular file".to_owned());
            }
            Ok(_) => {}
        }
    }
    Inspect::File
}

/// Whether `path` is still a regular file, reached through no symlink, that
/// holds `digest`.
///
/// `revert` calls this again just before it deletes a swept file. So a
/// directory swapped for a symlink, or an edit saved after the plan was made,
/// keeps the file.
pub(super) fn still_sweepable(project_root: &Path, path: &Path, digest: &str) -> bool {
    provenance::key(project_root, path).is_some_and(|key| {
        plain_parts(&key)
            .is_some_and(|parts| matches!(inspect(project_root, &parts), Inspect::File))
    }) && untouched(path, digest)
}

/// Whether the file still holds what `generate` wrote.
///
/// The entry does not say text or bytes, so both digests are tried. The text
/// digest ignores line endings, so a CRLF checkout is not an edit.
fn untouched(path: &Path, digest: &str) -> bool {
    fs::read(path).is_ok_and(|bytes| {
        provenance::bytes_digest(&bytes) == digest
            || std::str::from_utf8(&bytes).is_ok_and(|text| provenance::text_digest(text) == digest)
    })
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::*;
    use crate::generate::provenance::{Scope, text_digest};

    const ME: &str = "job\u{1f}Foo";

    fn tmp() -> tempfile::TempDir {
        tempfile::TempDir::new().unwrap()
    }

    /// Write `contents` at `rel` and record it for `invocation`.
    fn generated(
        root: &Path,
        p: &mut Provenance,
        rel: &str,
        contents: &str,
        invocation: &str,
        scope: Option<Scope>,
    ) -> PathBuf {
        let path = root.join(rel);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, contents).unwrap();
        p.record(root, &path, text_digest(contents), invocation, scope);
        path
    }

    fn create(root: &Path, rel: &str) -> Action {
        Action::Create {
            path: root.join(rel),
            contents: String::new(),
        }
    }

    #[test]
    fn an_untouched_renamed_file_is_removed() {
        // The `old.rs` -> `new.rs` case from the issue.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(
            root,
            &mut p,
            "src/old.rs",
            "// v1\n",
            ME,
            Some(Scope::Owned),
        );

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/new.rs")], &[]);

        assert_eq!(sweep.remove, vec![old]);
        assert!(sweep.warnings.is_empty(), "{:?}", sweep.warnings);
    }

    #[test]
    fn a_crlf_checkout_of_an_orphan_is_still_untouched() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(root, &mut p, "src/old.rs", "a\nb\n", ME, Some(Scope::Owned));
        fs::write(&old, "a\r\nb\r\n").unwrap();

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/new.rs")], &[]);
        assert_eq!(sweep.remove, vec![old]);
    }

    #[test]
    fn an_orphan_written_as_bytes_is_removed() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let bytes = [0x89_u8, b'P', b'N', b'G', 0xff, 0x00];
        let old = root.join("static/old.png");
        fs::create_dir_all(old.parent().unwrap()).unwrap();
        fs::write(&old, bytes).unwrap();
        p.record(
            root,
            &old,
            crate::generate::provenance::bytes_digest(&bytes),
            ME,
            Some(Scope::Owned),
        );

        let sweep = plan_sweep(root, &p, ME, &[create(root, "static/new.png")], &[]);
        assert_eq!(sweep.remove, vec![old]);
    }

    #[test]
    fn an_edited_orphan_is_kept_with_a_warning() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(
            root,
            &mut p,
            "src/old.rs",
            "// v1\n",
            ME,
            Some(Scope::Owned),
        );
        fs::write(&old, "// mine\n").unwrap();

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/new.rs")], &[]);

        assert!(sweep.remove.is_empty());
        assert_eq!(sweep.warnings.len(), 1);
        assert!(
            sweep.warnings[0].contains("src/old.rs"),
            "{:?}",
            sweep.warnings
        );
    }

    #[test]
    fn a_shared_orphan_is_kept_with_a_warning() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        generated(
            root,
            &mut p,
            "templates/mailers/_layout.html",
            "<html>\n",
            ME,
            Some(Scope::Shared),
        );

        let sweep = plan_sweep(root, &p, ME, &[], &[]);

        assert!(sweep.remove.is_empty());
        assert_eq!(sweep.warnings.len(), 1);
        assert!(sweep.warnings[0].contains("_layout.html"));
    }

    #[test]
    fn a_legacy_orphan_is_kept_with_a_warning() {
        // A 0.8.0 entry has no scope, so owned and shared look the same.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        generated(root, &mut p, "src/old.rs", "// v1\n", ME, None);

        let sweep = plan_sweep(root, &p, ME, &[], &[]);

        assert!(sweep.remove.is_empty());
        assert_eq!(sweep.warnings.len(), 1);
        assert!(sweep.warnings[0].contains("src/old.rs"));
    }

    #[test]
    fn another_commands_entry_is_ignored() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        generated(
            root,
            &mut p,
            "src/other.rs",
            "x",
            "job\u{1f}Bar",
            Some(Scope::Owned),
        );

        assert_eq!(plan_sweep(root, &p, ME, &[], &[]), Sweep::default());
    }

    #[test]
    fn a_path_the_plan_names_is_left_to_the_plan() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        generated(root, &mut p, "src/a.rs", "x", ME, Some(Scope::Owned));
        generated(root, &mut p, "src/b.rs", "y", ME, Some(Scope::Owned));
        let actions = [
            create(root, "src/a.rs"),
            Action::Modify {
                path: root.join("src/b.rs"),
                contents: String::new(),
            },
        ];

        assert_eq!(plan_sweep(root, &p, ME, &actions, &[]), Sweep::default());
    }

    #[test]
    fn a_case_only_match_is_one_file_only_when_it_is_one_entry() {
        // A case-insensitive file system lists one entry for both spellings:
        // the plan removes it. A case-sensitive one can hold two hard-linked
        // entries: removing `post.rs` leaves `Post.rs`, so it is an orphan.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(
            root,
            &mut p,
            "src/models/Post.rs",
            "x",
            ME,
            Some(Scope::Owned),
        );
        let new = root.join("src/models/post.rs");
        let one_entry = new.exists();
        if !one_entry && fs::hard_link(&old, &new).is_err() {
            return; // no hard links on this file system; nothing to test.
        }

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/models/post.rs")], &[]);

        if one_entry {
            assert_eq!(sweep, Sweep::default());
        } else {
            assert_eq!(sweep.remove, vec![old]);
        }
    }

    #[test]
    fn a_case_only_rename_on_a_case_sensitive_host_is_swept() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(
            root,
            &mut p,
            "src/models/Post.rs",
            "x",
            ME,
            Some(Scope::Owned),
        );
        if root.join("src/models/post.rs").exists() {
            return; // a case-insensitive file system: one file, not two.
        }

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/models/post.rs")], &[]);

        assert_eq!(sweep.remove, vec![old]);
    }

    #[test]
    fn an_orphan_in_a_case_only_renamed_directory_is_swept_only_when_it_is_one_directory() {
        // Issue #3382: a template moved `src/widgets/old.rs` to
        // `src/Widgets/new.rs`.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(
            root,
            &mut p,
            "src/widgets/old.rs",
            "x",
            ME,
            Some(Scope::Owned),
        );
        let upper = root.join("src/Widgets");
        let one_dir = upper.exists();
        if !one_dir {
            fs::create_dir(&upper).unwrap(); // a second, real directory.
        }

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/Widgets/new.rs")], &[]);

        if one_dir {
            assert_eq!(sweep.remove, vec![old]);
            assert!(sweep.warnings.is_empty(), "{:?}", sweep.warnings);
        } else {
            assert!(sweep.remove.is_empty(), "{:?}", sweep.remove);
            assert_eq!(sweep.warnings.len(), 1, "{:?}", sweep.warnings);
            assert!(sweep.warnings[0].contains("no file in its directory"));
        }
    }

    #[test]
    fn an_orphan_outside_every_planned_directory_is_kept() {
        // A forged entry can name any file and its digest. Without a planned
        // file next to it, the sweep must not delete it.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let readme = generated(root, &mut p, "README.md", "# app\n", ME, Some(Scope::Owned));
        let other = generated(root, &mut p, "src/other/x.rs", "x", ME, Some(Scope::Owned));

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/widgets/new.rs")], &[]);

        assert!(sweep.remove.is_empty(), "{:?}", sweep.remove);
        assert_eq!(sweep.warnings.len(), 2, "{:?}", sweep.warnings);
        assert!(readme.exists() && other.exists());
    }

    #[test]
    fn a_modify_target_does_not_make_its_directory_sweepable() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        generated(root, &mut p, "src/notes.rs", "x", ME, Some(Scope::Owned));
        let actions = [Action::Modify {
            path: root.join("src/routes.rs"),
            contents: String::new(),
        }];

        let sweep = plan_sweep(root, &p, ME, &actions, &[]);

        assert!(sweep.remove.is_empty());
        assert_eq!(sweep.warnings.len(), 1);
    }

    #[test]
    fn a_missing_orphan_drops_its_entry() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(root, &mut p, "src/old.rs", "x", ME, Some(Scope::Owned));
        fs::remove_file(&old).unwrap();

        let sweep = plan_sweep(root, &p, ME, &[], &[]);

        assert_eq!(sweep.forget, vec![old]);
        assert!(sweep.remove.is_empty());
        assert!(sweep.warnings.is_empty());
    }

    #[test]
    fn a_migration_the_plan_matches_by_suffix_is_left_to_the_plan() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        generated(
            root,
            &mut p,
            "migrations/20260101000000_create_posts/up.sql",
            "x",
            ME,
            Some(Scope::Owned),
        );
        let actions = [create(
            root,
            "migrations/20261021000000_create_posts/up.sql",
        )];

        assert_eq!(plan_sweep(root, &p, ME, &actions, &[]), Sweep::default());
    }

    #[test]
    fn an_orphan_migration_is_never_swept() {
        // Only the applied-migration guard may remove a migration.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        generated(
            root,
            &mut p,
            "migrations/20260101000000_create_posts/up.sql",
            "x",
            ME,
            Some(Scope::Owned),
        );

        let sweep = plan_sweep(root, &p, ME, &[], &[]);

        assert!(sweep.remove.is_empty());
        assert_eq!(sweep.warnings.len(), 1);
        assert!(
            sweep.warnings[0].contains("migration"),
            "{:?}",
            sweep.warnings
        );
    }

    #[test]
    fn an_orphan_migration_beside_another_planned_migration_is_never_swept() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(
            root,
            &mut p,
            "migrations/20260101000000_create_widgets/up.sql",
            "x",
            ME,
            Some(Scope::Owned),
        );
        let actions = [create(
            root,
            "migrations/20261021000000_create_posts/up.sql",
        )];

        let sweep = plan_sweep(root, &p, ME, &actions, &[]);

        assert!(sweep.remove.is_empty());
        assert_eq!(sweep.warnings.len(), 1, "{:?}", sweep.warnings);
        assert!(old.exists());
    }

    #[test]
    fn a_nested_migration_file_is_never_swept() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        generated(
            root,
            &mut p,
            "migrations/20260101000000_create_posts/data/seed.sql",
            "x",
            ME,
            Some(Scope::Owned),
        );
        let actions = [create(
            root,
            "migrations/20261021000000_create_posts/up.sql",
        )];

        let sweep = plan_sweep(root, &p, ME, &actions, &[]);

        assert!(sweep.remove.is_empty());
        assert_eq!(sweep.warnings.len(), 1, "{:?}", sweep.warnings);
    }

    #[test]
    fn a_protected_project_file_is_never_swept() {
        for rel in [
            "src/main.rs",
            "Cargo.toml",
            "CARGO.TOML",
            "Cargo.lock",
            "build.rs",
            "src/lib.rs",
            "autumn.toml",
            ".git/config",
            ".env",
            ".autumn/generated.toml",
            "src/.hidden/x.rs",
            "target/debug/x",
        ] {
            let dir = tmp();
            let root = dir.path();
            let mut p = Provenance::default();
            let path = generated(root, &mut p, rel, "x", ME, Some(Scope::Owned));
            // A planned file next to it, so only the protection can stop it.
            let sibling = match parent_key(rel) {
                "" => "planned.rs".to_owned(),
                dir => format!("{dir}/planned.rs"),
            };

            let sweep = plan_sweep(root, &p, ME, &[create(root, &sibling)], &[]);

            assert!(sweep.remove.is_empty(), "{rel} must not be swept");
            assert_eq!(sweep.warnings.len(), 1, "{rel}: {:?}", sweep.warnings);
            assert!(path.exists());
        }
    }

    /// Write a manifest whose only entry is `key`, with the digest of `x`.
    fn crafted(root: &Path, key: &str) -> Provenance {
        fs::create_dir_all(root.join(".autumn")).unwrap();
        let mut doc = toml::Table::new();
        let mut entry = toml::Table::new();
        entry.insert("digest".into(), text_digest("x").into());
        entry.insert("invocation".into(), ME.into());
        entry.insert("scope".into(), "owned".into());
        let mut files = toml::Table::new();
        files.insert(key.into(), entry.into());
        doc.insert("files".into(), files.into());
        fs::write(
            root.join(crate::generate::provenance::MANIFEST_PATH),
            toml::to_string(&doc).unwrap(),
        )
        .unwrap();
        Provenance::load(root)
    }

    #[test]
    fn a_crafted_key_never_reaches_outside_the_project() {
        let outer = tmp();
        let root = outer.path().join("app");
        fs::create_dir_all(&root).unwrap();
        let victim = outer.path().join("victim.rs");
        fs::write(&victim, "x").unwrap();
        let victim_key = victim.to_string_lossy().replace('\\', "/");

        for key in [
            "../victim.rs",
            "src/../../victim.rs",
            "./src/../../victim.rs",
            victim_key.as_str(),
            "C:/victim.rs",
            "src\\..\\..\\victim.rs",
            "",
            "src//a.rs",
            "src/./a.rs",
            "src/a\0b.rs",
        ] {
            let p = crafted(&root, key);
            let sweep = plan_sweep(&root, &p, ME, &[create(&root, "src/new.rs")], &[]);
            assert!(sweep.remove.is_empty(), "{key:?} must be refused");
            assert!(sweep.forget.is_empty(), "{key:?} must not be forgotten");
            assert_eq!(sweep.warnings.len(), 1, "{key:?}: {:?}", sweep.warnings);
        }
        assert!(victim.exists());
    }

    #[cfg(unix)]
    #[test]
    fn an_orphan_behind_a_symlinked_directory_is_refused() {
        let outer = tmp();
        let root = outer.path().join("app");
        let elsewhere = outer.path().join("elsewhere");
        fs::create_dir_all(&root).unwrap();
        fs::create_dir_all(&elsewhere).unwrap();
        fs::write(elsewhere.join("victim.rs"), "x").unwrap();
        std::os::unix::fs::symlink(&elsewhere, root.join("src")).unwrap();

        let p = crafted(&root, "src/victim.rs");
        let sweep = plan_sweep(&root, &p, ME, &[create(&root, "src/new.rs")], &[]);

        assert!(sweep.remove.is_empty());
        assert_eq!(sweep.warnings.len(), 1, "{:?}", sweep.warnings);
        assert!(elsewhere.join("victim.rs").exists());
    }

    #[cfg(unix)]
    #[test]
    fn a_symlinked_orphan_is_refused() {
        let outer = tmp();
        let root = outer.path().join("app");
        fs::create_dir_all(root.join("src")).unwrap();
        let victim = outer.path().join("victim.rs");
        fs::write(&victim, "x").unwrap();
        std::os::unix::fs::symlink(&victim, root.join("src/old.rs")).unwrap();

        let p = crafted(&root, "src/old.rs");
        let sweep = plan_sweep(&root, &p, ME, &[create(&root, "src/new.rs")], &[]);

        assert!(sweep.remove.is_empty());
        assert_eq!(sweep.warnings.len(), 1, "{:?}", sweep.warnings);
    }

    #[test]
    fn a_directory_at_the_orphan_path_is_kept() {
        let dir = tmp();
        let root = dir.path();
        fs::create_dir_all(root.join("src/old.rs")).unwrap();
        let p = crafted(root, "src/old.rs");

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/new.rs")], &[]);

        assert!(sweep.remove.is_empty());
        assert!(sweep.forget.is_empty());
        assert_eq!(sweep.warnings.len(), 1, "{:?}", sweep.warnings);
    }

    #[test]
    fn an_orphan_a_mod_line_still_declares_is_kept() {
        // v1 wrote `src/jobs/foo.rs` and `pub mod foo;`. v2 names `foo_job.rs`,
        // so its revert misses `pub mod foo;`. Deleting `foo.rs` would stop
        // the build.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(root, &mut p, "src/jobs/foo.rs", "x", ME, Some(Scope::Owned));
        fs::write(root.join("src/jobs/mod.rs"), "pub mod bar;\npub mod foo;\n").unwrap();

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/jobs/foo_job.rs")], &[]);

        assert!(sweep.remove.is_empty());
        assert_eq!(sweep.warnings.len(), 1, "{:?}", sweep.warnings);
        assert!(
            sweep.warnings[0].contains("still names it"),
            "{:?}",
            sweep.warnings
        );
        assert!(old.exists());
    }

    #[test]
    fn an_orphan_declared_in_main_rs_is_kept() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        generated(root, &mut p, "src/helpers.rs", "x", ME, Some(Scope::Owned));
        fs::write(root.join("src/main.rs"), "mod helpers;\nfn main() {}\n").unwrap();

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/new.rs")], &[]);

        assert!(sweep.remove.is_empty());
    }

    #[test]
    fn an_orphan_declared_in_a_sibling_module_file_is_kept() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        generated(root, &mut p, "src/jobs/foo.rs", "x", ME, Some(Scope::Owned));
        fs::write(root.join("src/jobs.rs"), "pub mod foo {}\n").unwrap();

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/jobs/new.rs")], &[]);

        assert!(sweep.remove.is_empty());
    }

    #[test]
    fn an_orphan_an_inline_parent_module_declares_is_kept() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(root, &mut p, "src/jobs/foo.rs", "x", ME, Some(Scope::Owned));
        fs::write(
            root.join("src/main.rs"),
            "mod jobs {\n    pub mod foo;\n}\nfn main() {}\n",
        )
        .unwrap();

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/jobs/new.rs")], &[]);

        assert!(sweep.remove.is_empty(), "{:?}", sweep.remove);
        assert!(old.exists());
    }

    #[test]
    fn an_orphan_mod_rs_its_directory_module_declares_is_kept() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(
            root,
            &mut p,
            "src/teams/mod.rs",
            "x",
            ME,
            Some(Scope::Owned),
        );
        fs::write(root.join("src/main.rs"), "mod teams;\nfn main() {}\n").unwrap();

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/teams/new.rs")], &[]);

        assert!(sweep.remove.is_empty(), "{:?}", sweep.remove);
        assert!(old.exists());
    }

    #[test]
    fn mentions_matches_only_the_whole_word() {
        assert!(mentions("pub mod foo;", "foo"));
        assert!(mentions("mod /* generated */ foo;", "foo"));
        assert!(mentions("mod\tfoo;", "foo"));
        assert!(mentions("mod r#foo;", "foo"));
        assert!(mentions("foo", "foo"));
        assert!(!mentions("pub mod foo_bar;", "foo"));
        assert!(!mentions("pub mod barfoo;", "foo"));
        assert!(!mentions("pub mod bar;", "foo"));
    }

    #[test]
    fn an_orphan_that_names_only_itself_is_swept() {
        // The orphan's own text is not a reference to it.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(
            root,
            &mut p,
            "src/jobs/foo.rs",
            "pub fn foo() {}\n",
            ME,
            Some(Scope::Owned),
        );

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/jobs/new.rs")], &[]);

        assert_eq!(sweep.remove, vec![old]);
    }

    #[test]
    fn an_orphan_a_path_attribute_loads_is_kept() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = generated(root, &mut p, "src/jobs/foo.rs", "x", ME, Some(Scope::Owned));
        fs::write(
            root.join("src/main.rs"),
            "#[path = \"jobs/foo.rs\"]\nmod bar;\nfn main() {}\n",
        )
        .unwrap();

        let sweep = plan_sweep(root, &p, ME, &[create(root, "src/jobs/new.rs")], &[]);

        assert!(sweep.remove.is_empty(), "{:?}", sweep.remove);
        assert!(old.exists());
    }

    #[test]
    fn an_orphan_named_through_a_raw_path_or_a_comment_is_kept() {
        for main in [
            "#[path = r\"jobs/foo.rs\"]\nmod bar;\nfn main() {}\n",
            "mod jobs { mod /* generated */ foo; }\nfn main() {}\n",
        ] {
            let dir = tmp();
            let root = dir.path();
            let mut p = Provenance::default();
            let old = generated(root, &mut p, "src/jobs/foo.rs", "x", ME, Some(Scope::Owned));
            fs::write(root.join("src/main.rs"), main).unwrap();

            let sweep = plan_sweep(root, &p, ME, &[create(root, "src/jobs/new.rs")], &[]);

            assert!(sweep.remove.is_empty(), "{main}: {:?}", sweep.remove);
            assert!(old.exists());
        }
    }

    #[test]
    fn a_revert_target_is_left_to_the_revert() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let target = generated(
            root,
            &mut p,
            "src/jobs/list.rs",
            "x",
            ME,
            Some(Scope::Owned),
        );

        let sweep = plan_sweep(
            root,
            &p,
            ME,
            &[create(root, "src/jobs/new.rs")],
            &[target.as_path()],
        );

        assert_eq!(sweep, Sweep::default());
    }

    #[test]
    fn a_missing_migration_or_protected_entry_is_forgotten() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let migration = generated(
            root,
            &mut p,
            "migrations/20260101000000_create_widgets/up.sql",
            "x",
            ME,
            Some(Scope::Owned),
        );
        let dotfile = generated(root, &mut p, ".env.example", "x", ME, Some(Scope::Owned));
        fs::remove_file(&migration).unwrap();
        fs::remove_file(&dotfile).unwrap();

        let mut sweep = plan_sweep(root, &p, ME, &[], &[]);
        sweep.forget.sort();

        assert_eq!(sweep.forget, vec![dotfile, migration]);
        assert!(sweep.warnings.is_empty(), "{:?}", sweep.warnings);
    }

    #[test]
    fn windows_aliases_are_not_plain_parts() {
        for key in ["Cargo.toml.", "src/main.rs ", "PROGRA~1/x.rs", "src/a.rs."] {
            assert!(plain_parts(key).is_none(), "{key:?}");
        }
        assert_eq!(plain_parts("src/a.rs"), Some(vec!["src", "a.rs"]));
    }

    #[test]
    fn a_differently_spelled_name_is_refused_where_it_resolves() {
        // Only a case-insensitive file system resolves `SRC/old.rs` to
        // `src/old.rs`. There, the exact-name check must refuse it.
        let dir = tmp();
        let root = dir.path();
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(root.join("src/old.rs"), "x").unwrap();
        if !root.join("SRC/old.rs").exists() {
            return; // case-sensitive: the alias is simply missing.
        }
        let p = crafted(root, "SRC/old.rs");

        let sweep = plan_sweep(root, &p, ME, &[create(root, "SRC/new.rs")], &[]);

        assert!(sweep.remove.is_empty());
        assert!(root.join("src/old.rs").exists());
    }

    #[test]
    fn still_sweepable_rechecks_the_path() {
        let dir = tmp();
        let root = dir.path();
        fs::create_dir_all(root.join("src")).unwrap();
        let file = root.join("src/old.rs");
        fs::write(&file, "x").unwrap();
        let digest = text_digest("x");
        assert!(still_sweepable(root, &file, &digest));
        fs::write(&file, "edited").unwrap();
        assert!(!still_sweepable(root, &file, &digest), "an edit saved late");
        fs::remove_file(&file).unwrap();
        assert!(!still_sweepable(root, &file, &digest));
        assert!(!still_sweepable(root, &root.join("../x.rs"), &digest));
    }
}