freshl 0.20260603.1

Modern ls replacement with git awareness
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
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
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
// Copyright © 2026 Michael Shields
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use std::path::{Component, Path, PathBuf};

use gix::bstr::BStr;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PorcelainCode {
    pub index: char,
    pub worktree: char,
}

impl PorcelainCode {
    pub const BLANK: Self = Self {
        index: ' ',
        worktree: ' ',
    };
    pub const CLEAN: Self = Self {
        index: '',
        worktree: ' ',
    };
    pub const UNTRACKED: Self = Self {
        index: '?',
        worktree: '?',
    };
    pub const IGNORED: Self = Self {
        index: '·',
        worktree: '·',
    };
    pub const MODIFIED_WORKTREE: Self = Self {
        index: ' ',
        worktree: '',
    };
    pub const DELETED_WORKTREE: Self = Self {
        index: ' ',
        worktree: '',
    };
    pub const TYPE_CHANGE_WORKTREE: Self = Self {
        index: ' ',
        worktree: '',
    };
    pub const RENAMED: Self = Self {
        index: '',
        worktree: ' ',
    };
    pub const COPIED: Self = Self {
        index: '',
        worktree: ' ',
    };
    pub const RENAMED_WORKTREE: Self = Self {
        index: ' ',
        worktree: '',
    };
    pub const COPIED_WORKTREE: Self = Self {
        index: ' ',
        worktree: '',
    };
    pub const UNMERGED: Self = Self {
        index: '',
        worktree: '',
    };
    pub const DIRTY_SUBTREE: Self = Self {
        index: '',
        worktree: ' ',
    };

    #[must_use]
    pub const fn with_index(self, idx: char) -> Self {
        Self {
            index: idx,
            worktree: self.worktree,
        }
    }

    /// The single glyph rendered for this code: worktree wins, index is the fallback.
    #[must_use]
    pub const fn glyph(self) -> char {
        if self.worktree == ' ' {
            self.index
        } else {
            self.worktree
        }
    }
}

/// Per-repository view used for status rendering.
///
/// The lookup invariant: `PorcelainCode::CLEAN` is returned *only* when the
/// path has positive proof of being in the index. Anything else is
/// `IGNORED`, `UNTRACKED`, or one of the change codes — never `CLEAN` by
/// default. Achieving that requires three sources of truth:
///   - `statuses`: what the status walk reported (changes + collapsed
///     untracked/ignored dirs).
///   - `tracked_prefixes`: every indexed path *and* all of its ancestor
///     directories, so a directory row counts as "tracked" iff at least one
///     of its descendants is in the index.
///   - `excludes`: a gix exclude stack consulted on demand for paths that
///     are neither in `statuses` nor in `tracked_prefixes`.
///
/// `repo` is held because the detached exclude stack's `at_path` call
/// requires the repository's object database to resolve in-tree
/// `.gitignore` files.
pub struct Snapshot {
    pub root: PathBuf,
    pub statuses: HashMap<PathBuf, PorcelainCode>,
    dirty_ancestors: HashSet<PathBuf>,
    tracked_prefixes: HashSet<PathBuf>,
    /// Index entries with `Mode::COMMIT` — submodule gitlinks. The parent
    /// repo doesn't track contents under these paths; the submodule does.
    /// Used by `lookup_rel` to classify submodule descendants as CLEAN
    /// instead of UNTRACKED.
    submodule_roots: HashSet<PathBuf>,
    repo: gix::Repository,
    excludes: RefCell<gix::worktree::Stack>,
}

impl std::fmt::Debug for Snapshot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // `gix::worktree::Stack` doesn't impl Debug; render a compact view.
        f.debug_struct("Snapshot")
            .field("root", &self.root)
            .field("statuses", &self.statuses)
            .field("dirty_ancestors", &self.dirty_ancestors)
            .field("tracked_prefixes_len", &self.tracked_prefixes.len())
            .field("submodule_roots", &self.submodule_roots)
            .finish_non_exhaustive()
    }
}

impl Snapshot {
    /// Resolve `path` to its `PorcelainCode`.
    ///
    /// Unknown paths are classified as `UNTRACKED` (or `IGNORED` if the
    /// exclude stack matches) — never `CLEAN`. `CLEAN` is reserved for
    /// paths the index has positive proof of (see `lookup_rel`).
    /// `PorcelainCode::BLANK` is returned for paths outside the snapshot's
    /// workdir (so cross-repo arguments render no glyph instead of a spurious
    /// `?`) and for the repo's own `.git` directory and anything beneath it
    /// (the git column has nothing meaningful to say about its own metadata).
    ///
    /// Filesystem kind probing is deferred to the cold path — only the
    /// exclude check needs it, so `lookup`'s common case (path is in
    /// `statuses`/`tracked_prefixes`) avoids any `stat` syscall.
    ///
    /// Path normalisation tries lexical absolutisation first (cheap, preserves
    /// symlink identity for entries that are themselves symlinks). If the
    /// lexical result fails to land inside `self.root` or contains unresolved
    /// `..` components, it falls back to [`std::fs::canonicalize`] — that
    /// covers symlinked workdirs and `freshl ..` style paths.
    #[must_use]
    pub fn lookup(&self, path: &Path) -> PorcelainCode {
        let Some(rel) = self.relativize(path) else {
            return PorcelainCode::BLANK;
        };
        // `symlink_metadata` (lstat) so a symlink itself reports `is_dir=false`,
        // matching git's "symlinks to directories are not considered directories
        // for the purpose of matching" rule. `metadata` would follow the link
        // and cause directory-only patterns (e.g. `vendor/`) to match symlinks.
        self.lookup_rel(&rel, || {
            std::fs::symlink_metadata(path).ok().map(|m| m.is_dir())
        })
    }

    /// Resolve `rel` to its `PorcelainCode`. `kind_resolver` is called at most
    /// once and only when the exclude check needs to know whether `rel` is a
    /// directory (i.e. only on the cold path).
    fn lookup_rel<F: FnOnce() -> Option<bool>>(
        &self,
        rel: &Path,
        kind_resolver: F,
    ) -> PorcelainCode {
        // The repo's own metadata at `.git` isn't source-controlled (a
        // directory in a primary worktree, a linkfile in a secondary
        // worktree). `Path::starts_with` matches component-wise, so this
        // catches `.git` and `.git/HEAD` but not sibling names like
        // `.gitignore`, and not a nested `subdir/.git` — the latter is
        // either a submodule linkfile (resolved to CLEAN below because
        // its `subdir` ancestor is in `submodule_roots`) or a stray file
        // (falls through to UNTRACKED).
        if rel.starts_with(".git") {
            return PorcelainCode::BLANK;
        }
        // Positive index proof: `rel` (or a descendant) is in the index, so it
        // belongs to the tracked tree. gix's worktree walk can collapse a
        // directory whose *on-disk* content is wholly untracked into a single
        // UNTRACKED/IGNORED entry even when the index still tracks a file there
        // that was deleted from the worktree. That collapsed entry — on `rel`
        // itself, or inherited from a collapsed ancestor — must not override the
        // index proof, or the directory would render `?`/`·`, violating the
        // CLEAN-requires-proof invariant. Resolve it to CLEAN; `display_code_for`
        // then refines it to DIRTY_SUBTREE because the subtree has changes.
        let tracked_prefix = self.tracked_prefixes.contains(rel);
        if let Some(code) = self.statuses.get(rel).copied()
            && !(tracked_prefix && is_collapsed_dir(code))
        {
            return code;
        }
        if !tracked_prefix {
            for ancestor in iter_ancestors(rel) {
                if let Some(code) = self.statuses.get(ancestor).copied()
                    && (code == PorcelainCode::UNTRACKED || code == PorcelainCode::IGNORED)
                {
                    return code;
                }
                // A submodule gitlink ancestor means the parent repo delegates
                // this subtree to the submodule — classify descendants as CLEAN
                // so the listing doesn't drown in spurious `?` glyphs.
                if self.submodule_roots.contains(ancestor) {
                    return PorcelainCode::CLEAN;
                }
            }
        }
        // The status walk had no overriding entry for this path. Resolve by
        // positive proof: CLEAN requires the path (or a descendant) to be in the
        // index; otherwise it's IGNORED (matches an exclude rule) or UNTRACKED.
        if tracked_prefix {
            return PorcelainCode::CLEAN;
        }
        if self.path_is_excluded(rel, kind_resolver()) {
            PorcelainCode::IGNORED
        } else {
            PorcelainCode::UNTRACKED
        }
    }

    fn path_is_excluded(&self, rel: &Path, is_directory: Option<bool>) -> bool {
        // Unknown kind (e.g. lookup on a path that doesn't exist on disk):
        // try both modes. Patterns either gate on `MUST_BE_DIR` or don't,
        // so checking both is a strict superset — no risk of a false hit.
        is_directory.map_or_else(
            || self.check_excluded(rel, true) || self.check_excluded(rel, false),
            |d| self.check_excluded(rel, d),
        )
    }

    fn check_excluded(&self, rel: &Path, is_directory: bool) -> bool {
        let mode = if is_directory {
            gix::index::entry::Mode::DIR
        } else {
            gix::index::entry::Mode::FILE
        };
        // `is_ok_and` short-circuits an `at_path` error to "not excluded".
        // The exclude stack reads `.gitignore` files lazily; a transient
        // I/O error mid-walk shouldn't crash the lookup.
        self.excludes
            .borrow_mut()
            .at_path(rel, Some(mode), &self.repo.objects)
            .is_ok_and(|p| p.is_excluded())
    }

    #[must_use]
    pub fn is_ignored(&self, path: &Path) -> bool {
        self.lookup(path) == PorcelainCode::IGNORED
    }

    /// Whether `path` is git-ignored, using a caller-supplied directory flag
    /// instead of an `lstat`. For a caller that already knows the entry's kind
    /// (e.g. recursion gating) this matches [`Self::is_ignored`], and — unlike
    /// [`Self::display_code_for`] — it never runs the empty-directory subtree
    /// walk, which is irrelevant to ignore status.
    #[must_use]
    pub fn is_ignored_with_kind(&self, path: &Path, is_directory: bool) -> bool {
        self.relativize(path).is_some_and(|rel| {
            self.lookup_rel(&rel, || Some(is_directory)) == PorcelainCode::IGNORED
        })
    }

    /// Ignored descendants don't count — otherwise vendored/build trees would
    /// flag every ancestor.
    #[must_use]
    pub fn has_dirty_descendants(&self, path: &Path) -> bool {
        let Some(rel) = self.relativize(path) else {
            return false;
        };
        self.dirty_ancestors.contains(&rel)
    }

    /// Directory-aware refinement of [`Self::lookup`]:
    ///   - `DIRTY_SUBTREE` for a tracked-clean directory whose subtree has
    ///     dirty descendants.
    ///   - `BLANK` for an *empty* untracked directory — one with no file
    ///     anywhere beneath it. Git tracks files, not directories, so it
    ///     reports nothing for an empty dir; rendering `?` would be wrong.
    ///     `mkdir -p x/y/z` leaves `x` blank; a single file beneath it makes
    ///     it `?`. (An explicitly *ignored* empty dir stays `·`, matching
    ///     `git status --ignored`, which lists `!! dir/` but never an empty
    ///     untracked dir.)
    ///
    /// Otherwise behaves like [`Self::lookup`]. Single path-normalisation for
    /// all checks. Outside-root paths return [`PorcelainCode::BLANK`] (no
    /// glyph), matching [`Self::lookup`].
    #[must_use]
    pub fn display_code_for(&self, path: &Path, is_directory: bool) -> PorcelainCode {
        let Some(rel) = self.relativize(path) else {
            return PorcelainCode::BLANK;
        };
        let direct = self.lookup_rel(&rel, || Some(is_directory));
        if direct == PorcelainCode::CLEAN && is_directory && self.dirty_ancestors.contains(&rel) {
            PorcelainCode::DIRTY_SUBTREE
        } else if direct == PorcelainCode::UNTRACKED
            && is_directory
            && !subtree_contains_file(&self.root.join(&rel))
        {
            // An empty directory — no file anywhere beneath it — has nothing
            // git can track, so git reports no status for it: render blank, not
            // `?`. The walk short-circuits at the first file, so a directory
            // with content costs ~one `read_dir`. `statuses` can't pre-filter
            // this: gix's dirwalk emits some empty untracked directories as
            // entries, so membership there doesn't prove content. Walk the
            // canonical in-root path (`root` + `rel`) so it's exactly the
            // directory `lookup_rel` just classified, however `path` was spelled.
            PorcelainCode::BLANK
        } else {
            direct
        }
    }

    fn relativize(&self, path: &Path) -> Option<PathBuf> {
        let abs = std::path::absolute(path).ok();
        let candidate: &Path = abs.as_deref().unwrap_or(path);
        if let Ok(rel) = candidate.strip_prefix(&self.root) {
            // `std::path::absolute` strips all `.` components (both leading
            // and interior) on POSIX, so we only have to watch for `..`,
            // which it preserves and which would mis-key the status lookup.
            let has_dotdot = rel.components().any(|c| matches!(c, Component::ParentDir));
            if !has_dotdot {
                return Some(rel.to_path_buf());
            }
        }
        // Canonicalise the parent and re-attach the leaf so directory
        // symlinks (e.g. macOS `/var` → `/private/var`) and `..` components
        // resolve, but a symlinked entry isn't dereferenced into its target.
        // When the path has no separable parent+name (single-component, `.`,
        // `..`, `/`), canonicalising the whole path is safe — those forms
        // can't themselves be the symlinked entry we're trying to look up.
        let resolved = match (path.parent(), path.file_name()) {
            (Some(parent), Some(name)) => {
                let to_canon: &Path = if parent.as_os_str().is_empty() {
                    Path::new(".")
                } else {
                    parent
                };
                std::fs::canonicalize(to_canon).ok()?.join(name)
            }
            _ => std::fs::canonicalize(path).ok()?,
        };
        resolved
            .strip_prefix(&self.root)
            .ok()
            .map(Path::to_path_buf)
    }
}

/// Caches snapshots keyed by canonical repository workdir.
///
/// The status walk is always full-repo (empty pathspec) — pathspec-limited
/// walks descend into gitignored subtrees in gix (orders of magnitude
/// slower) for no gain, since `Snapshot::lookup` resolves any path inside
/// the workdir without needing the walk to have been scoped. Multiple
/// targets inside the same repo therefore share a single snapshot.
///
/// `by_scope` is a separate negative/positive cache mapping each scope
/// directory to the canonical workdir it resolves to (or `None` if no
/// repository was found). It saves a second `gix::discover` walk when the
/// same scope is requested twice and caches negative results so `freshl *`
/// in a non-git directory doesn't re-traverse the filesystem per target.
#[derive(Debug, Default)]
pub struct SnapshotCache {
    by_scope: HashMap<PathBuf, Option<PathBuf>>,
    by_workdir: HashMap<PathBuf, Option<Snapshot>>,
}

impl SnapshotCache {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    pub fn for_target(&mut self, target: &Path) -> Option<&Snapshot> {
        let scope = normalize_existing(&scope_dir(target))?;
        if !self.by_scope.contains_key(&scope) {
            self.populate_scope(&scope);
        }
        let workdir = self.by_scope.get(&scope)?.clone()?;
        self.by_workdir.get(&workdir)?.as_ref()
    }

    fn populate_scope(&mut self, scope: &Path) {
        // `and_then` chains the two failure modes — no repository, or a
        // bare repo with no workdir — into a single `None` so the negative
        // cache only needs one insertion point.
        let resolved = gix::discover(scope).ok().and_then(|repo| {
            repo.workdir()
                .and_then(normalize_existing)
                .map(|wd| (repo, wd))
        });
        let Some((repo, workdir)) = resolved else {
            self.by_scope.insert(scope.to_path_buf(), None);
            return;
        };
        self.by_scope
            .insert(scope.to_path_buf(), Some(workdir.clone()));
        if self.by_workdir.contains_key(&workdir) {
            return;
        }
        let snap = build_snapshot(repo, workdir.clone());
        self.by_workdir.insert(workdir, snap);
    }
}

fn build_snapshot(repo: gix::Repository, workdir: PathBuf) -> Option<Snapshot> {
    let statuses = collect_statuses(&repo).unwrap_or_default();
    assemble_snapshot(repo, workdir, statuses)
}

fn scope_dir(target: &Path) -> PathBuf {
    if target.is_dir() {
        return target.to_path_buf();
    }
    let parent = target.parent().filter(|p| !p.as_os_str().is_empty());
    parent.map_or_else(|| PathBuf::from("."), Path::to_path_buf)
}

/// Canonicalise where possible (resolves symlinks and `..`); fall back to
/// lexical absolutisation. Returns `None` only when both `canonicalize` and
/// `std::path::absolute` fail — on Unix that essentially means the CWD has
/// been deleted out from under us, at which point we give up rather than
/// guess.
fn normalize_existing(path: &Path) -> Option<PathBuf> {
    std::fs::canonicalize(path)
        .ok()
        .or_else(|| std::path::absolute(path).ok())
}

fn rela_to_pathbuf(b: &BStr) -> PathBuf {
    // gix paths are raw bytes; on Unix go through OsStr directly so non-UTF-8
    // names survive (to_os_str_lossy would replace invalid sequences with U+FFFD).
    PathBuf::from(OsStr::from_bytes(b.as_ref()))
}

#[must_use]
pub fn discover(start: &Path) -> Option<Snapshot> {
    let repo = gix::discover(start).ok()?;
    let workdir = normalize_existing(repo.workdir()?)?;
    let statuses = collect_statuses(&repo).unwrap_or_default();
    assemble_snapshot(repo, workdir, statuses)
}

fn assemble_snapshot(
    repo: gix::Repository,
    workdir: PathBuf,
    statuses: HashMap<PathBuf, PorcelainCode>,
) -> Option<Snapshot> {
    // `index_or_empty` synthesises an empty index on a fresh `git init` (no
    // index file on disk yet); we only get `Err` from a corrupt index file,
    // in which case Snapshot construction has to fail — without a usable
    // index there's no way to honour the CLEAN-requires-proof invariant.
    let index = repo.index_or_empty().ok()?;
    let excludes = repo
        .excludes(
            &index,
            None,
            gix::worktree::stack::state::ignore::Source::WorktreeThenIdMappingIfNotSkipped,
        )
        .ok()?
        .detach();
    let dirty_ancestors = compute_dirty_ancestors(&statuses, &workdir);
    let (tracked_prefixes, submodule_roots) = collect_index_prefixes(&index);
    Some(Snapshot {
        root: workdir,
        statuses,
        dirty_ancestors,
        tracked_prefixes,
        submodule_roots,
        repo,
        excludes: RefCell::new(excludes),
    })
}

fn collect_index_prefixes(index: &gix::index::File) -> (HashSet<PathBuf>, HashSet<PathBuf>) {
    let mut prefixes: HashSet<PathBuf> = HashSet::new();
    let mut submodules: HashSet<PathBuf> = HashSet::new();
    // The repo root itself counts as "has tracked content" so a directory
    // row at the root doesn't fall through to UNTRACKED. The empty path is
    // always present so the root row gets CLEAN treatment in an empty repo
    // too.
    prefixes.insert(PathBuf::new());
    for entry in index.entries() {
        let path = rela_to_pathbuf(entry.path(index));
        if entry.mode.contains(gix::index::entry::Mode::COMMIT) {
            submodules.insert(path.clone());
        }
        for ancestor in path.ancestors() {
            if !prefixes.insert(ancestor.to_path_buf()) {
                break;
            }
        }
    }
    (prefixes, submodules)
}

fn compute_dirty_ancestors(
    statuses: &HashMap<PathBuf, PorcelainCode>,
    workdir: &Path,
) -> HashSet<PathBuf> {
    let mut out = HashSet::new();
    for (path, code) in statuses {
        if *code == PorcelainCode::CLEAN || *code == PorcelainCode::IGNORED {
            continue;
        }
        // An empty untracked directory renders blank — git tracks nothing in
        // it — so it must not flag its ancestors as a dirty subtree. (gix's
        // dirwalk reports some empty untracked dirs as entries.) Only a real
        // empty directory is skipped; an untracked file or symlink is content.
        if *code == PorcelainCode::UNTRACKED && is_empty_dir(&workdir.join(path)) {
            continue;
        }
        for ancestor in iter_ancestors(path) {
            out.insert(ancestor.to_path_buf());
        }
    }
    out
}

/// Whether `code` is a collapsed-directory status (`UNTRACKED`/`IGNORED`) from
/// gix's worktree walk, as opposed to a concrete change. Only these are subject
/// to being overridden by positive index proof in `lookup_rel`; a real change
/// code (modified, deleted, …) on a tracked file is authoritative.
fn is_collapsed_dir(code: PorcelainCode) -> bool {
    code == PorcelainCode::UNTRACKED || code == PorcelainCode::IGNORED
}

// Yields strict ancestors of `rel`, including the empty path (which represents
// the repository root after `relativize`). The repository root itself must
// appear in `dirty_ancestors` so `freshl -d <root>` flags a dirty tree; the
// extra `statuses.get("")` in `lookup_rel` is a harmless miss.
fn iter_ancestors(rel: &Path) -> impl Iterator<Item = &Path> {
    rel.ancestors().skip(1)
}

/// `true` if `dir`'s subtree holds at least one non-directory entry, stopping
/// at the first one rather than walking the whole tree. Tells an empty
/// directory (which git can't track, so it renders blank) from one that holds
/// other entries (renders `?`).
///
/// Any entry that isn't a subdirectory counts as content — regular files,
/// symlinks, and the odd FIFO/socket/device alike — because the directory
/// plainly isn't empty. `file_type` doesn't follow symlinks, so a
/// symlink-to-directory counts as content rather than being descended, which
/// also rules out symlink-loop recursion. A directory that can't be read, or
/// an entry whose kind can't be determined, is treated as content so an
/// unreadable tree keeps its `?` rather than silently going blank.
fn subtree_contains_file(dir: &Path) -> bool {
    let mut stack = vec![dir.to_path_buf()];
    while let Some(current) = stack.pop() {
        let Ok(read) = std::fs::read_dir(&current) else {
            return true;
        };
        for entry in read {
            // A subdirectory: descend. Anything else — a file, symlink, or
            // device, or an entry we can't read or stat — means the directory
            // isn't provably empty, so it counts as content.
            match entry.and_then(|e| e.file_type().map(|ft| (ft, e))) {
                Ok((ft, e)) if ft.is_dir() => stack.push(e.path()),
                _ => return true,
            }
        }
    }
    false
}

/// `true` if `abs` is a real (non-symlinked) directory with no file anywhere
/// beneath it. Keeps empty untracked directories — which render blank, since
/// git tracks nothing in them — from marking their ancestors as a dirty
/// subtree. `symlink_metadata` (not `metadata`) so a symlink reports `false`:
/// git stores a symlink as content, so it should still flag its ancestors.
///
/// [`Snapshot::display_code_for`] makes the analogous emptiness check (via
/// [`subtree_contains_file`]) for the directory's own glyph; keep the two in
/// step so a leaf's blank column and its parent's dirty-subtree mark agree.
fn is_empty_dir(abs: &Path) -> bool {
    abs.symlink_metadata().is_ok_and(|m| m.is_dir()) && !subtree_contains_file(abs)
}

fn collect_statuses(
    repo: &gix::Repository,
) -> Result<HashMap<PathBuf, PorcelainCode>, Box<dyn std::error::Error>> {
    let mut out: HashMap<PathBuf, PorcelainCode> = HashMap::new();

    let platform = repo
        .status(gix::progress::Discard)?
        // Collapse a whole-untracked or whole-ignored directory into one entry;
        // files within are absent from the map and inherit via
        // `Snapshot::lookup`'s ancestor walk.
        //
        // Both untracked and ignored must collapse. A directory ignored only by
        // its own `.gitignore` (e.g. uv's `.venv`, ruff's `.ruff_cache` — each
        // holding a `.gitignore` of `*`) matches no exclude rule itself, so gix
        // classifies it untracked and recurses in. Only directory collapse then
        // folds its all-ignored contents back into a single IGNORED entry;
        // `EmissionMode::Matching` would instead emit the individual ignored
        // files and leave the directory row to fall through to UNTRACKED.
        //
        // `emit_collapsed(OnStatusMismatch)` re-emits a collapsed directory's
        // status-mismatched children. Without it, an untracked parent that
        // collapses swallows a wholly-ignored subdir, which then inherits the
        // parent's UNTRACKED; with it, the subdir is re-emitted as IGNORED —
        // matching `git status --ignored`'s dual `?? parent/` + `!! parent/sub/`.
        .untracked_files(gix::status::UntrackedFiles::Collapsed)
        .index_worktree_rewrites(gix::diff::Rewrites::default())
        .dirwalk_options(|opts| {
            opts.emit_ignored(Some(gix::dir::walk::EmissionMode::CollapseDirectory))
                .emit_collapsed(Some(
                    gix::dir::walk::CollapsedEntriesEmissionMode::OnStatusMismatch,
                ))
        });

    // Empty pathspec: always walk the full repo. A non-empty pathspec
    // forces gix to descend into gitignored subtrees (e.g. `node_modules/`),
    // turning what should be ~10 ms into ~1.6 s.
    let iter = platform.into_iter(Vec::new())?;
    for item in iter {
        let item = item?;
        match item {
            gix::status::Item::IndexWorktree(iw) => {
                handle_index_worktree(&iw, &mut out);
            }
            gix::status::Item::TreeIndex(change) => {
                handle_tree_index(&change, &mut out);
            }
        }
    }

    Ok(out)
}

fn handle_index_worktree(
    item: &gix::status::index_worktree::Item,
    out: &mut HashMap<PathBuf, PorcelainCode>,
) {
    use gix::status::plumbing::index_as_worktree::{Change as IwChange, EntryStatus};
    match item {
        gix::status::index_worktree::Item::Modification {
            rela_path, status, ..
        } => {
            let path = rela_to_pathbuf(rela_path.as_ref());
            let code = match status {
                EntryStatus::Change(IwChange::Removed) => PorcelainCode::DELETED_WORKTREE,
                EntryStatus::Change(IwChange::Type { .. }) => PorcelainCode::TYPE_CHANGE_WORKTREE,
                EntryStatus::Conflict { .. } => PorcelainCode::UNMERGED,
                _ => PorcelainCode::MODIFIED_WORKTREE,
            };
            let prev = out.get(&path).copied();
            out.insert(path, merge(prev, code));
        }
        gix::status::index_worktree::Item::DirectoryContents { entry, .. } => {
            let path = rela_to_pathbuf(entry.rela_path.as_ref());
            let code = match entry.status {
                gix::dir::entry::Status::Ignored(_) => PorcelainCode::IGNORED,
                _ => PorcelainCode::UNTRACKED,
            };
            out.insert(path, code);
        }
        gix::status::index_worktree::Item::Rewrite {
            source,
            dirwalk_entry,
            copy,
            ..
        } => {
            let path = rela_to_pathbuf(dirwalk_entry.rela_path.as_ref());
            let code = rewrite_code(*copy);
            let prev = out.get(&path).copied();
            out.insert(path, merge(prev, code));
            // A rename (not a copy) takes the source out of the worktree;
            // the index still has the source path, so `tracked_prefixes`
            // would otherwise claim CLEAN for a file that's gone. Mark the
            // source as DELETED_WORKTREE explicitly. A copy keeps the
            // source on disk, so there's nothing to record for it.
            if !*copy
                && let gix::status::index_worktree::RewriteSource::RewriteFromIndex {
                    source_rela_path,
                    ..
                } = source
            {
                let source_path = rela_to_pathbuf(source_rela_path.as_ref());
                let prev = out.get(&source_path).copied();
                out.insert(source_path, merge(prev, PorcelainCode::DELETED_WORKTREE));
            }
        }
    }
}

fn handle_tree_index(change: &gix::diff::index::Change, out: &mut HashMap<PathBuf, PorcelainCode>) {
    let (rel, idx_char) = match change {
        gix::diff::index::Change::Addition { location, .. } => (location, '+'),
        gix::diff::index::Change::Deletion { location, .. } => (location, ''),
        gix::diff::index::Change::Modification { location, .. } => (location, ''),
        gix::diff::index::Change::Rewrite { location, .. } => (location, ''),
    };
    let path = rela_to_pathbuf(rel);
    let existing = out.get(&path).copied().unwrap_or(PorcelainCode::BLANK);
    out.insert(path, existing.with_index(idx_char));
}

const fn rewrite_code(copy: bool) -> PorcelainCode {
    // Worktree-only rewrites: mark the worktree column so they don't look
    // like staged renames/copies (those go through `handle_tree_index`).
    if copy {
        PorcelainCode::COPIED_WORKTREE
    } else {
        PorcelainCode::RENAMED_WORKTREE
    }
}

fn merge(prev: Option<PorcelainCode>, next: PorcelainCode) -> PorcelainCode {
    prev.map_or(next, |p| PorcelainCode {
        index: if p.index == ' ' { next.index } else { p.index },
        worktree: if next.worktree == ' ' {
            p.worktree
        } else {
            next.worktree
        },
    })
}

#[cfg(test)]
#[expect(
    clippy::significant_drop_tightening,
    reason = "TestRepo intentionally holds GIT_LOCK and TempDir for the entire test scope so parallel git subprocesses can't share index state via environment"
)]
mod tests {
    use super::{PorcelainCode, Snapshot, SnapshotCache, discover, merge};
    use std::path::{Path, PathBuf};
    use std::process::Command;
    use std::sync::{Mutex, MutexGuard};
    use tempfile::TempDir;

    // The lock serialises `git` subprocesses so cargo's parallel test runner
    // can't have two of them sharing index state via environment.
    static GIT_LOCK: Mutex<()> = Mutex::new(());

    fn run_git(dir: &Path, args: &[&str]) {
        let status = Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .env("HOME", dir)
            .status()
            .unwrap();
        assert!(status.success(), "git {args:?} failed");
    }

    /// Fluent test fixture: a freshly-initialised git repo in a tempdir,
    /// holding `GIT_LOCK` for its lifetime so concurrent tests don't
    /// interleave git subprocesses or share index state via env vars.
    ///
    /// Methods return `&Self` so common setup reads like a builder:
    ///   `r.write("a", b"x").commit(&["a"], "msg").write("a", b"y");`
    struct TestRepo {
        _lock: MutexGuard<'static, ()>,
        dir: TempDir,
    }

    impl TestRepo {
        fn new() -> Self {
            // `unwrap_or_else(into_inner)` keeps a failing test from
            // cascading into ~40 PoisonError failures and masking the real
            // root cause. The lock's job is serialisation; a previous panic
            // doesn't make later acquisitions unsafe.
            let lock = GIT_LOCK
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let dir = tempfile::tempdir().unwrap();
            run_git(dir.path(), &["init", "-q", "-b", "main"]);
            run_git(dir.path(), &["config", "user.email", "t@example.invalid"]);
            run_git(dir.path(), &["config", "user.name", "t"]);
            Self { _lock: lock, dir }
        }

        fn root(&self) -> &Path {
            self.dir.path()
        }

        fn write(&self, rel: &str, content: &[u8]) -> &Self {
            let p = self.dir.path().join(rel);
            if let Some(parent) = p.parent() {
                std::fs::create_dir_all(parent).unwrap();
            }
            std::fs::write(p, content).unwrap();
            self
        }

        fn create_dir(&self, rel: &str) -> &Self {
            std::fs::create_dir_all(self.dir.path().join(rel)).unwrap();
            self
        }

        fn remove_file(&self, rel: &str) -> &Self {
            std::fs::remove_file(self.dir.path().join(rel)).unwrap();
            self
        }

        fn rename(&self, from: &str, to: &str) -> &Self {
            std::fs::rename(self.dir.path().join(from), self.dir.path().join(to)).unwrap();
            self
        }

        fn symlink(&self, target: impl AsRef<Path>, rel: &str) -> &Self {
            std::os::unix::fs::symlink(target, self.dir.path().join(rel)).unwrap();
            self
        }

        fn git(&self, args: &[&str]) -> &Self {
            run_git(self.dir.path(), args);
            self
        }

        /// `git add <add_args>` followed by `git commit -m <msg>`. Pass
        /// `&["."]` to stage everything.
        fn commit(&self, add_args: &[&str], msg: &str) -> &Self {
            let mut add: Vec<&str> = vec!["add"];
            add.extend_from_slice(add_args);
            self.git(&add).git(&["commit", "-q", "-m", msg])
        }

        fn snapshot(&self) -> Snapshot {
            discover(self.dir.path()).expect("repo present")
        }
    }

    fn status_at(snap: &Snapshot, rel: &str) -> PorcelainCode {
        snap.lookup(&snap.root.join(rel))
    }

    // A directory whose tracked file was deleted from the worktree, and whose
    // remaining on-disk content is untracked, gets collapsed to UNTRACKED by
    // gix's dirwalk. It is still a tracked prefix (the file is in the index),
    // so it must render as a dirty subtree, not `?`. Regression for a
    // divergence the git-CLI differential test surfaced.
    #[test]
    fn dir_with_deleted_tracked_file_and_untracked_content_is_dirty_subtree() {
        let r = TestRepo::new();
        r.write("d0/f1", b"base\n").commit(&["d0/f1"], "base");
        r.remove_file("d0/f1");
        r.write("d0/d1/f0", b"x\n"); // untracked, makes d0 look untracked on disk
        let snap = r.snapshot();
        assert_eq!(
            snap.display_code_for(&snap.root.join("d0"), true),
            PorcelainCode::DIRTY_SUBTREE,
            "a directory that still tracks a (deleted) file is a dirty subtree, not untracked"
        );
        // The genuinely untracked leaf is unaffected.
        assert_eq!(status_at(&snap, "d0/d1/f0"), PorcelainCode::UNTRACKED);
    }

    // The same divergence one level deeper: the tracked file sits under an
    // intermediate directory, so `d0` collapses to UNTRACKED while the tracked
    // prefix that needs protecting is the *ancestor-inherited* `d0/d1`.
    #[test]
    fn nested_tracked_prefix_under_collapsed_untracked_is_dirty_subtree() {
        let r = TestRepo::new();
        r.write("d0/d1/f1", b"base\n").commit(&["d0/d1/f1"], "base");
        r.remove_file("d0/d1/f1");
        r.write("d0/u", b"x\n"); // untracked sibling collapses d0 on disk
        let snap = r.snapshot();
        assert_eq!(
            snap.display_code_for(&snap.root.join("d0"), true),
            PorcelainCode::DIRTY_SUBTREE
        );
        assert_eq!(
            snap.display_code_for(&snap.root.join("d0/d1"), true),
            PorcelainCode::DIRTY_SUBTREE
        );
    }

    #[test]
    fn rewrite_code_distinguishes_copy_and_rename() {
        use super::rewrite_code;
        assert_eq!(rewrite_code(true), PorcelainCode::COPIED_WORKTREE);
        assert_eq!(rewrite_code(false), PorcelainCode::RENAMED_WORKTREE);
    }

    #[test]
    fn merge_returns_next_when_no_prior() {
        let m = merge(None, PorcelainCode::UNTRACKED);
        assert_eq!(m, PorcelainCode::UNTRACKED);
    }

    #[test]
    fn merge_keeps_prior_index_and_takes_next_worktree() {
        let prev = PorcelainCode {
            index: '+',
            worktree: ' ',
        };
        let m = merge(Some(prev), PorcelainCode::MODIFIED_WORKTREE);
        assert_eq!(m.index, '+');
        assert_eq!(m.worktree, '');
    }

    #[test]
    fn merge_keeps_prior_worktree_when_next_is_blank() {
        let prev = PorcelainCode {
            index: ' ',
            worktree: '',
        };
        let next = PorcelainCode {
            index: '',
            worktree: ' ',
        };
        let m = merge(Some(prev), next);
        assert_eq!(m.index, '');
        assert_eq!(m.worktree, '');
    }

    #[test]
    fn lookup_returns_untracked_for_unknown_path_inside_root() {
        // An empty repo with no entries: nothing is tracked, nothing has a
        // status, nothing matches an ignore rule. A path INSIDE the repo
        // root must resolve to UNTRACKED — never CLEAN.
        let r = TestRepo::new();
        assert_eq!(
            r.snapshot().lookup(&r.root().join("ghost")),
            PorcelainCode::UNTRACKED,
        );
    }

    #[test]
    fn lookup_returns_blank_for_path_outside_root() {
        // Outside the snapshot's workdir, lookup has nothing to say — return
        // BLANK so the git column stays empty (no spurious `?` glyph).
        let r = TestRepo::new();
        let sibling = tempfile::tempdir().unwrap();
        assert_eq!(
            r.snapshot().lookup(&sibling.path().join("elsewhere")),
            PorcelainCode::BLANK,
        );
    }

    #[test]
    fn lookup_uses_status_walk_entry_for_known_path() {
        // Stage a tracked-then-modified file: the status walk emits
        // MODIFIED_WORKTREE, which is distinguishable from both the CLEAN
        // outcome (would mean tracked-fine) and the UNTRACKED outcome
        // (would mean the per-path classifier ran). So this test pins the
        // statuses precedence — a regression that reorders statuses vs
        // tracked_prefixes can no longer pass by accident.
        let r = TestRepo::new();
        r.write("a", b"one\n").commit(&["a"], "init");
        r.write("a", b"two\n");
        assert_eq!(
            status_at(&r.snapshot(), "a"),
            PorcelainCode::MODIFIED_WORKTREE,
        );
    }

    #[test]
    fn is_ignored_only_true_for_ignored_code() {
        let r = TestRepo::new();
        r.write(".gitignore", b"ig\n")
            .write("ig", b"x")
            .write("un", b"x");
        let snap = r.snapshot();
        assert!(snap.is_ignored(&r.root().join("ig")));
        assert!(!snap.is_ignored(&r.root().join("un")));
        assert!(!snap.is_ignored(&r.root().join("missing")));
    }

    #[test]
    fn discover_returns_none_outside_repo() {
        let dir = tempfile::tempdir().unwrap();
        assert!(discover(dir.path()).is_none());
    }

    #[test]
    fn discover_returns_some_inside_repo() {
        let dir = tempfile::tempdir().unwrap();
        let _repo = gix::init(dir.path()).unwrap();
        let snap = discover(dir.path()).unwrap();
        let expected = std::fs::canonicalize(dir.path()).unwrap();
        let actual = std::fs::canonicalize(&snap.root).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn discover_reports_untracked_file() {
        let r = TestRepo::new();
        r.write("new", b"x");
        assert_eq!(status_at(&r.snapshot(), "new"), PorcelainCode::UNTRACKED);
    }

    #[test]
    fn discover_reports_ignored_file() {
        let r = TestRepo::new();
        r.write(".gitignore", b"hidden\n").write("hidden", b"x");
        assert_eq!(status_at(&r.snapshot(), "hidden"), PorcelainCode::IGNORED);
    }

    #[test]
    fn discover_reports_modified_worktree() {
        let r = TestRepo::new();
        r.write("a", b"hello\n").commit(&["a"], "x");
        r.write("a", b"different\n");
        assert_eq!(
            status_at(&r.snapshot(), "a"),
            PorcelainCode::MODIFIED_WORKTREE,
        );
    }

    #[test]
    fn discover_reports_deleted_worktree() {
        let r = TestRepo::new();
        r.write("b", b"x").commit(&["b"], "x").remove_file("b");
        assert_eq!(
            status_at(&r.snapshot(), "b"),
            PorcelainCode::DELETED_WORKTREE,
        );
    }

    #[test]
    fn discover_reports_staged_addition() {
        // The tree-vs-index diff needs at least one commit on HEAD to compare against.
        let r = TestRepo::new();
        r.write("seed", b"x").commit(&["seed"], "seed");
        r.write("staged", b"hi").git(&["add", "staged"]);
        assert_eq!(status_at(&r.snapshot(), "staged").index, '+');
    }

    #[test]
    fn discover_reports_staged_modification() {
        let r = TestRepo::new();
        r.write("m", b"one\n").commit(&["m"], "m");
        r.write("m", b"two\n").git(&["add", "m"]);
        assert_eq!(status_at(&r.snapshot(), "m").index, '');
    }

    #[test]
    fn discover_reports_staged_deletion() {
        let r = TestRepo::new();
        r.write("d", b"x")
            .commit(&["d"], "d")
            .git(&["rm", "-q", "d"]);
        assert_eq!(status_at(&r.snapshot(), "d").index, '');
    }

    #[test]
    fn discover_reports_rename_in_worktree() {
        // 40 lines so the similarity threshold inside gix's rewrite detector
        // is comfortably above the default 50% — otherwise the rename is
        // reported as an add+delete pair.
        let r = TestRepo::new();
        let body = "line\n".repeat(40);
        r.write("from", body.as_bytes()).commit(&["from"], "from");
        r.rename("from", "to");
        assert_eq!(
            status_at(&r.snapshot(), "to"),
            PorcelainCode::RENAMED_WORKTREE,
        );
    }

    #[test]
    fn discover_reports_staged_rename() {
        let r = TestRepo::new();
        let body = "line\n".repeat(40);
        r.write("from", body.as_bytes()).commit(&["from"], "from");
        r.git(&["mv", "from", "to"]);
        assert_eq!(status_at(&r.snapshot(), "to").index, '');
    }

    #[test]
    fn discover_reports_unmerged_conflict() {
        let r = TestRepo::new();
        r.write("c", b"base\n").commit(&["c"], "base");
        r.git(&["checkout", "-q", "-b", "other"]);
        r.write("c", b"other\n")
            .git(&["commit", "-q", "-am", "other"]);
        r.git(&["checkout", "-q", "main"]);
        r.write("c", b"main\n")
            .git(&["commit", "-q", "-am", "main"]);
        // git merge exits non-zero on conflict; ignore its status.
        let _ = Command::new("git")
            .arg("-C")
            .arg(r.root())
            .args(["merge", "--no-edit", "-q", "other"])
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .env("HOME", r.root())
            .status()
            .unwrap();
        assert_eq!(status_at(&r.snapshot(), "c"), PorcelainCode::UNMERGED);
    }

    #[test]
    fn discover_reports_type_change() {
        let r = TestRepo::new();
        r.write("t", b"file").commit(&["t"], "t").remove_file("t");
        r.symlink("anything", "t");
        assert_eq!(
            status_at(&r.snapshot(), "t"),
            PorcelainCode::TYPE_CHANGE_WORKTREE,
        );
    }

    #[test]
    fn porcelain_codes_are_distinct() {
        let codes = [
            PorcelainCode::CLEAN,
            PorcelainCode::UNTRACKED,
            PorcelainCode::IGNORED,
            PorcelainCode::MODIFIED_WORKTREE,
            PorcelainCode::DELETED_WORKTREE,
            PorcelainCode::TYPE_CHANGE_WORKTREE,
            PorcelainCode::RENAMED,
            PorcelainCode::COPIED,
            PorcelainCode::RENAMED_WORKTREE,
            PorcelainCode::COPIED_WORKTREE,
            PorcelainCode::UNMERGED,
            PorcelainCode::DIRTY_SUBTREE,
            PorcelainCode::BLANK,
        ];
        for (i, a) in codes.iter().enumerate() {
            for b in &codes[i + 1..] {
                assert_ne!(a, b);
            }
        }
        let with = PorcelainCode::MODIFIED_WORKTREE.with_index('+');
        assert_eq!(with.index, '+');
        assert_eq!(with.worktree, '');
    }

    #[test]
    fn lookup_inherits_untracked_from_collapsed_directory() {
        // Whole-untracked subdirectories are emitted as one collapsed entry
        // by gix; descendants inherit UNTRACKED via the ancestor walk.
        let r = TestRepo::new();
        r.write("dir/file", b"x").write("dir/deeper/file", b"x");
        let snap = r.snapshot();
        assert_eq!(
            snap.lookup(&r.root().join("dir/file")),
            PorcelainCode::UNTRACKED,
        );
        assert_eq!(
            snap.lookup(&r.root().join("dir/deeper/file")),
            PorcelainCode::UNTRACKED,
        );
        // A path outside the collapsed directory and not in the index falls
        // through to UNTRACKED as well — never CLEAN.
        assert_eq!(
            snap.lookup(&r.root().join("other")),
            PorcelainCode::UNTRACKED,
        );
    }

    #[test]
    fn lookup_inherits_ignored_from_ancestor() {
        // A whole-ignored directory is emitted as one collapsed entry; a
        // child path inherits IGNORED via the ancestor walk.
        let r = TestRepo::new();
        r.write(".gitignore", b"ig/\n").write("ig/inside", b"x");
        let snap = r.snapshot();
        assert_eq!(
            snap.lookup(&r.root().join("ig/inside")),
            PorcelainCode::IGNORED,
        );
    }

    #[test]
    fn lookup_marks_dir_ignored_when_internal_gitignore_ignores_all() {
        // uv/ruff write a `.gitignore` of `*` into the dirs they create
        // (`.venv`, `.ruff_cache`); every entry inside is ignored, so git
        // treats the whole directory as ignored. The directory itself matches
        // no exclude rule, so only the status walk's directory collapse can
        // report it — the cold-path exclude check on the directory can't.
        let r = TestRepo::new();
        r.write("seed", b"x").commit(&["."], "init");
        r.write(".venv/.gitignore", b"*\n").write(".venv/lib", b"x");
        let snap = r.snapshot();
        assert_eq!(
            snap.display_code_for(&r.root().join(".venv"), true),
            PorcelainCode::IGNORED,
        );
        // Descendants still inherit IGNORED via the ancestor walk.
        assert_eq!(
            snap.lookup(&r.root().join(".venv/lib")),
            PorcelainCode::IGNORED,
        );
    }

    #[test]
    fn lookup_marks_ignored_subdir_inside_untracked_dir() {
        // A wholly-ignored dir nested inside an *untracked* dir: gix collapses
        // the untracked parent and would swallow the ignored subtree unless
        // emit_collapsed re-emits the status-mismatched child. git agrees —
        // `git status --ignored` shows both `?? newdir/` and `!! newdir/cache/`.
        let r = TestRepo::new();
        r.write("seed", b"x").commit(&["."], "init");
        r.write("newdir/note", b"x") // genuinely untracked
            .write("newdir/cache/.gitignore", b"*\n")
            .write("newdir/cache/data", b"x");
        let snap = r.snapshot();
        assert_eq!(
            snap.display_code_for(&r.root().join("newdir/cache"), true),
            PorcelainCode::IGNORED,
        );
        assert_eq!(
            snap.lookup(&r.root().join("newdir/cache/data")),
            PorcelainCode::IGNORED,
        );
        // The untracked parent and its loose file stay UNTRACKED.
        assert_eq!(
            snap.lookup(&r.root().join("newdir/note")),
            PorcelainCode::UNTRACKED,
        );
        assert_eq!(
            snap.display_code_for(&r.root().join("newdir"), true),
            PorcelainCode::UNTRACKED,
        );
    }

    #[test]
    fn display_ignored_for_subdir_with_only_root_ignored_files() {
        // A subdirectory whose only content is files ignored by a *root*
        // `.gitignore` rule (not the dir's own `.gitignore`, not a `dir/` rule)
        // renders `·`: gix collapses the wholly-ignored directory, matching
        // `git status`, which reports every file beneath it as `!`. This is the
        // "dir whose only content is ignored" backlog case from docs/edge-cases.md.
        let r = TestRepo::new();
        r.write(".gitignore", b"*.log\n")
            .write("seed", b"x")
            .commit(&["."], "init");
        r.write("a/x.log", b"1\n").write("a/y.log", b"2\n");
        let snap = r.snapshot();
        assert_eq!(
            snap.display_code_for(&r.root().join("a"), true),
            PorcelainCode::IGNORED,
        );
        assert_eq!(
            snap.lookup(&r.root().join("a/x.log")),
            PorcelainCode::IGNORED,
        );
    }

    #[test]
    fn display_untracked_for_subdir_mixing_ignored_and_untracked() {
        // Mixed content — one ignored file and one genuinely untracked file —
        // resolves to `?`, not `·`: the untracked file is content git would
        // pick up, so untracked wins. Mirrors `git status` showing both
        // `? a/y.txt` and `! a/x.log`.
        let r = TestRepo::new();
        r.write(".gitignore", b"*.log\n")
            .write("seed", b"x")
            .commit(&["."], "init");
        r.write("a/x.log", b"1\n").write("a/y.txt", b"2\n");
        let snap = r.snapshot();
        assert_eq!(
            snap.display_code_for(&r.root().join("a"), true),
            PorcelainCode::UNTRACKED,
        );
        assert_eq!(
            snap.lookup(&r.root().join("a/x.log")),
            PorcelainCode::IGNORED,
        );
        assert_eq!(
            snap.lookup(&r.root().join("a/y.txt")),
            PorcelainCode::UNTRACKED,
        );
    }

    #[test]
    fn display_clean_for_tracked_subdir_holding_an_ignored_file() {
        // A tracked directory keeps its `○` when it also holds an ignored file:
        // an ignored file is not a change, so the subtree stays clean. Touch the
        // tracked file and the directory becomes `⋯` — the ignored sibling still
        // doesn't count toward the dirty subtree.
        let r = TestRepo::new();
        r.write(".gitignore", b"*.log\n")
            .write("a/t", b"tracked\n")
            .commit(&["."], "init");
        r.write("a/x.log", b"1\n");
        assert_eq!(
            r.snapshot().display_code_for(&r.root().join("a"), true),
            PorcelainCode::CLEAN,
        );
        r.write("a/t", b"changed\n");
        assert_eq!(
            r.snapshot().display_code_for(&r.root().join("a"), true),
            PorcelainCode::DIRTY_SUBTREE,
        );
    }

    #[test]
    fn display_blank_for_empty_untracked_dir() {
        // Git can't track an empty directory, so it reports no status — the
        // git column must be blank, not `?`.
        let r = TestRepo::new();
        r.write("seed", b"x").commit(&["."], "init");
        r.create_dir("empty");
        assert_eq!(
            r.snapshot().display_code_for(&r.root().join("empty"), true),
            PorcelainCode::BLANK,
        );
    }

    #[test]
    fn display_blank_for_deep_empty_dir_chain() {
        // `mkdir -p x/y/z`: no file exists anywhere beneath `x`, so every
        // level renders blank.
        let r = TestRepo::new();
        r.write("seed", b"x").commit(&["."], "init");
        r.create_dir("x/y/z");
        let snap = r.snapshot();
        for rel in ["x", "x/y", "x/y/z"] {
            assert_eq!(
                snap.display_code_for(&r.root().join(rel), true),
                PorcelainCode::BLANK,
                "{rel} should render blank",
            );
        }
    }

    #[test]
    fn display_untracked_for_dir_with_deep_file() {
        // A single file anywhere beneath the directory flips it back to `?`.
        let r = TestRepo::new();
        r.write("seed", b"x").commit(&["."], "init");
        r.write("x/y/z/f", b"data");
        assert_eq!(
            r.snapshot().display_code_for(&r.root().join("x"), true),
            PorcelainCode::UNTRACKED,
        );
    }

    #[test]
    fn display_blank_for_empty_subdir_in_untracked_dir() {
        // An empty dir nested inside an untracked dir that has files elsewhere
        // is still empty itself → blank, while the parent stays `?`.
        let r = TestRepo::new();
        r.write("seed", b"x").commit(&["."], "init");
        r.write("newdir/note", b"x").create_dir("newdir/emptysub");
        let snap = r.snapshot();
        assert_eq!(
            snap.display_code_for(&r.root().join("newdir"), true),
            PorcelainCode::UNTRACKED,
        );
        assert_eq!(
            snap.display_code_for(&r.root().join("newdir/emptysub"), true),
            PorcelainCode::BLANK,
        );
    }

    #[test]
    fn display_ignored_for_empty_explicitly_ignored_dir() {
        // An explicitly-ignored dir matches a rule even when empty (git status
        // --ignored shows `!! build/`), so it stays `·` — only the UNTRACKED
        // fall-through becomes blank.
        let r = TestRepo::new();
        r.write(".gitignore", b"build/\n").commit(&["."], "init");
        r.create_dir("build");
        assert_eq!(
            r.snapshot().display_code_for(&r.root().join("build"), true),
            PorcelainCode::IGNORED,
        );
    }

    #[test]
    fn subtree_contains_file_treats_unreadable_as_content() {
        // `read_dir` fails on a non-directory or a missing path; "can't read"
        // counts as content so the column stays `?` rather than silently blank.
        let tmp = tempfile::tempdir().unwrap();
        let file = tmp.path().join("f");
        std::fs::write(&file, b"x").unwrap();
        assert!(super::subtree_contains_file(&file));
        assert!(super::subtree_contains_file(&tmp.path().join("missing")));
    }

    #[test]
    fn is_ignored_with_kind_tracks_classification() {
        let r = TestRepo::new();
        r.write(".gitignore", b"build/\n")
            .write("seed", b"x")
            .commit(&["."], "init");
        r.create_dir("build").create_dir("plain");
        let snap = r.snapshot();
        assert!(snap.is_ignored_with_kind(&r.root().join("build"), true));
        assert!(!snap.is_ignored_with_kind(&r.root().join("plain"), true));
        // A path outside the workdir can't be relativized → not ignored.
        let outside = tempfile::tempdir().unwrap();
        assert!(!snap.is_ignored_with_kind(&outside.path().join("x"), true));
    }

    #[test]
    fn lookup_does_not_inherit_modified_from_ancestor() {
        // A modified file's status must not bleed onto something that looks
        // like its child (nonsense for regular files; possible for
        // type-change cases).
        let r = TestRepo::new();
        r.write("mod", b"orig\n").commit(&["mod"], "init");
        r.write("mod", b"changed\n");
        let snap = r.snapshot();
        // `mod/inside` doesn't exist; the MODIFIED status of `mod` must
        // not be inherited by phantom descendants.
        assert_ne!(
            snap.lookup(&r.root().join("mod/inside")),
            PorcelainCode::MODIFIED_WORKTREE,
        );
    }

    #[test]
    fn lookup_resolves_dotdot_via_canonicalize_fallback() {
        // The lexical strip yields `sub/../file`; the canonicalize fallback
        // simplifies that to `file` so the lookup matches.
        let r = TestRepo::new();
        r.write("file", b"x").create_dir("sub");
        let canonical_root = std::fs::canonicalize(r.root()).unwrap();
        let weird = canonical_root.join("sub").join("..").join("file");
        assert_eq!(r.snapshot().lookup(&weird), PorcelainCode::UNTRACKED);
    }

    #[test]
    fn lookup_returns_blank_when_canonicalize_lands_outside_root() {
        // A real path that lands outside the snapshot's workdir: `relativize`
        // yields None → lookup returns BLANK so the row renders no glyph.
        let r = TestRepo::new();
        let snap = r.snapshot();
        let sibling = tempfile::tempdir().unwrap();
        std::fs::write(sibling.path().join("file"), b"x").unwrap();
        assert_eq!(
            snap.lookup(&sibling.path().join("file")),
            PorcelainCode::BLANK,
        );
    }

    #[test]
    fn lookup_returns_blank_when_canonicalize_fails() {
        // A `..` path with no real on-disk components forces both lexical
        // strip and canonicalize to fail → relativize yields None → BLANK.
        let r = TestRepo::new();
        assert_eq!(
            r.snapshot()
                .lookup(&r.root().join("missing/../also-missing")),
            PorcelainCode::BLANK,
        );
    }

    #[test]
    fn lookup_preserves_leaf_symlink_via_parent_canonicalisation() {
        // The canonicalize fallback must NOT dereference a leaf symlink — if
        // it did, a symlinked entry would look up under its target's path
        // instead of its own. Set up a TYPE_CHANGE_WORKTREE for `entry` (a
        // committed regular file replaced by a symlink) so the test has a
        // discriminating status code: following the symlink to `/dev/null`
        // would yield a different lookup result entirely (BLANK, since
        // `/dev/null` is outside the snapshot root), so any future
        // regression that follows the leaf symlink will fail loudly.
        let r = TestRepo::new();
        r.write("entry", b"originally a file")
            .commit(&["entry"], "init");
        r.remove_file("entry").symlink("/dev/null", "entry");
        let canonical = std::fs::canonicalize(r.root()).unwrap();
        // Put the directory symlink in a separate tempdir so its path can't
        // share a prefix with `canonical`. On platforms where the tempdir
        // is already canonical (Linux), the lexical strip_prefix would
        // otherwise succeed and yield `via_link/entry`, bypassing the
        // parent-canonicalisation fallback this test exists to cover.
        let link_parent = tempfile::tempdir().unwrap();
        let link_dir = link_parent.path().join("via_link");
        std::os::unix::fs::symlink(&canonical, &link_dir).unwrap();

        let snap = r.snapshot();
        // Reaching `entry` via the directory-symlink path must resolve to
        // TYPE_CHANGE_WORKTREE — the status of the symlink itself, not the
        // status of `/dev/null`.
        assert_eq!(
            snap.lookup(&link_dir.join("entry")),
            PorcelainCode::TYPE_CHANGE_WORKTREE,
        );
    }

    #[test]
    fn lookup_handles_single_component_relative_path() {
        // `Path::new("solo").parent()` is `Some("")`; the fallback must
        // substitute "." so canonicalize doesn't choke on the empty path.
        // CWD during tests is the package root, not under the tempdir, so
        // the path can't be relativized → outside-root → BLANK.
        let r = TestRepo::new();
        assert_eq!(r.snapshot().lookup(Path::new("solo")), PorcelainCode::BLANK);
    }

    #[test]
    fn lookup_handles_path_with_no_file_name() {
        // `Path::new("..").file_name()` is `None`. The fallback must
        // canonicalise the whole path rather than panic via `?`. The parent
        // of the tempdir is outside the root → BLANK.
        let r = TestRepo::new();
        assert_eq!(r.snapshot().lookup(Path::new("..")), PorcelainCode::BLANK);
    }

    #[test]
    fn lookup_returns_blank_for_path_in_unrelated_tempdir() {
        let r = TestRepo::new();
        let snap = r.snapshot();
        let sibling = tempfile::tempdir().unwrap();
        assert_eq!(
            snap.lookup(&sibling.path().join("file")),
            PorcelainCode::BLANK,
        );
    }

    #[test]
    fn snapshot_cache_reuses_entry_for_same_target() {
        let r = TestRepo::new();
        let mut cache = SnapshotCache::new();
        let first_ptr: *const Snapshot = cache.for_target(r.root()).unwrap();
        let second_ptr: *const Snapshot = cache.for_target(r.root()).unwrap();
        assert!(std::ptr::eq(first_ptr, second_ptr));
    }

    #[test]
    fn snapshot_cache_shares_snapshot_across_subdirs_in_same_repo() {
        // Two subdirectories of the same repo must resolve to the *same*
        // snapshot — one full-repo walk, not one per scope. Sharing also
        // ensures the snapshot's `statuses` covers both subtrees so a
        // lookup outside the originally-requested scope still works.
        let r = TestRepo::new();
        r.write("a/tracked", b"x")
            .write("b/tracked", b"x")
            .commit(&["."], "init");
        r.write("a/only_a", b"x").write("b/only_b", b"x");

        let mut cache = SnapshotCache::new();
        let first_ptr: *const Snapshot = cache.for_target(&r.root().join("a")).unwrap();
        let second_ptr: *const Snapshot = cache.for_target(&r.root().join("b")).unwrap();
        assert!(std::ptr::eq(first_ptr, second_ptr));
        let statuses: Vec<_> = cache
            .for_target(&r.root().join("a"))
            .unwrap()
            .statuses
            .keys()
            .cloned()
            .collect();
        assert!(statuses.iter().any(|p| p.ends_with("only_a")));
        assert!(statuses.iter().any(|p| p.ends_with("only_b")));
    }

    #[test]
    fn snapshot_cache_returns_none_outside_repo() {
        let dir = tempfile::tempdir().unwrap();
        let mut cache = SnapshotCache::new();
        assert!(cache.for_target(dir.path()).is_none());
    }

    #[test]
    fn snapshot_cache_returns_none_when_build_fails() {
        // Cache the negative result of `build_snapshot` returning `None`
        // (corrupt index here, same trigger as `discover_returns_none_for_corrupt_index`).
        // The workdir is still recorded in `by_scope`/`by_workdir` so a
        // second lookup is free instead of re-attempting the failed build.
        let r = TestRepo::new();
        let mut bytes = Vec::new();
        bytes.extend_from_slice(b"DIRC");
        bytes.extend_from_slice(&0x99_u32.to_be_bytes());
        bytes.extend_from_slice(&0_u32.to_be_bytes());
        bytes.extend_from_slice(&[0u8; 20]);
        std::fs::write(r.root().join(".git/index"), &bytes).unwrap();
        let mut cache = SnapshotCache::new();
        assert!(cache.for_target(r.root()).is_none());
        assert!(cache.for_target(r.root()).is_none());
    }

    #[test]
    fn snapshot_cache_caches_negative_results() {
        // A non-git directory should only cause one `gix::discover` traversal
        // regardless of how many targets resolve into it. We exercise the
        // public API and then sneak in via the same cache key to confirm the
        // sentinel `None` is recorded.
        let dir = tempfile::tempdir().unwrap();
        let canon = std::fs::canonicalize(dir.path()).unwrap();
        let mut cache = SnapshotCache::new();
        assert!(cache.for_target(dir.path()).is_none());
        // Second call lands on the same canonical scope; the negative result
        // is returned from the map rather than from a fresh walk.
        assert!(cache.for_target(dir.path()).is_none());
        assert!(cache.by_scope.contains_key(&canon));
        assert!(cache.by_scope[&canon].is_none());
    }

    #[test]
    fn scope_dir_for_bare_filename_returns_current_dir() {
        use super::scope_dir;
        // `target.parent()` for a bare filename is `Some("")`; we filter
        // that out and fall back to `.` so the pathspec computation has a
        // real directory to anchor against.
        assert_eq!(scope_dir(Path::new("ghost.txt")), PathBuf::from("."));
    }

    #[test]
    fn normalize_existing_falls_back_to_absolute_for_missing_path() {
        use super::normalize_existing;
        // canonicalize fails because the path doesn't exist, but
        // `std::path::absolute` succeeds lexically.
        let result = normalize_existing(Path::new("/tmp/freshl-definitely-missing-12345"));
        assert_eq!(
            result,
            Some(PathBuf::from("/tmp/freshl-definitely-missing-12345"))
        );
    }

    #[test]
    fn rename_in_worktree_status_uses_worktree_column() {
        // Worktree-only renames should mark the worktree column so they don't
        // visually masquerade as staged changes.
        assert_eq!(PorcelainCode::RENAMED_WORKTREE.index, ' ');
        assert_eq!(PorcelainCode::RENAMED_WORKTREE.worktree, '');
        assert_eq!(PorcelainCode::COPIED_WORKTREE.index, ' ');
        assert_eq!(PorcelainCode::COPIED_WORKTREE.worktree, '');
    }

    #[test]
    fn dirty_ancestors_includes_parents_of_modified_file() {
        let r = TestRepo::new();
        r.write("a/b/c/file", b"orig\n")
            .write("sibling/other", b"x")
            .commit(&["."], "init");
        r.write("a/b/c/file", b"modified\n");
        let snap = r.snapshot();
        assert!(snap.has_dirty_descendants(&r.root().join("a")));
        assert!(snap.has_dirty_descendants(&r.root().join("a/b")));
        assert!(snap.has_dirty_descendants(&r.root().join("a/b/c")));
        assert!(!snap.has_dirty_descendants(&r.root().join("sibling")));
    }

    #[test]
    fn dirty_ancestors_excludes_ignored_descendants() {
        let r = TestRepo::new();
        r.write("dir/tracked", b"x")
            .write(".gitignore", b"dir/hidden\n")
            .commit(&["."], "init");
        r.write("dir/hidden", b"x");
        let snap = r.snapshot();
        // `dir/hidden` is IGNORED; its ancestor `dir` must not be flagged.
        assert!(!snap.has_dirty_descendants(&r.root().join("dir")));
    }

    #[test]
    fn dirty_ancestors_includes_untracked_in_tracked_dir() {
        let r = TestRepo::new();
        r.write("dir/tracked", b"x").commit(&["."], "init");
        r.write("dir/new", b"x");
        let snap = r.snapshot();
        assert!(snap.has_dirty_descendants(&r.root().join("dir")));
    }

    #[test]
    fn dirty_ancestors_does_not_flag_clean_repo() {
        let r = TestRepo::new();
        r.write("file", b"x").commit(&["."], "init");
        let snap = r.snapshot();
        assert!(!snap.has_dirty_descendants(r.root()));
        assert!(!snap.has_dirty_descendants(&r.root().join("file")));
    }

    #[test]
    fn has_dirty_descendants_false_outside_root() {
        let r = TestRepo::new();
        let snap = r.snapshot();
        let sibling = tempfile::tempdir().unwrap();
        assert!(!snap.has_dirty_descendants(&sibling.path().join("dir")));
    }

    #[test]
    fn display_code_for_returns_blank_outside_root() {
        // Outside-root paths can't be relativized; display_code_for matches
        // lookup's BLANK contract so the git column for a cross-repo
        // argument stays empty rather than rendering a misleading `?`.
        let r = TestRepo::new();
        let snap = r.snapshot();
        let sibling = tempfile::tempdir().unwrap();
        assert_eq!(
            snap.display_code_for(&sibling.path().join("dir"), true),
            PorcelainCode::BLANK,
        );
    }

    #[test]
    fn has_dirty_descendants_true_for_root_with_dirty_subtree() {
        // `freshl -d <root>` needs the root row itself to flag a dirty tree.
        let r = TestRepo::new();
        r.write("a", b"x").commit(&["."], "init");
        r.write("a", b"changed");
        let snap = r.snapshot();
        assert!(snap.has_dirty_descendants(r.root()));
        assert_eq!(
            snap.display_code_for(r.root(), true),
            PorcelainCode::DIRTY_SUBTREE,
        );
    }

    #[test]
    fn dirty_ancestors_skips_empty_untracked_dir() {
        // An empty untracked directory tree (`mkdir -p x/y/z`) renders blank,
        // so it must not flag the otherwise-clean root as a dirty subtree:
        // `freshl -d .` stays CLEAN rather than showing `⋯`.
        let r = TestRepo::new();
        r.write("seed", b"x").commit(&["."], "init");
        r.create_dir("x/y/z");
        let snap = r.snapshot();
        assert!(!snap.has_dirty_descendants(r.root()));
        assert_eq!(snap.display_code_for(r.root(), true), PorcelainCode::CLEAN);
    }

    #[test]
    fn dirty_ancestors_includes_untracked_dir_with_content() {
        // A single file beneath an untracked directory makes it real content,
        // so the clean root flags a dirty subtree.
        let r = TestRepo::new();
        r.write("seed", b"x").commit(&["."], "init");
        r.write("bar/f", b"x");
        let snap = r.snapshot();
        assert!(snap.has_dirty_descendants(r.root()));
        assert_eq!(
            snap.display_code_for(r.root(), true),
            PorcelainCode::DIRTY_SUBTREE,
        );
    }

    #[test]
    fn dirty_ancestors_counts_untracked_symlink_as_content() {
        // An untracked symlink is content git stores (a blob), even one whose
        // target is an empty directory, so it must flag its ancestors. Guards
        // the `symlink_metadata`-not-`metadata` choice in `is_empty_dir`:
        // following the link to its empty target would wrongly skip it.
        let r = TestRepo::new();
        r.write("seed", b"x").commit(&["."], "init");
        r.create_dir("target").symlink("target", "link");
        let snap = r.snapshot();
        assert!(snap.has_dirty_descendants(r.root()));
    }

    // ---------- Regression tests for the CLEAN-requires-proof invariant ----

    #[test]
    fn lookup_marks_ignored_dir_when_scope_is_subdir() {
        // The original bug: listing `backend/` (a subdir of the repo) walked
        // status with pathspec `["backend"]`, and gix didn't emit
        // `backend/node_modules/` as IGNORED at the pathspec boundary. The
        // fix consults the exclude stack per-path instead of relying solely
        // on the walk's emissions.
        let r = TestRepo::new();
        r.write(".gitignore", b"node_modules/\n")
            .write("backend/tracked", b"x")
            .commit(&["."], "init");
        r.write("backend/node_modules/anything", b"x");
        let mut cache = SnapshotCache::new();
        let snap = cache
            .for_target(&r.root().join("backend"))
            .expect("repo present");
        assert_eq!(
            snap.display_code_for(&r.root().join("backend/node_modules"), true),
            PorcelainCode::IGNORED,
        );
    }

    #[test]
    fn lookup_marks_untracked_dir_when_scope_is_subdir() {
        // Symmetric regression: a brand-new directory under a subdir scope
        // must resolve to UNTRACKED, not CLEAN.
        let r = TestRepo::new();
        r.write("backend/tracked", b"x").commit(&["."], "init");
        r.write("backend/brand_new/anything", b"x");
        let mut cache = SnapshotCache::new();
        let snap = cache
            .for_target(&r.root().join("backend"))
            .expect("repo present");
        assert_eq!(
            snap.display_code_for(&r.root().join("backend/brand_new"), true),
            PorcelainCode::UNTRACKED,
        );
    }

    #[test]
    fn lookup_marks_clean_only_when_path_in_index() {
        // CLEAN requires positive proof of being in the index. "No change
        // reported" and "exists on disk" don't qualify.
        let r = TestRepo::new();
        r.write("backend/tracked", b"x").commit(&["."], "init");
        let mut cache = SnapshotCache::new();
        let snap = cache
            .for_target(&r.root().join("backend"))
            .expect("repo present");
        assert_eq!(
            snap.lookup(&r.root().join("backend/tracked")),
            PorcelainCode::CLEAN,
        );
        // A path that's not in the index and has no exclude rule must NOT
        // be CLEAN.
        assert_ne!(
            snap.lookup(&r.root().join("backend/never_existed")),
            PorcelainCode::CLEAN,
        );
    }

    #[test]
    fn lookup_marks_brand_new_file_untracked_not_clean() {
        // The core invariant: a brand-new file with no statuses entry and
        // no exclude rule match resolves to UNTRACKED.
        let r = TestRepo::new();
        r.write("seed", b"x").commit(&["."], "init");
        r.write("brand_new", b"x");
        assert_eq!(
            status_at(&r.snapshot(), "brand_new"),
            PorcelainCode::UNTRACKED,
        );
    }

    #[test]
    fn lookup_consults_exclude_stack_for_unwalked_paths() {
        // Paths the status walk didn't see fall through `statuses` and
        // `tracked_prefixes`; the exclude stack is the only thing left to
        // decide IGNORED vs UNTRACKED. Two flavours exercise both
        // `kind_resolver` branches inside `lookup`: missing-on-disk (lstat
        // fails, resolver returns `None`, both DIR and FILE modes are
        // tried) and created-after-the-snapshot (lstat succeeds, resolver
        // returns `Some(false)`, only FILE mode is tried).
        let r = TestRepo::new();
        r.write(".gitignore", b"*.log\n")
            .write("anchor", b"x")
            .commit(&["."], "init");
        let snap = r.snapshot();
        assert_eq!(
            snap.lookup(&r.root().join("missing.log")),
            PorcelainCode::IGNORED,
        );
        r.write("created_after_snapshot.log", b"x");
        assert_eq!(
            snap.lookup(&r.root().join("created_after_snapshot.log")),
            PorcelainCode::IGNORED,
        );
    }

    #[test]
    fn snapshot_debug_emits_non_empty_repr() {
        // The Debug impl is hand-rolled because `gix::worktree::Stack`
        // doesn't impl Debug; this test makes sure it actually compiles
        // and produces a recognisable string for diagnostic output.
        let r = TestRepo::new();
        let snap = r.snapshot();
        let repr = format!("{snap:?}");
        assert!(repr.contains("Snapshot"));
        assert!(repr.contains("tracked_prefixes_len"));
    }

    #[test]
    fn worktree_rename_marks_source_deleted_not_clean() {
        // `mv from to` after committing `from` triggers a single gix
        // Item::Rewrite. The Rewrite arm must record the source as
        // DELETED_WORKTREE — otherwise the source path stays in
        // `tracked_prefixes` (still in the index) and `lookup` would
        // claim CLEAN for a file that no longer exists.
        let r = TestRepo::new();
        // 40 lines so gix's rewrite detector clears its default 50%
        // similarity threshold.
        let body = "line\n".repeat(40);
        r.write("from", body.as_bytes()).commit(&["from"], "from");
        r.rename("from", "to");
        assert_eq!(
            status_at(&r.snapshot(), "from"),
            PorcelainCode::DELETED_WORKTREE,
        );
    }

    #[test]
    fn submodule_contents_resolve_to_clean() {
        // The parent repo only tracks the submodule's gitlink commit, not
        // its contents — but those contents shouldn't render as `?`. With
        // a gitlink in submodule_roots, lookup under the submodule path
        // returns CLEAN (we delegate that subtree to the submodule).
        let r = TestRepo::new();
        // Set up a real inner repo to register as a submodule.
        let inner = tempfile::tempdir().unwrap();
        run_git(inner.path(), &["init", "-q", "-b", "main"]);
        run_git(inner.path(), &["config", "user.email", "t@example.invalid"]);
        run_git(inner.path(), &["config", "user.name", "t"]);
        std::fs::write(inner.path().join("inside"), b"x").unwrap();
        run_git(inner.path(), &["add", "inside"]);
        run_git(inner.path(), &["commit", "-q", "-m", "inner"]);
        // `git submodule add` from a local path; the protocol restriction
        // env var lets file:// urls through in modern git.
        let inner_url = format!("file://{}", inner.path().display());
        let status = Command::new("git")
            .arg("-C")
            .arg(r.root())
            .args(["-c", "protocol.file.allow=always"])
            .args(["submodule", "add", "-q", &inner_url, "submod"])
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .env("HOME", r.root())
            .status()
            .unwrap();
        assert!(status.success(), "git submodule add failed");
        r.commit(&["."], "add submod");
        let snap = r.snapshot();
        assert_eq!(
            snap.lookup(&r.root().join("submod/inside")),
            PorcelainCode::CLEAN,
        );
    }

    #[test]
    fn symlink_to_directory_matching_dir_rule_is_not_ignored() {
        // `man gitignore`: "Symbolic links to directories are not considered
        // directories for the purpose of matching." After the fix,
        // `lookup` uses lstat (so is_dir=false for the symlink itself) and
        // a trailing-slash rule fails to match.
        let r = TestRepo::new();
        r.write(".gitignore", b"vendor/\n")
            .commit(&[".gitignore"], "ig");
        // Symlink target need not exist on disk — gix only consults
        // the link's own kind, not the target.
        r.symlink("/tmp", "vendor");
        let snap = r.snapshot();
        assert_ne!(
            snap.lookup(&r.root().join("vendor")),
            PorcelainCode::IGNORED,
        );
    }

    #[test]
    fn lookup_returns_untracked_when_exclude_stack_at_path_errors() {
        // The exclude stack walks ancestors to push directories. If an
        // ancestor exists as a regular file (not a directory), `at_path`
        // returns an I/O error; `path_is_excluded` swallows it and the
        // lookup falls through to UNTRACKED. Triggering this via a file
        // posing as a parent works regardless of uid (chmod 0o000 doesn't,
        // since root bypasses POSIX read permissions).
        let r = TestRepo::new();
        // `parent` is a regular file; treating "parent/child" as a path
        // forces at_path to fail when it tries to enter `parent` as a dir.
        r.write("parent", b"i'm a file");
        let snap = r.snapshot();
        assert_eq!(
            snap.lookup(&r.root().join("parent/child")),
            PorcelainCode::UNTRACKED,
        );
    }

    #[test]
    fn dot_git_dir_looks_up_as_blank() {
        // The repo's own metadata isn't source-controlled. The git column
        // should render nothing, not a spurious `?` glyph.
        let r = TestRepo::new();
        assert_eq!(
            r.snapshot().lookup(&r.root().join(".git")),
            PorcelainCode::BLANK,
        );
    }

    #[test]
    fn dot_git_descendants_look_up_as_blank() {
        // The short-circuit's prefix clause catches `.git/HEAD`,
        // `.git/config`, and anything else nested under the gitdir.
        let r = TestRepo::new();
        let snap = r.snapshot();
        assert_eq!(
            snap.lookup(&r.root().join(".git/HEAD")),
            PorcelainCode::BLANK,
        );
        assert_eq!(
            snap.lookup(&r.root().join(".git/config")),
            PorcelainCode::BLANK,
        );
    }

    #[test]
    fn display_code_for_dot_git_is_blank() {
        // Renderer-facing API: must also report BLANK so a `freshl ls -a`
        // row for `.git` shows no glyph.
        let r = TestRepo::new();
        assert_eq!(
            r.snapshot().display_code_for(&r.root().join(".git"), true),
            PorcelainCode::BLANK,
        );
    }

    #[test]
    fn display_code_for_consults_exclude_stack_on_missing_path() {
        // Cold-path exercise for `display_code_for`'s `|| Some(is_directory)`
        // resolver, which is a distinct closure type from `lookup`'s
        // `symlink_metadata` resolver. A path that doesn't exist on disk
        // and isn't in the index falls through `statuses` and
        // `tracked_prefixes`; `path_is_excluded` then calls the resolver
        // to pick DIR vs FILE mode for the exclude check.
        let r = TestRepo::new();
        r.write(".gitignore", b"*.log\n")
            .write("anchor", b"x")
            .commit(&["."], "init");
        assert_eq!(
            r.snapshot()
                .display_code_for(&r.root().join("missing.log"), false),
            PorcelainCode::IGNORED,
        );
    }

    #[test]
    fn submodule_dot_git_linkfile_resolves_to_clean() {
        // The submodule's `.git` linkfile is at a nested path
        // (`submod/.git`), so the `.git` short-circuit doesn't fire
        // (`starts_with` is component-wise; the first component is
        // `submod`). It resolves to CLEAN via the ancestor walk, because
        // `submod` is in `submodule_roots`. This pins that the short-
        // circuit doesn't over-match nested `.git` basenames. Setup
        // mirrors submodule_contents_resolve_to_clean.
        let r = TestRepo::new();
        let inner = tempfile::tempdir().unwrap();
        run_git(inner.path(), &["init", "-q", "-b", "main"]);
        run_git(inner.path(), &["config", "user.email", "t@example.invalid"]);
        run_git(inner.path(), &["config", "user.name", "t"]);
        std::fs::write(inner.path().join("inside"), b"x").unwrap();
        run_git(inner.path(), &["add", "inside"]);
        run_git(inner.path(), &["commit", "-q", "-m", "inner"]);
        let inner_url = format!("file://{}", inner.path().display());
        let status = Command::new("git")
            .arg("-C")
            .arg(r.root())
            .args(["-c", "protocol.file.allow=always"])
            .args(["submodule", "add", "-q", &inner_url, "submod"])
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .env("HOME", r.root())
            .status()
            .unwrap();
        assert!(status.success(), "git submodule add failed");
        r.commit(&["."], "add submod");
        assert_eq!(
            r.snapshot().lookup(&r.root().join("submod/.git")),
            PorcelainCode::CLEAN,
        );
    }

    #[test]
    fn dot_git_only_special_at_real_gitdir() {
        // A stray file named `.git` inside a subdirectory (not a
        // submodule, not a nested repo registered with the parent) is
        // *not* this repo's metadata. The short-circuit's component-wise
        // `starts_with` check leaves `subdir/.git` alone (its first
        // component is `subdir`, not `.git`); the ancestor walk inherits
        // UNTRACKED from `subdir`, which gix emits as collapsed-untracked.
        // This pins the check against a refactor to `rel.file_name() ==
        // Some(".git")`, which would over-match here.
        let r = TestRepo::new();
        r.write("subdir/.git", b"not a real linkfile\n");
        let snap = r.snapshot();
        assert_eq!(snap.lookup(&r.root().join(".git")), PorcelainCode::BLANK);
        assert_eq!(
            snap.lookup(&r.root().join("subdir/.git")),
            PorcelainCode::UNTRACKED,
        );
    }

    #[test]
    fn discover_returns_none_for_corrupt_index() {
        // `assemble_snapshot` propagates an `index_or_empty` failure as
        // `None` — a corrupt repo can't satisfy the lookup invariant
        // (we can't tell what's tracked) so refusing to build a snapshot
        // is the right behaviour. The corruption here is a valid header
        // signature with an unsupported version number, which gix rejects
        // cleanly instead of panicking on truncated data.
        let r = TestRepo::new();
        let mut bytes = Vec::new();
        bytes.extend_from_slice(b"DIRC"); // signature
        bytes.extend_from_slice(&0x99_u32.to_be_bytes()); // unsupported version
        bytes.extend_from_slice(&0_u32.to_be_bytes()); // entry count
        // Pad with the trailing SHA-1 (20 zero bytes) so the truncation
        // check doesn't trigger before the version check.
        bytes.extend_from_slice(&[0u8; 20]);
        std::fs::write(r.root().join(".git/index"), &bytes).unwrap();
        assert!(discover(r.root()).is_none());
    }
}