zshrs 0.13.41

The first JIT-compiled Unix shell — bytecode VM, Cranelift JIT, worker pool, AOP intercept, Rkyv caching
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
//! p10k git status backend — native replacement for gitstatusd.
//!
//! Implementation strategy (native `.git` reader, subprocess gated):
//! - Repo discovery + branch/commit/action come from reading `.git` directly:
//!   `.git` may be a file containing `gitdir: <path>` (worktrees/submodules);
//!   `HEAD` is either a symbolic ref (`ref: refs/heads/<branch>`) or a detached
//!   commit hash; in-progress action state (rebase/merge/cherry-pick/bisect/
//!   revert/am) is detected from marker files/dirs in the gitdir, mirroring
//!   gitstatus's action names exactly (gitstatus/src/git.cc `RepoState`, which
//!   itself mirrors libgit2 `git_repository_state`). Branch tips resolve via
//!   loose refs then `packed-refs` in the common dir.
//! - NATIVE fields (no subprocess): branch, commit, action, remote_branch
//!   (from `.git/config` `branch.<name>.remote`/`branch.<name>.merge`,
//!   branch-only name per gitstatus.plugin.zsh:39,97), unstaged + conflicted
//!   (native `.git/index` v2/v3/v4 parse + lstat scan, port of gitstatus
//!   index.cc IsModified), stashes (`.git/logs/refs/stash` reflog line count —
//!   exactly what `git stash list` counts), tag (refs/tags loose scan +
//!   packed-refs peel lines, port of gitstatus tag_db.cc TagForCommit), and
//!   ahead/behind in the common case (upstream tip == HEAD tip, or no
//!   upstream ⇒ 0/0, matching gitstatusd's absent-upstream output).
//! - SUBPROCESS fields (`git status --porcelain=v2 --branch --show-stash`,
//!   ONE exec per cache miss, gated to only these fields):
//!   * staged  — requires diffing the index against the HEAD tree
//!     (gitstatus repo.cc:127-243 does `git_diff_tree_to_index`); reading the
//!     HEAD tree needs the object store (zlib-inflated loose objects and
//!     packfiles) and no inflate impl exists in-tree (Cargo.toml has zstd,
//!     not zlib), so it comes from the porcelain subprocess.
//!   * untracked — requires a faithful .gitignore engine (nested .gitignore,
//!     info/exclude, core.excludesFile, negations, dir-only patterns, `**`),
//!     so it comes from the porcelain subprocess as well.
//!   * ahead/behind when the branch and upstream tips DIVERGE — the commit
//!     count needs an object-store commit walk (same zlib wall as staged);
//!     `# branch.ab` from the porcelain fallback is kept for this case only.
//!   * everything, when the native index parse fails (unsupported version,
//!     sparse-index tree entries, oversized index, corrupt data).
//! - Tag lookup: loose ANNOTATED tags are peeled through one memoised
//!   `git cat-file --batch-check` (the object store needs zlib); packed
//!   tags use the `^<oid>` peel lines (gitstatus peels via libgit2,
//!   tag_db.cc:295-330 TagHasTarget).
//! - Caches: two, with different lifetimes.
//!   * `cache()` — the combined snapshot, per-gitdir, ~2s TTL, additionally
//!     invalidated when `.git/index` or `.git/HEAD` mtime changes. A hit is
//!     a map lookup.
//!   * `sub_cache()` — the last COMPLETED porcelain parse, per-gitdir, no
//!     TTL. It exists because the subprocess is run ASYNCHRONOUSLY, the way
//!     p10k queries gitstatusd: the prompt waits at most
//!     `POWERLEVEL9K_VCS_MAX_SYNC_LATENCY_SECONDS` (0.05 default) and then
//!     renders the LAST KNOWN status while the daemon answers
//!     (p10k:3799-3812). So only the first prompt in a repo ever blocks
//!     (SUBPROCESS_BUDGET); after that the snapshot is served immediately
//!     and a refresh runs on a helper thread, at most one per repo. The
//!     child is never killed — killing it, as this code used to do, threw
//!     away every answer in any repo where `git status` is slower than the
//!     budget, so the segment never rendered AND the full cost was paid
//!     again on the very next prompt.
//!   The cost of that async model is that staged/untracked (and diverged
//!   ahead/behind) can be one prompt stale; every NATIVE field is always
//!   recomputed fresh.
//! - Perf: native path is one ~600KB index read + one lstat per index entry
//!   + a few small ref/config/log reads. The lstat scan dominates and is
//!   latency-bound, so it fans out over up to MAX_STAT_THREADS threads the
//!   way gitstatusd's does (`gitstatusd -t <n>`): measured on this repo at
//!   5,831 entries, 63-132ms serial vs 20-24ms parallel. Indexes over
//!   NATIVE_SCAN_MAX entries skip the native scan to protect the budget.
//! - No new crate dependencies; std only.
//!
//! p10k consumes these fields as the `VCS_STATUS_*` parameters that gitstatusd
//! used to publish (p10k:3775-3783 — `$VCS_STATUS_COMMIT`,
//! `$VCS_STATUS_LOCAL_BRANCH`, `$VCS_STATUS_REMOTE_BRANCH`,
//! `$VCS_STATUS_ACTION`, `$VCS_STATUS_NUM_STAGED`, `$VCS_STATUS_NUM_UNSTAGED`,
//! `$VCS_STATUS_NUM_CONFLICTED`, `$VCS_STATUS_NUM_UNTRACKED`,
//! `$VCS_STATUS_COMMITS_AHEAD`, `$VCS_STATUS_COMMITS_BEHIND`,
//! `$VCS_STATUS_STASHES`, `$VCS_STATUS_TAG`). The tag p10k renders
//! (p10k:3959-3961) is gitstatus's EXACT match of a tag to the HEAD commit
//! (tag_db.cc:119-148 TagForCommit), not a `git describe` nearest-tag.

use crate::extensions::p10k::gitconfig::GitConfig;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::io::Read;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant, SystemTime};

/// One snapshot of a repo's state, shaped after gitstatusd's response fields
/// (gitstatus/src/response.cc) as p10k reads them (p10k:3775-3783).
#[derive(Debug, Clone, Default)]
pub struct GitStatus {
    pub branch: String,
    pub commit: String,
    pub action: String, // rebase/merge/etc, "" if none
    pub ahead: i64,
    pub behind: i64,
    pub staged: i64,
    pub unstaged: i64,
    pub untracked: i64,
    pub conflicted: i64,
    pub stashes: i64,
    pub tag: String,
    pub remote_branch: String,
    /// `VCS_STATUS_REMOTE_URL` — configured URL of the upstream's remote
    /// (gitstatus git.cc:215 `git_remote_url`); "" with no upstream or a
    /// local-branch upstream (`remote = .`).
    pub remote_url: String,
    /// `VCS_STATUS_WORKDIR` — top-level working directory.
    pub workdir: String,
    /// `VCS_STATUS_REMOTE_NAME` — the tracking remote (`.` for a local
    /// upstream branch); "" without a resolvable upstream.
    pub remote_name: String,
    /// `VCS_STATUS_PUSH_REMOTE_NAME` / `_URL` — `branch.<b>.pushRemote`, else
    /// `remote.pushDefault`; "" when it or its tracking ref cannot be
    /// resolved (gitstatus git.cc GetPushRemote).
    pub push_remote_name: String,
    pub push_remote_url: String,
    /// `VCS_STATUS_PUSH_COMMITS_AHEAD` / `_BEHIND` against that ref.
    pub push_ahead: i64,
    pub push_behind: i64,
    /// `VCS_STATUS_INDEX_SIZE` — entries in the index.
    pub index_size: i64,
    /// `VCS_STATUS_NUM_SKIP_WORKTREE` / `_NUM_ASSUME_UNCHANGED`.
    pub skip_worktree: i64,
    pub assume_unchanged: i64,
    /// `VCS_STATUS_NUM_STAGED_NEW` / `_STAGED_DELETED` / `_UNSTAGED_DELETED`,
    /// each at most the matching staged/unstaged count.
    pub staged_new: i64,
    pub staged_deleted: i64,
    pub unstaged_deleted: i64,
    /// `VCS_STATUS_HAS_*` is `-1` (unknown) when the index is larger than
    /// `POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY`.
    pub dirty_unknown: bool,
}

/// The reporting limits p10k hands gitstatusd (`-s -u -d -c -m -e`,
/// p10k:8866-8890): at most this many changes of each kind (negative:
/// unlimited), the index size above which unstaged/untracked are not
/// computed (negative: never), and whether untracked directories are
/// counted file by file.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GitLimits {
    pub max_staged: i64,
    pub max_unstaged: i64,
    pub max_untracked: i64,
    pub max_conflicted: i64,
    pub dirty_max_index_size: i64,
    pub recurse_untracked_dirs: bool,
}

impl Default for GitLimits {
    /// gitstatusd's defaults (options.cc).
    fn default() -> Self {
        GitLimits {
            max_staged: 1,
            max_unstaged: 1,
            max_untracked: 1,
            max_conflicted: 1,
            dirty_max_index_size: -1,
            recurse_untracked_dirs: false,
        }
    }
}

impl GitLimits {
    /// The `POWERLEVEL9K_VCS_*` parameters, with p10k's defaults.
    pub fn from_params() -> Self {
        use crate::extensions::p10k::shared::{global_bool, global_int};
        GitLimits {
            max_staged: global_int("VCS_STAGED_MAX_NUM", 1),
            max_unstaged: global_int("VCS_UNSTAGED_MAX_NUM", 1),
            max_untracked: global_int("VCS_UNTRACKED_MAX_NUM", 1),
            max_conflicted: global_int("VCS_CONFLICTED_MAX_NUM", 1),
            dirty_max_index_size: global_int("VCS_MAX_INDEX_SIZE_DIRTY", -1),
            recurse_untracked_dirs: global_bool("VCS_RECURSE_UNTRACKED_DIRS", false),
        }
    }

    /// `std::min(count, limit)` with a negative limit meaning no limit.
    fn clamp(count: i64, limit: i64) -> i64 {
        if limit < 0 {
            count
        } else {
            count.min(limit)
        }
    }

    /// The part of `GetIndexStats` that follows the scans (repo.cc:205-237):
    /// zero the dirty counts of an oversized index, then apply the maxima.
    fn apply(&self, s: &mut GitStatus, index_size: i64) {
        let too_large = self.dirty_max_index_size >= 0 && index_size > self.dirty_max_index_size;
        if too_large {
            s.unstaged = 0;
            s.untracked = 0;
            s.unstaged_deleted = 0;
        }
        s.dirty_unknown = too_large;
        s.staged = Self::clamp(s.staged, self.max_staged);
        s.unstaged = Self::clamp(s.unstaged, self.max_unstaged);
        s.conflicted = Self::clamp(s.conflicted, self.max_conflicted);
        s.untracked = Self::clamp(s.untracked, self.max_untracked);
        s.staged_new = s.staged_new.min(s.staged);
        s.staged_deleted = s.staged_deleted.min(s.staged);
        s.unstaged_deleted = s.unstaged_deleted.min(s.unstaged);
    }
}

/// Cache TTL. gitstatusd recomputed on every prompt but kept the repo open;
/// we amortize the index scan + subprocess instead.
const CACHE_TTL: Duration = Duration::from_secs(2);
/// Prompt latency budget for the `git status` subprocess.
const SUBPROCESS_BUDGET: Duration = Duration::from_millis(45);
/// Native index scan cap: one lstat per entry; 20k entries ≈ ~10-20ms warm,
/// which is the most the prompt path should ever spend. Bigger indexes fall
/// back to the subprocess for unstaged/conflicted (gitstatus has the same
/// escape hatch via its dirty_max_index_size option).
const NATIVE_SCAN_MAX: usize = 20_000;
/// Index-entry count below which the worktree scan stays on one thread —
/// below this the spawn/join overhead outweighs the latency it hides.
const PAR_STAT_MIN: usize = 512;
/// Upper bound on worktree-scan threads. gitstatusd defaults its pool to the
/// core count (`gitstatusd -t`, gitstatus/src/options.cc), but the prompt is
/// not the only thing running; past ~8 the lstat queue, not the CPU, is the
/// limit.
const MAX_STAT_THREADS: usize = 8;

struct CacheEntry {
    at: Instant,
    head_mtime: Option<SystemTime>,
    index_mtime: Option<SystemTime>,
    limits: GitLimits,
    status: GitStatus,
}

fn cache() -> &'static Mutex<HashMap<PathBuf, CacheEntry>> {
    static CACHE: OnceLock<Mutex<HashMap<PathBuf, CacheEntry>>> = OnceLock::new();
    CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Last completed `git status --porcelain=v2` parse per gitdir, kept apart
/// from `cache()` because it has its OWN lifetime: a background refresh
/// lands here whenever the child finishes, long after the prompt that
/// started it returned. Only the subprocess-only fields of the value are
/// ever read (module doc); the rest is recomputed natively every time.
struct SubEntry {
    at: Instant,
    mode: UntrackedMode,
    status: GitStatus,
}

/// `git status --untracked-files=<mode>`: how untracked files are counted.
#[derive(Clone, Copy, Debug, PartialEq)]
enum UntrackedMode {
    No,
    Normal,
    All,
}

impl UntrackedMode {
    fn arg(self) -> &'static str {
        match self {
            UntrackedMode::No => "--untracked-files=no",
            UntrackedMode::Normal => "--untracked-files=normal",
            UntrackedMode::All => "--untracked-files=all",
        }
    }
}

fn sub_cache() -> &'static Mutex<HashMap<PathBuf, SubEntry>> {
    static SUB: OnceLock<Mutex<HashMap<PathBuf, SubEntry>>> = OnceLock::new();
    SUB.get_or_init(|| Mutex::new(HashMap::new()))
}

/// gitdirs with a `git status` child already running. p10k likewise keeps at
/// most one outstanding gitstatusd request per repo (p10k:3799-3812 —
/// `_p9k_vcs_status_deferred`), so a slow repo cannot pile up work.
fn sub_inflight() -> &'static Mutex<std::collections::HashSet<PathBuf>> {
    static IN: OnceLock<Mutex<std::collections::HashSet<PathBuf>>> = OnceLock::new();
    IN.get_or_init(|| Mutex::new(std::collections::HashSet::new()))
}

/// Bound on both caches — one entry per repo visited, generous because the
/// map is per-repo, not per-directory.
const CACHE_CAP: usize = 64;

/// Start a `git status --porcelain=v2` for `repo` unless one is already
/// running, and wait up to `wait` for it.
///
/// Returns the parse when the child answered inside `wait`. Otherwise the
/// child is NOT killed: it keeps running on its helper thread and stores its
/// answer in `sub_cache()` for the next prompt. That is the gitstatusd
/// contract p10k is written against — the prompt waits at most
/// `POWERLEVEL9K_VCS_MAX_SYNC_LATENCY_SECONDS` (0.05 by default,
/// p10k:7495) and then renders the last known status while the daemon
/// finishes (p10k:3799-3812). Killing the child instead, as this code did
/// before, threw away every answer in any repo where `git status` is slower
/// than the budget — so the snapshot never appeared at all, and the full
/// cost was paid again on the very next prompt.
fn refresh_porcelain(
    repo: &Repo,
    mode: UntrackedMode,
    wait: Option<Duration>,
) -> Option<GitStatus> {
    {
        let mut set = sub_inflight().lock().ok()?;
        if !set.insert(repo.git_dir.clone()) {
            return None; // already refreshing; nothing new to serve yet
        }
    }

    let work_dir = repo.work_dir.clone();
    let git_dir = repo.git_dir.clone();
    let (tx, rx) = mpsc::channel();
    crate::signal_thread::spawn(move || {
        let out = run_porcelain(&work_dir, mode);
        if let Some(out) = out {
            let mut sub = GitStatus::default();
            parse_porcelain_v2(&out, &mut sub);
            if let Ok(mut map) = sub_cache().lock() {
                if map.len() >= CACHE_CAP && !map.contains_key(&git_dir) {
                    evict_oldest(&mut map, |e: &SubEntry| e.at);
                }
                map.insert(
                    git_dir.clone(),
                    SubEntry {
                        at: Instant::now(),
                        mode,
                        status: sub.clone(),
                    },
                );
            }
            let _ = tx.send(sub);
        }
        if let Ok(mut set) = sub_inflight().lock() {
            set.remove(&git_dir);
        }
    });

    match wait {
        Some(d) => rx.recv_timeout(d).ok(),
        None => None,
    }
}

/// Drop the stalest entry of a capped cache.
fn evict_oldest<V>(map: &mut HashMap<PathBuf, V>, at: impl Fn(&V) -> Instant) {
    if let Some(oldest) = map
        .iter()
        .max_by_key(|(_, v)| at(v).elapsed())
        .map(|(k, _)| k.clone())
    {
        map.remove(&oldest);
    }
}

/// Public entry point per the p10k module contract. `dir` is any directory;
/// the repo is discovered by walking up. None when not inside a git repo, or
/// when the first-ever status of a repo exceeds the latency budget.
pub fn git_status_for(dir: &Path) -> Option<GitStatus> {
    git_status_with(dir, &GitLimits::from_params())
}

/// [`git_status_for`] under explicit reporting limits.
pub fn git_status_with(dir: &Path, limits: &GitLimits) -> Option<GitStatus> {
    let repo = discover_repo(dir)?;
    let head_mtime = mtime_of(&repo.git_dir.join("HEAD"));
    let index_mtime = mtime_of(&repo.git_dir.join("index"));

    // Fresh-enough cache hit: TTL not expired AND HEAD/index untouched.
    if let Ok(map) = cache().lock() {
        if let Some(e) = map.get(&repo.git_dir) {
            if e.at.elapsed() < CACHE_TTL
                && e.limits == *limits
                && e.head_mtime == head_mtime
                && e.index_mtime == index_mtime
            {
                return Some(e.status.clone());
            }
        }
    }

    // -------- native layer (no subprocess) --------
    let mut status = GitStatus::default();
    read_head(&repo, &mut status);
    status.workdir = repo.work_dir.to_string_lossy().into_owned();
    status.action = repo_action(&repo.git_dir); // gitstatus git.cc:43-110 RepoState

    // libgit2's view of the configuration: system, XDG, global, the repo's
    // own file and (with extensions.worktreeConfig) config.worktree, with
    // include / includeIf followed.
    let cfg = GitConfig::load_stack(
        &repo.common_dir,
        &repo.git_dir,
        Some(status.branch.as_str()).filter(|b| !b.is_empty()),
    );
    let caps = RepoCaps::from_config(&cfg);

    // Git options gitstatusd honours on top of the -s/-u/-d/-c limits
    // (repo.cc:116-145): a repo that turns untracked or dirty reporting off.
    let mut lim = *limits;
    let off = |section: &str, key: &str| cfg.bool_value(section, key) == Some(false);
    if off("status", "showuntrackedfiles") || off("bash", "showuntrackedfiles") {
        lim.max_untracked = 0;
    }
    if off("bash", "showdirtystate") {
        lim.max_staged = 0;
        lim.max_unstaged = 0;
        lim.max_conflicted = 0;
    }
    let untracked_mode = if lim.max_untracked == 0 {
        UntrackedMode::No
    } else if lim.recurse_untracked_dirs {
        UntrackedMode::All
    } else {
        UntrackedMode::Normal
    };

    // Upstream from branch.<name>.remote / branch.<name>.merge. REMOTE_BRANCH
    // is the branch-only name (gitstatus.plugin.zsh:39 `VCS_STATUS_REMOTE_BRANCH=master`),
    // which is what p10k compares against the local branch (p10k:3967-3968).
    let mut ab_native = false;
    if !status.branch.is_empty() {
        match tracking_of(&cfg, &repo.common_dir, &status.branch) {
            Some(t) => {
                status.remote_branch = t.branch;
                status.remote_name = t.remote.clone();
                // gitstatus git.cc:204-215 — the URL of a real remote.
                if t.remote != "." {
                    status.remote_url =
                        cfg.get("remote", &t.remote, "url").unwrap_or_default().to_string();
                }
                if t.tip == status.commit {
                    // Tips equal ⇒ ahead=behind=0 without any object walk;
                    // diverged tips take the counts from porcelain.
                    ab_native = true;
                }
            }
            // No upstream, or its ref is gone: gitstatusd reports 0/0.
            None => ab_native = true,
        }
        if let Some(p) = push_target_of(&cfg, &repo.common_dir, &status.branch) {
            status.push_remote_name = p.remote;
            status.push_remote_url = p.url;
            if p.tip != status.commit {
                if let Some((ahead, behind)) = rev_list_counts(&repo.common_dir, &status.commit, &p.refname) {
                    status.push_ahead = ahead;
                    status.push_behind = behind;
                }
            }
        }
    } else {
        ab_native = true; // detached HEAD has no upstream
    }

    // Stashes: reflog line count — `git stash list` is exactly this reflog.
    let native_stash = stash_count(&repo.common_dir);
    if let Some(n) = native_stash {
        status.stashes = n;
    }

    // Tag: exact match of refs/tags/* against the HEAD commit
    // (tag_db.cc:119-148 TagForCommit).
    if !status.commit.is_empty() {
        status.tag = tag_for_commit(&repo.common_dir, &status.commit);
    }

    // Index scan: unstaged + conflicted natively.
    let index_size = index_entry_count(&repo.git_dir);
    status.index_size = index_size;
    let native_counts = read_index_counts(&repo, &caps);
    if let Some(ic) = &native_counts {
        status.unstaged = ic.unstaged;
        status.conflicted = ic.conflicted;
        status.skip_worktree = ic.skip_worktree;
        status.assume_unchanged = ic.assume_unchanged;
    }

    // -------- subprocess fields (staged/untracked always; the rest only
    // when the native layer could not produce them — see module doc) --------
    // Asynchronous, exactly as p10k queries gitstatusd: serve the last
    // snapshot immediately and let a refresh land in the background; only
    // the first-ever prompt in a repo blocks, and then only for
    // SUBPROCESS_BUDGET. The native fields above are always fresh; a
    // background refresh can leave staged/untracked one prompt stale, which
    // is the same window p10k lives with (p10k:3799-3812).
    let prev_sub = sub_cache()
        .lock()
        .ok()
        .and_then(|m| {
            m.get(&repo.git_dir)
                .filter(|e| e.mode == untracked_mode)
                .map(|e| e.status.clone())
        });
    let sub = match prev_sub {
        Some(s) => {
            // Have something to render: never block, just kick the refresh.
            refresh_porcelain(&repo, untracked_mode, None);
            Some(s)
        }
        // Nothing cached yet — wait out the budget so a first paint in a
        // fast repo is already complete.
        None => refresh_porcelain(&repo, untracked_mode, Some(SUBPROCESS_BUDGET)),
    };

    let sub = match sub {
        Some(s) => s,
        // First prompt in this repo and `git status` is still running: the
        // subprocess-only fields have no value yet, and a segment claiming
        // "0 staged, 0 untracked" would be a lie. Same as before: no
        // segment this prompt, real numbers on the next one.
        None => return None,
    };

    status.staged = sub.staged;
    status.untracked = sub.untracked;
    status.staged_new = sub.staged_new;
    status.staged_deleted = sub.staged_deleted;
    status.unstaged_deleted = sub.unstaged_deleted;
    if native_counts.is_none() {
        status.unstaged = sub.unstaged;
        status.conflicted = sub.conflicted;
    }
    if !ab_native {
        status.ahead = sub.ahead;
        status.behind = sub.behind;
    }
    if native_stash.is_none() {
        status.stashes = sub.stashes; // --show-stash fallback
    }
    if status.commit.is_empty() {
        status.commit = sub.commit;
    }
    if status.branch.is_empty() {
        status.branch = sub.branch;
    }
    if status.remote_branch.is_empty() && !sub.remote_branch.is_empty() {
        // `# branch.upstream` is `<remote>/<branch>`; strip the remote
        // (remote names cannot contain '/') to the branch-only shape.
        status.remote_branch = match sub.remote_branch.split_once('/') {
            Some((_, b)) => b.to_string(),
            None => sub.remote_branch,
        };
    }

    lim.apply(&mut status, index_size);

    if let Ok(mut map) = cache().lock() {
        // Bound the cache: one entry per repo visited; a long-lived shell
        // hopping across many repos must not grow this without limit.
        if map.len() >= CACHE_CAP && !map.contains_key(&repo.git_dir) {
            evict_oldest(&mut map, |e: &CacheEntry| e.at);
        }
        map.insert(
            repo.git_dir.clone(),
            CacheEntry {
                at: Instant::now(),
                head_mtime,
                index_mtime,
                limits: *limits,
                status: status.clone(),
            },
        );
    }
    Some(status)
}

// ---------------------------------------------------------------------------
// Repo discovery
// ---------------------------------------------------------------------------

struct Repo {
    /// Directory containing HEAD, index, rebase state, ... (per-worktree).
    git_dir: PathBuf,
    /// Directory containing refs/, packed-refs, config, logs/refs/stash
    /// (shared across worktrees).
    common_dir: PathBuf,
    /// Top-level working directory (where `git status` runs).
    work_dir: PathBuf,
}

/// Walk up from `dir` until a `.git` entry is found. A `.git` directory is
/// the gitdir itself; a `.git` file holds `gitdir: <path>` (worktree or
/// submodule checkout). The common dir is the gitdir unless a `commondir`
/// file redirects it (linked worktrees).
fn discover_repo(dir: &Path) -> Option<Repo> {
    let mut cur = if dir.is_absolute() {
        dir.to_path_buf()
    } else {
        std::env::current_dir().ok()?.join(dir)
    };
    loop {
        let dotgit = cur.join(".git");
        if let Ok(meta) = fs::symlink_metadata(&dotgit) {
            let git_dir = if meta.is_dir() {
                dotgit
            } else {
                // `.git` file: `gitdir: /abs/path` or `gitdir: ../rel/path`
                let text = fs::read_to_string(&dotgit).ok()?;
                let target = text.strip_prefix("gitdir:")?.trim();
                let p = Path::new(target);
                if p.is_absolute() {
                    p.to_path_buf()
                } else {
                    cur.join(p)
                }
            };
            let common_dir = match fs::read_to_string(git_dir.join("commondir")) {
                Ok(text) => {
                    let t = text.trim();
                    let p = Path::new(t);
                    if p.is_absolute() {
                        p.to_path_buf()
                    } else {
                        git_dir.join(p)
                    }
                }
                Err(_) => git_dir.clone(),
            };
            return Some(Repo {
                git_dir,
                common_dir,
                work_dir: cur,
            });
        }
        if !cur.pop() {
            return None;
        }
    }
}

fn mtime_of(p: &Path) -> Option<SystemTime> {
    fs::metadata(p).ok().and_then(|m| m.modified().ok())
}

// ---------------------------------------------------------------------------
// HEAD / refs
// ---------------------------------------------------------------------------

/// Fill `branch` and `commit` from HEAD. Symbolic HEAD names the branch and
/// the tip commit resolves through loose refs then packed-refs; detached
/// HEAD is a bare hash with no branch (gitstatusd reports LOCAL_BRANCH=""
/// for detached HEAD; p10k then falls back to the commit, p10k:3775).
fn read_head(repo: &Repo, status: &mut GitStatus) {
    let head = match fs::read_to_string(repo.git_dir.join("HEAD")) {
        Ok(s) => s,
        Err(e) => {
            tracing::warn!("p10k git: unreadable HEAD in {:?}: {e}", repo.git_dir);
            return;
        }
    };
    let head = head.trim();
    if let Some(refname) = head.strip_prefix("ref: ") {
        let refname = refname.trim();
        status.branch = refname
            .strip_prefix("refs/heads/")
            .unwrap_or(refname)
            .to_string();
        if let Some(oid) = resolve_ref(&repo.common_dir, refname) {
            status.commit = oid;
        }
    } else if head.len() >= 40 && head.bytes().all(|b| b.is_ascii_hexdigit()) {
        status.commit = head.to_string(); // detached HEAD
    }
}

/// Resolve a fully-qualified ref to its commit hash: loose ref file first,
/// then a linear scan of packed-refs (`<oid> <refname>` lines; `^<oid>`
/// peel lines and `#` comments skipped).
fn resolve_ref(common_dir: &Path, refname: &str) -> Option<String> {
    if let Ok(s) = fs::read_to_string(common_dir.join(refname)) {
        let s = s.trim();
        if !s.is_empty() {
            return Some(s.to_string());
        }
    }
    let packed = fs::read_to_string(common_dir.join("packed-refs")).ok()?;
    for line in packed.lines() {
        if line.starts_with('#') || line.starts_with('^') {
            continue;
        }
        if let Some((oid, name)) = line.split_once(' ') {
            if name == refname {
                return Some(oid.to_string());
            }
        }
    }
    None
}

// ---------------------------------------------------------------------------
// In-progress action
// ---------------------------------------------------------------------------

/// Port of gitstatus RepoState (gitstatus/src/git.cc:43-110), which maps
/// libgit2 `git_repository_state` to names that "mostly match gitaction in
/// vcs_info" (git.cc:46-47). Detection order and marker files follow libgit2
/// repository.c: rebase-merge (interactive?) > rebase-apply
/// (rebasing/applying?) > MERGE_HEAD > REVERT_HEAD > CHERRY_PICK_HEAD >
/// BISECT_LOG. A rebase/am in flight appends " <next>/<last>" progress
/// (git.cc:96-108).
fn repo_action(git_dir: &Path) -> String {
    let exists = |name: &str| git_dir.join(name).exists();
    let read1 = |name: &str| -> String {
        // git.cc:87-92 ReadFile — first whitespace-delimited token.
        fs::read_to_string(git_dir.join(name))
            .ok()
            .and_then(|s| s.split_whitespace().next().map(str::to_string))
            .unwrap_or_default()
    };

    let state: &str = if exists("rebase-merge") {
        if exists("rebase-merge/interactive") {
            "rebase-i" // git.cc:68 GIT_REPOSITORY_STATE_REBASE_INTERACTIVE
        } else {
            "rebase-m" // git.cc:70 GIT_REPOSITORY_STATE_REBASE_MERGE
        }
    } else if exists("rebase-apply") {
        if exists("rebase-apply/rebasing") {
            "rebase" // git.cc:66 GIT_REPOSITORY_STATE_REBASE
        } else if exists("rebase-apply/applying") {
            "am" // git.cc:72 GIT_REPOSITORY_STATE_APPLY_MAILBOX
        } else {
            "am/rebase" // git.cc:74 GIT_REPOSITORY_STATE_APPLY_MAILBOX_OR_REBASE
        }
    } else if exists("MERGE_HEAD") {
        "merge" // git.cc:54 GIT_REPOSITORY_STATE_MERGE
    } else if exists("REVERT_HEAD") {
        if exists("sequencer/todo") {
            "revert-seq" // git.cc:58 GIT_REPOSITORY_STATE_REVERT_SEQUENCE
        } else {
            "revert" // git.cc:56 GIT_REPOSITORY_STATE_REVERT
        }
    } else if exists("CHERRY_PICK_HEAD") {
        if exists("sequencer/todo") {
            "cherry-seq" // git.cc:62 GIT_REPOSITORY_STATE_CHERRYPICK_SEQUENCE
        } else {
            "cherry" // git.cc:60 GIT_REPOSITORY_STATE_CHERRYPICK
        }
    } else if exists("BISECT_LOG") {
        "bisect" // git.cc:64 GIT_REPOSITORY_STATE_BISECT
    } else {
        "" // git.cc:52 GIT_REPOSITORY_STATE_NONE
    };

    // git.cc:96-102 — rebase-merge carries msgnum/end, rebase-apply next/last.
    let (next, last) = if exists("rebase-merge") {
        (read1("rebase-merge/msgnum"), read1("rebase-merge/end"))
    } else if exists("rebase-apply") {
        (read1("rebase-apply/next"), read1("rebase-apply/last"))
    } else {
        (String::new(), String::new())
    };

    // git.cc:104-107 — append " next/last" only when both are present.
    if !next.is_empty() && !last.is_empty() {
        format!("{state} {next}/{last}")
    } else {
        state.to_string()
    }
}

/// git_refspec_transform: map `refname` through one fetch refspec
/// (`[+]<src>[*]:<dst>[*]`); `None` when its source does not match.
fn refspec_transform(spec: &str, refname: &str) -> Option<String> {
    let spec = spec.strip_prefix('+').unwrap_or(spec);
    let (src, dst) = spec.split_once(':')?;
    match src.split_once('*') {
        Some((pre, post)) => {
            let middle = refname.strip_prefix(pre)?.strip_suffix(post)?;
            let (dst_pre, dst_post) = dst.split_once('*')?;
            Some(format!("{dst_pre}{middle}{dst_post}"))
        }
        None => (src == refname).then(|| dst.to_string()),
    }
}

/// `refname` as the tracking ref of `remote` (the first fetch refspec of
/// the remote that matches it). `None` when the remote is not configured.
fn remote_tracking_ref(cfg: &GitConfig, remote: &str, refname: &str) -> Option<String> {
    if !cfg.has_group("remote", remote) {
        return None;
    }
    cfg.get_all("remote", remote, "fetch")
        .iter()
        .find_map(|spec| refspec_transform(spec, refname))
}

/// The upstream of a branch, as gitstatus git.cc GetRemote resolves it.
struct Tracking {
    /// `origin`, or `.` for a local upstream branch.
    remote: String,
    /// The upstream's short name without the remote (`main`).
    branch: String,
    /// The commit its ref points at.
    tip: String,
}

/// `branch.<name>.remote` + `branch.<name>.merge`, mapped to a tracking ref
/// through the remote's fetch refspecs (`.` keeps the merge ref). `None`
/// unless that ref exists (git.cc:203-204 `git_reference_lookup`).
fn tracking_of(cfg: &GitConfig, common_dir: &Path, branch: &str) -> Option<Tracking> {
    let remote = cfg.get("branch", branch, "remote").filter(|r| !r.is_empty())?;
    let merge = cfg.get("branch", branch, "merge").filter(|m| !m.is_empty())?;
    let refname = if remote == "." {
        merge.to_string()
    } else {
        remote_tracking_ref(cfg, remote, merge)?
    };
    let tip = resolve_ref(common_dir, &refname)?;
    let short = refname
        .strip_prefix("refs/heads/")
        .or_else(|| refname.strip_prefix("refs/remotes/"))
        .unwrap_or(&refname);
    let name = if remote == "." {
        short
    } else {
        short.strip_prefix(remote).and_then(|s| s.strip_prefix('/')).unwrap_or(short)
    };
    Some(Tracking { remote: remote.to_string(), branch: name.to_string(), tip })
}

/// Where a branch is pushed, as git.cc GetPushRemote resolves it.
struct PushTarget {
    remote: String,
    url: String,
    refname: String,
    tip: String,
}

/// `branch.<name>.pushRemote`, else `remote.pushDefault`; the ref is the
/// branch itself mapped through that remote's fetch refspecs. `None` when
/// there is no such remote or its ref does not exist.
fn push_target_of(cfg: &GitConfig, common_dir: &Path, branch: &str) -> Option<PushTarget> {
    let remote = cfg
        .get("branch", branch, "pushremote")
        .or_else(|| cfg.get("remote", "", "pushdefault"))
        .filter(|r| !r.is_empty())?;
    let local = format!("refs/heads/{branch}");
    let refname = if remote == "." {
        local
    } else {
        remote_tracking_ref(cfg, remote, &local)?
    };
    let tip = resolve_ref(common_dir, &refname)?;
    let url = if remote == "." {
        String::new()
    } else {
        cfg.get("remote", remote, "url").unwrap_or_default().to_string()
    };
    Some(PushTarget { remote: remote.to_string(), url, refname, tip })
}

/// `(commits in head not in other, commits in other not in head)` — the
/// two `CountRange` walks of gitstatus (`other..HEAD`, `HEAD..other`).
fn rev_list_counts(common_dir: &Path, head: &str, other: &str) -> Option<(i64, i64)> {
    let out = Command::new("git")
        .arg(format!("--git-dir={}", common_dir.display()))
        .args(["rev-list", "--left-right", "--count"])
        .arg(format!("{head}...{other}"))
        .env("GIT_OPTIONAL_LOCKS", "0")
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()
        .ok()?;
    let text = String::from_utf8_lossy(&out.stdout);
    let mut it = text.split_whitespace().map(|n| n.parse::<i64>());
    match (it.next(), it.next()) {
        (Some(Ok(a)), Some(Ok(b))) => Some((a, b)),
        _ => None,
    }
}

/// Port of gitstatus RepoCaps (index.cc:308-318): repository capabilities
/// that steer the lstat comparison. libgit2 defaults both to true on unix;
/// `git clone`/`git init` write them explicitly.
#[derive(Clone, Copy)]
struct RepoCaps {
    trust_filemode: bool, // core.filemode  (index.cc:309 is_filemode_trustworthy)
    has_symlinks: bool,   // core.symlinks  (index.cc:310 index_supports_symlinks)
    hash_len: usize,      // 20 (sha1) / 32 (extensions.objectformat = sha256)
}

impl RepoCaps {
    fn from_config(cfg: &GitConfig) -> RepoCaps {
        RepoCaps {
            trust_filemode: cfg.get_bool("core", "filemode", true),
            has_symlinks: cfg.get_bool("core", "symlinks", true),
            hash_len: match cfg.get("extensions", "", "objectformat") {
                Some("sha256") => 32,
                _ => 20,
            },
        }
    }
}

// ---------------------------------------------------------------------------
// .git/index (v2/v3/v4) → unstaged + conflicted
// ---------------------------------------------------------------------------

struct IndexCounts {
    unstaged: i64,
    conflicted: i64,
    /// Entries with the skip-worktree / assume-valid ("assume unchanged")
    /// bit set (gitstatus index.cc).
    skip_worktree: i64,
    assume_unchanged: i64,
}

/// The entry count in the `.git/index` header (`VCS_STATUS_INDEX_SIZE`);
/// 0 when there is no readable index.
fn index_entry_count(git_dir: &Path) -> i64 {
    use std::io::Read as _;
    let mut head = [0u8; 12];
    let read = fs::File::open(git_dir.join("index")).and_then(|mut f| f.read_exact(&mut head));
    match read {
        Ok(()) if &head[0..4] == b"DIRC" => i64::from(u32::from_be_bytes([head[8], head[9], head[10], head[11]])),
        _ => 0,
    }
}

fn be32(data: &[u8], pos: usize) -> Option<u32> {
    data.get(pos..pos + 4)
        .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}

fn be16(data: &[u8], pos: usize) -> Option<u16> {
    data.get(pos..pos + 2)
        .map(|b| u16::from_be_bytes([b[0], b[1]]))
}

/// git varint.c decode_varint — "offset encoding": 7 bits per byte, MSB is
/// the continuation bit, and each continuation adds 1 before shifting so
/// that multi-byte encodings have no redundant forms.
fn decode_varint(data: &[u8], pos: &mut usize) -> Option<u64> {
    let mut c = *data.get(*pos)?;
    *pos += 1;
    let mut val = u64::from(c & 0x7f);
    let mut rounds = 0;
    while c & 0x80 != 0 {
        rounds += 1;
        if rounds > 9 {
            return None; // > 63 significant bits ⇒ corrupt
        }
        c = *data.get(*pos)?;
        *pos += 1;
        val = val.checked_add(1)?.checked_shl(7)? | u64::from(c & 0x7f);
    }
    Some(val)
}

/// The per-entry stat fields the modified check needs (gitformat-index.txt
/// entry layout; offsets relative to the entry start):
///   0 ctime-sec  4 ctime-nsec  8 mtime-sec  12 mtime-nsec  16 dev  20 ino
///   24 mode  28 uid  32 gid  36 file-size  (all u32 big-endian, truncated)
///   40 .. 40+H  object id (H = 20 sha1 / 32 sha256)
///   40+H  flags u16be: bit15 assume-valid, bit14 extended (v3+),
///         bits13-12 stage, bits11-0 name length (0xFFF when longer)
///   [+2 extended flags u16be when the extended bit is set (v3+):
///         bit14 skip-worktree, bit13 intent-to-add]
///   then the path: v2/v3 NUL-terminated + NUL padding to a multiple of 8
///   bytes from the entry start (1-8 NULs); v4 prefix-compressed — varint N
///   (bytes to strip from the END of the previous path) + NUL-terminated
///   suffix, no padding.
#[derive(Clone, Copy)]
struct EntryStat {
    mode: u32,
    ino: u32,
    size: u32,
    mt_s: u32,
    mt_ns: u32,
}

const S_IFMT: u32 = 0o170000;
const S_IFREG: u32 = 0o100000;
const S_IFLNK: u32 = 0o120000;
const S_IFDIR: u32 = 0o040000;

/// Port of gitstatus IsModified (index.cc:71-104) — decides whether a
/// stage-0 index entry differs from its worktree file. gitstatus compares
/// exactly ino / stage / fsize / mtime / mode (index.cc:93-99); dev, uid,
/// gid and ctime are NOT compared.
fn is_modified(e: &EntryStat, st: &fs::Metadata, caps: &RepoCaps) -> bool {
    use std::os::unix::fs::MetadataExt;
    // index.cc:71-83 — normalize the worktree mode before comparing.
    let st_mode = st.mode();
    let mode = if st_mode & S_IFMT == S_IFREG {
        if !caps.has_symlinks && e.mode & S_IFMT == S_IFLNK {
            e.mode
        } else if !caps.trust_filemode {
            e.mode
        } else {
            S_IFREG | if st_mode & 0o100 != 0 { 0o755 } else { 0o644 }
        }
    } else {
        st_mode & S_IFMT
    };
    // index.cc:93 — ino: 0 in the index matches anything; else compare the
    // u32-truncated st_ino exactly as C does.
    if e.ino != 0 && e.ino != st.ino() as u32 {
        return true;
    }
    // index.cc:97 — fsize. NOTE racy-git: git smudges racily-clean entries
    // to file_size 0 on index write, forcing a content check; gitstatus (and
    // git) would then hash the file. We instead COUNT the entry as unstaged
    // per the racy-git convention — a just-touched-but-identical file may
    // show unstaged for one prompt until the next `git status`/`git add`
    // rewrites the index. Never wrong about truly-dirty files.
    if u64::from(e.size) != st.size() {
        return true;
    }
    // index.cc:61-69 MTimeEq — seconds must match; nanoseconds match, or the
    // index stores 0 nsec (git built without USE_NSEC — the GITSTATUS_ZERO_NSEC
    // build flag; applied unconditionally here since a 0-nsec index entry vs
    // a real-nsec filesystem is the common macOS/Linux packaged-git case).
    if e.mt_s as i64 != st.mtime() || !(e.mt_ns as i64 == st.mtime_nsec() || e.mt_ns == 0) {
        return true;
    }
    // index.cc:99 — mode.
    if e.mode != mode {
        return true;
    }
    false
}

/// lstat every collected entry and count the modified ones (index.cc:191-199
/// StatFiles + IsModified). One lstat(2) per index entry is latency-bound,
/// not CPU-bound, which is why gitstatusd fans the same scan out over its
/// thread pool (`gitstatusd -t <n>`); measured here at 5,831 entries the
/// serial scan is ~115-133ms and an 8-way scan ~28-49ms.
///
/// The count is order-independent (a plain sum over entries), so splitting
/// the slice changes nothing about the result.
fn count_modified(entries: &[(EntryStat, PathBuf)], caps: &RepoCaps) -> i64 {
    fn scan(chunk: &[(EntryStat, PathBuf)], caps: &RepoCaps) -> i64 {
        chunk
            .iter()
            .filter(|(e, path)| match fs::symlink_metadata(path) {
                // index.cc:195 — ENOENT ⇒ deleted, other errors ⇒ unreadable;
                // both are dirty candidates.
                Err(_) => true,
                Ok(st) => is_modified(e, &st, caps),
            })
            .count() as i64
    }

    let nthreads = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
        .min(MAX_STAT_THREADS);
    if entries.len() < PAR_STAT_MIN || nthreads < 2 {
        return scan(entries, caps);
    }
    let caps = *caps;
    let chunk_len = entries.len().div_ceil(nthreads);
    std::thread::scope(|s| {
        let handles: Vec<_> = entries
            .chunks(chunk_len)
            .map(|c| s.spawn(move || scan(c, &caps)))
            .collect();
        handles.into_iter().map(|h| h.join().unwrap_or(0)).sum()
    })
}

/// Parse `.git/index` and lstat each stage-0 entry: unstaged = entries whose
/// worktree file is missing/unreadable/modified (index.cc:191-199 StatFiles
/// + IsModified), conflicted = distinct paths with stage > 0. Returns None
/// when the native parse cannot proceed (unsupported version, sparse-index
/// tree entries, oversized index, corrupt data) — the caller then takes both
/// counts from the porcelain subprocess. The trailing checksum is NOT
/// verified (read-only prompt path; no SHA-1 impl in-tree — worst case a
/// torn index yields wrong counts for one 2s cache window).
fn read_index_counts(repo: &Repo, caps: &RepoCaps) -> Option<IndexCounts> {
    let data = fs::read(repo.git_dir.join("index")).ok()?;
    // Header (12 bytes): "DIRC", version u32be, entry count u32be; the file
    // ends with a hash-len checksum trailer.
    if data.len() < 12 + caps.hash_len || &data[0..4] != b"DIRC" {
        tracing::debug!(
            "p10k git: index missing/short/bad magic in {:?}",
            repo.git_dir
        );
        return None;
    }
    let version = be32(&data, 4)?;
    if !(2..=4).contains(&version) {
        tracing::debug!("p10k git: unsupported index version {version}");
        return None;
    }
    let nentries = be32(&data, 8)? as usize;
    if nentries > NATIVE_SCAN_MAX {
        tracing::debug!(
            "p10k git: index has {nentries} entries > {NATIVE_SCAN_MAX}, deferring to subprocess"
        );
        return None;
    }

    let mut pos = 12usize;
    let mut prev_path: Vec<u8> = Vec::new(); // v4 prefix compression state
    let mut last_conflict: Vec<u8> = Vec::new();
    let mut unstaged = 0i64;
    let mut conflicted = 0i64;
    let (mut skip_count, mut assume_count) = (0i64, 0i64);
    // Entries whose worktree file must be lstat'ed, collected here and
    // scanned in parallel once the (inherently serial) parse is done.
    let mut to_stat: Vec<(EntryStat, PathBuf)> = Vec::with_capacity(nentries);

    for _ in 0..nentries {
        let start = pos;
        // Fixed stat area (40) + oid + flags.
        if pos + 40 + caps.hash_len + 2 > data.len() {
            return None;
        }
        let e = EntryStat {
            mt_s: be32(&data, pos + 8)?,
            mt_ns: be32(&data, pos + 12)?,
            ino: be32(&data, pos + 20)?,
            mode: be32(&data, pos + 24)?,
            size: be32(&data, pos + 36)?,
        };
        let flags = be16(&data, pos + 40 + caps.hash_len)?;
        pos += 40 + caps.hash_len + 2;

        let assume_valid = flags & 0x8000 != 0;
        let extended = flags & 0x4000 != 0;
        let stage = (flags >> 12) & 0x3;
        let name_len = (flags & 0xFFF) as usize;

        let mut skip_worktree = false;
        let mut intent_to_add = false;
        if extended {
            if version < 3 {
                return None; // extended bit is invalid in v2 ⇒ corrupt
            }
            let ext = be16(&data, pos)?;
            pos += 2;
            skip_worktree = ext & 0x4000 != 0;
            intent_to_add = ext & 0x2000 != 0;
        }

        // Path.
        if version == 4 {
            let strip = decode_varint(&data, &mut pos)? as usize;
            if strip > prev_path.len() {
                return None;
            }
            let keep = prev_path.len() - strip;
            prev_path.truncate(keep);
            let nul = data.get(pos..)?.iter().position(|&b| b == 0)?;
            prev_path.extend_from_slice(&data[pos..pos + nul]);
            pos += nul + 1; // v4: no padding
        } else {
            let actual_len = if name_len < 0xFFF {
                name_len
            } else {
                data.get(pos..)?.iter().position(|&b| b == 0)?
            };
            prev_path.clear();
            prev_path.extend_from_slice(data.get(pos..pos + actual_len)?);
            // v2/v3 entry size: (fixed + namelen + 8) & !7 — NUL padding to a
            // multiple of 8 from the entry start, ≥ 1 NUL (read-cache.c
            // ondisk_ce_size).
            let fixed = pos - start;
            pos = start + ((fixed + actual_len + 8) & !7);
            if pos > data.len() {
                return None;
            }
        }

        // ---- evaluate the entry ----
        if stage != 0 {
            // Unmerged: 2-3 entries per path (stages 1/2/3, adjacent since
            // the index is name-then-stage sorted); count the PATH once,
            // matching one `u` line per path in porcelain v2.
            if prev_path != last_conflict {
                conflicted += 1;
                last_conflict.clear();
                last_conflict.extend_from_slice(&prev_path);
            }
            continue;
        }
        skip_count += i64::from(skip_worktree);
        assume_count += i64::from(assume_valid);
        if skip_worktree || assume_valid {
            // git status ignores skip-worktree entries; assume-valid
            // (`git update-index --assume-unchanged`) means "trust the index"
            // — no stat, matching git.
            continue;
        }
        if intent_to_add {
            // `git add -N`: porcelain v2 reports `1 .A` — an unstaged add.
            unstaged += 1;
            continue;
        }
        if e.mode & S_IFMT == S_IFDIR {
            // Sparse-index tree entry (extensions.sparseIndex): expanding it
            // needs the object store — defer everything to the subprocess.
            tracing::debug!(
                "p10k git: sparse index in {:?}, deferring to subprocess",
                repo.git_dir
            );
            return None;
        }
        // Defer the lstat: gitstatus does the whole worktree scan on a thread
        // pool (index.cc:191-199 StatFiles runs under ParallelForEach), and
        // the parse cannot itself be parallelised because v4 paths are
        // prefix-compressed against the previous entry.
        to_stat.push((e, repo.work_dir.join(OsStr::from_bytes(&prev_path))));
    }
    unstaged += count_modified(&to_stat, caps);
    // Extensions (TREE, REUC, UNTR, ...) follow the entries; none are needed
    // for these two counts, so parsing stops here.

    Some(IndexCounts {
        unstaged,
        conflicted,
        skip_worktree: skip_count,
        assume_unchanged: assume_count,
    })
}

// ---------------------------------------------------------------------------
// Stashes — .git/logs/refs/stash reflog
// ---------------------------------------------------------------------------

/// Stash count = line count of the stash reflog; `git stash list` renders
/// exactly this reflog, one line per stash. The file lives in the COMMON dir
/// (reflogs other than HEAD are shared across worktrees). Absent file = no
/// stashes (git deletes it when the last stash is dropped). None only on a
/// real read error (the caller then falls back to porcelain `# stash`).
fn stash_count(common_dir: &Path) -> Option<i64> {
    match fs::read(common_dir.join("logs/refs/stash")) {
        Ok(bytes) => Some(bytes.iter().filter(|&&b| b == b'\n').count() as i64),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(0),
        Err(e) => {
            tracing::debug!("p10k git: stash reflog unreadable: {e}");
            None
        }
    }
}

// ---------------------------------------------------------------------------
// Tag — port of gitstatus TagDb::TagForCommit (tag_db.cc:119-148)
// ---------------------------------------------------------------------------

/// Fully peeled target (`<oid>^{}`) of each object id. Objects are
/// immutable, so results are memoised for the process; unseen ids are
/// resolved by ONE `git cat-file --batch-check` (the object store needs
/// zlib, which this crate does not link). Ids git cannot resolve map to
/// themselves.
fn peel_objects<'a>(
    common_dir: &Path,
    oids: impl Iterator<Item = &'a str>,
) -> HashMap<String, String> {
    use std::io::Write;
    static MEMO: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
    let memo = MEMO.get_or_init(Default::default);
    let wanted: Vec<&str> = oids.collect();
    let unseen: Vec<&str> = {
        let m = memo.lock().unwrap();
        let mut u: Vec<&str> = wanted.iter().copied().filter(|o| !m.contains_key(*o)).collect();
        u.sort_unstable();
        u.dedup();
        u
    };
    if !unseen.is_empty() {
        let child = Command::new("git")
            .arg(format!("--git-dir={}", common_dir.display()))
            .args(["cat-file", "--batch-check=%(objectname)"])
            .env("GIT_OPTIONAL_LOCKS", "0")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn();
        let mut answers: Vec<String> = Vec::new();
        if let Ok(mut child) = child {
            if let Some(mut stdin) = child.stdin.take() {
                let input: String = unseen.iter().map(|o| format!("{o}^{{}}\n")).collect();
                let _ = stdin.write_all(input.as_bytes());
            }
            if let Ok(out) = child.wait_with_output() {
                answers = String::from_utf8_lossy(&out.stdout)
                    .lines()
                    .map(str::to_string)
                    .collect();
            }
        }
        let mut m = memo.lock().unwrap();
        for (i, oid) in unseen.iter().enumerate() {
            // `<input> missing` lines never equal a 40/64-hex id.
            let peeled = answers
                .get(i)
                .filter(|a| !a.contains(' '))
                .cloned()
                .unwrap_or_else(|| (*oid).to_string());
            m.insert((*oid).to_string(), peeled);
        }
    }
    let m = memo.lock().unwrap();
    wanted
        .iter()
        .filter_map(|o| m.get(*o).map(|p| ((*o).to_string(), p.clone())))
        .collect()
}

/// The tag p10k shows for HEAD: the lexicographically GREATEST tag name whose
/// (peeled) target equals the HEAD commit (tag_db.cc:130 `if (res < tag ...)`
/// and :143 — max over loose and packed matches). "" when no tag points at
/// HEAD. Loose tags shadow same-named packed tags (tag_db.cc:135,143
/// IsLooseTag). Loose ANNOTATED tags (file holds a tag object id) are
/// peeled with [`peel_objects`].
fn tag_for_commit(common_dir: &Path, commit: &str) -> String {
    let mut best = String::new();
    let mut loose_names: Vec<String> = Vec::new();
    let mut loose_candidates: Vec<(String, String)> = Vec::new();

    // Loose tags: flat scan of refs/tags, mirroring tag_db.cc:150-162
    // ReadLooseTags (non-recursive; nested names like refs/tags/foo/bar are
    // missed — gitstatus has the same TODO at tag_db.cc:158).
    if let Ok(rd) = fs::read_dir(common_dir.join("refs/tags")) {
        for entry in rd.flatten() {
            let is_file = entry.file_type().map(|t| t.is_file()).unwrap_or(false);
            if !is_file {
                continue;
            }
            let Some(name) = entry.file_name().to_str().map(str::to_string) else {
                continue;
            };
            if let Ok(oid) = fs::read_to_string(entry.path()) {
                let oid = oid.trim();
                // Lightweight tag: the file IS the commit id.
                if oid == commit {
                    if best < name {
                        best = name.clone();
                    }
                } else if !oid.is_empty() {
                    // Possibly an annotated tag (the file holds the tag
                    // object id): peeled below.
                    loose_candidates.push((name.clone(), oid.to_string()));
                }
            }
            loose_names.push(name);
        }
    }

    // Loose ANNOTATED tags (tag_db.cc:295-330 TagHasTarget peels through
    // libgit2): the tag object's final target, memoised per object id.
    if !loose_candidates.is_empty() {
        let peeled = peel_objects(common_dir, loose_candidates.iter().map(|(_, o)| o.as_str()));
        for (name, oid) in &loose_candidates {
            if peeled.get(oid).is_some_and(|t| t == commit) && best < *name {
                best = name.clone();
            }
        }
    }

    // Packed tags. tag_db.cc:228-231: without a `#` header line the refs
    // cannot be assumed fully-peeled — drop all packed tags. tag_db.cc:236-238:
    // a header missing " fully-peeled"/" sorted" only warns and continues.
    let Ok(packed) = fs::read_to_string(common_dir.join("packed-refs")) else {
        return best;
    };
    if !packed.starts_with('#') {
        tracing::warn!("p10k git: packed-refs doesn't have a header. Won't resolve packed tags.");
        return best;
    }
    if let Some(header) = packed.lines().next() {
        if !header.contains(" fully-peeled") || !header.contains(" sorted") {
            tracing::warn!("p10k git: packed-refs has unexpected header."); // tag_db.cc:237
        }
    }
    let mut lines = packed.lines().peekable();
    while let Some(line) = lines.next() {
        if line.starts_with('#') || line.starts_with('^') {
            continue;
        }
        let Some((oid, refname)) = line.split_once(' ') else {
            continue;
        };
        // A following `^<oid>` line is the peeled target of an annotated tag
        // (tag_db.cc:256-263 replaces the id with the peeled one).
        let effective = match lines.peek() {
            Some(peel) if peel.starts_with('^') => lines
                .next()
                .and_then(|p| p.strip_prefix('^'))
                .unwrap_or(oid),
            _ => oid,
        };
        let Some(name) = refname.strip_prefix("refs/tags/") else {
            continue;
        };
        if effective == commit
            && !loose_names.iter().any(|l| l == name) // loose shadows packed
            && best.as_str() < name
        {
            best = name.to_string();
        }
    }
    best
}

// ---------------------------------------------------------------------------
// Commit message — VCS_STATUS_COMMIT_ENCODING / VCS_STATUS_COMMIT_SUMMARY
// ---------------------------------------------------------------------------

/// `Truncate(msg.summary, opts.max_commit_summary_length)`; gitstatusd's
/// `-z` default.
const MAX_COMMIT_SUMMARY_LEN: usize = 256;

/// libgit2 `git_commit_summary`: the first paragraph of the message with
/// each run of whitespace containing a newline collapsed to one space and
/// trailing whitespace dropped.
fn commit_summary_of(message: &str) -> String {
    let msg = message.trim_start_matches('\n').as_bytes();
    let mut out: Vec<u8> = Vec::new();
    let mut space: Option<usize> = None;
    let mut space_has_newline = false;
    for (i, &c) in msg.iter().enumerate() {
        if c == b'\n' {
            // End of the first paragraph: the message ends, a blank line
            // follows, or the next line holds only whitespace.
            let rest = &msg[i + 1..];
            let next_blank = rest
                .iter()
                .find(|&&b| b == b'\n' || !b.is_ascii_whitespace())
                .is_none_or(|&b| b == b'\n');
            if next_blank {
                break;
            }
        }
        if c.is_ascii_whitespace() {
            if space.is_none() {
                space = Some(i);
                space_has_newline = false;
            }
            space_has_newline |= c == b'\n';
        } else {
            if let Some(start) = space.take() {
                if space_has_newline {
                    out.push(b' ');
                } else {
                    out.extend_from_slice(&msg[start..i]);
                }
            }
            out.push(c);
        }
    }
    out.truncate(MAX_COMMIT_SUMMARY_LEN);
    String::from_utf8_lossy(&out).into_owned()
}

/// `(encoding, summary)` of `commit` in the repository at `workdir`; both
/// empty for an unreadable commit. Memoised per object id (commits are
/// immutable): one `git cat-file commit` the first time a HEAD is seen.
pub fn commit_message(workdir: &Path, commit: &str) -> (String, String) {
    static MEMO: OnceLock<Mutex<HashMap<String, (String, String)>>> = OnceLock::new();
    let memo = MEMO.get_or_init(Default::default);
    if commit.is_empty() {
        return Default::default();
    }
    if let Some(hit) = memo.lock().ok().and_then(|m| m.get(commit).cloned()) {
        return hit;
    }
    let out = Command::new("git")
        .arg("-C")
        .arg(workdir)
        .args(["cat-file", "commit", commit])
        .env("GIT_OPTIONAL_LOCKS", "0")
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output();
    let result = match out {
        Ok(o) if o.status.success() => {
            let raw = String::from_utf8_lossy(&o.stdout).into_owned();
            let (headers, message) = raw.split_once("\n\n").unwrap_or((raw.as_str(), ""));
            let encoding = headers
                .lines()
                .find_map(|l| l.strip_prefix("encoding "))
                .unwrap_or_default()
                .to_string();
            (encoding, commit_summary_of(message))
        }
        _ => Default::default(),
    };
    if let Ok(mut m) = memo.lock() {
        if m.len() > 256 {
            m.clear();
        }
        m.insert(commit.to_string(), result.clone());
    }
    result
}

// ---------------------------------------------------------------------------
// Gated subprocess: `git status --porcelain=v2` for staged / untracked
// (+ ahead-behind on divergence, + everything on native-parse failure)
// ---------------------------------------------------------------------------

/// Run the one subprocess. Output is drained on a helper thread so a huge
/// dirty tree can't deadlock on a full pipe; the caller waits at most
/// SUBPROCESS_BUDGET. Returns None on spawn failure or timeout (child is
/// killed and reaped).
fn run_porcelain(work_dir: &Path, mode: UntrackedMode) -> Option<String> {
    let mut child = match Command::new("git")
        .arg("-C")
        .arg(work_dir)
        .args(["status", "--porcelain=v2", "--branch", "--show-stash"])
        .arg(mode.arg())
        // Match gitstatusd: never take optional locks / touch the index
        // from a prompt-driven read.
        .env("GIT_OPTIONAL_LOCKS", "0")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!("p10k git: failed to spawn git status: {e}");
            return None;
        }
    };

    // Runs to completion on the caller's (always a helper) thread — the
    // prompt-latency budget is applied by `refresh_porcelain`, which decides
    // how long to WAIT for this, never how long to let it run. See that
    // function for why the child is no longer killed on a timeout.
    let mut stdout = child.stdout.take()?;
    let mut out = String::new();
    let read = stdout.read_to_string(&mut out);
    let _ = child.wait();
    match read {
        Ok(_) => Some(out),
        Err(e) => {
            tracing::warn!("p10k git: reading git status output failed: {e}");
            None
        }
    }
}

/// Parse `git status --porcelain=v2 --branch --show-stash` output into the
/// count fields (plus upstream/ahead/behind and commit/branch fallbacks).
///
/// Header lines:
///   `# branch.oid <oid>`            — commit (fallback if HEAD read failed)
///   `# branch.head <name>`          — `(detached)` when detached
///   `# branch.upstream <r>/<b>`     — remote_branch
///   `# branch.ab +A -B`             — ahead/behind
///   `# stash <N>`                   — stash count (--show-stash)
/// Entry lines:
///   `1 XY ...` / `2 XY ...`         — X!='.' staged++, Y!='.' unstaged++
///   `u ...`                         — conflicted++ (unmerged)
///   `? <path>`                      — untracked++
fn parse_porcelain_v2(out: &str, status: &mut GitStatus) {
    for line in out.lines() {
        if let Some(rest) = line.strip_prefix("# ") {
            if let Some(oid) = rest.strip_prefix("branch.oid ") {
                if status.commit.is_empty() && oid != "(initial)" {
                    status.commit = oid.to_string();
                }
            } else if let Some(head) = rest.strip_prefix("branch.head ") {
                if status.branch.is_empty() && head != "(detached)" {
                    status.branch = head.to_string();
                }
            } else if let Some(up) = rest.strip_prefix("branch.upstream ") {
                status.remote_branch = up.to_string();
            } else if let Some(ab) = rest.strip_prefix("branch.ab ") {
                for tok in ab.split_whitespace() {
                    if let Some(a) = tok.strip_prefix('+') {
                        status.ahead = a.parse().unwrap_or(0);
                    } else if let Some(b) = tok.strip_prefix('-') {
                        status.behind = b.parse().unwrap_or(0);
                    }
                }
            } else if let Some(n) = rest.strip_prefix("stash ") {
                status.stashes = n.trim().parse().unwrap_or(0);
            }
        } else if line.starts_with("1 ") || line.starts_with("2 ") {
            // XY at bytes 2..4: X = staged state, Y = worktree state.
            let bytes = line.as_bytes();
            if bytes.len() >= 4 {
                if bytes[2] != b'.' {
                    status.staged += 1;
                }
                if bytes[3] != b'.' {
                    status.unstaged += 1;
                }
                // X = A: staged new file; X = D / Y = D: deleted.
                if bytes[2] == b'A' {
                    status.staged_new += 1;
                }
                if bytes[2] == b'D' {
                    status.staged_deleted += 1;
                }
                if bytes[3] == b'D' {
                    status.unstaged_deleted += 1;
                }
            }
        } else if line.starts_with("u ") {
            status.conflicted += 1;
        } else if line.starts_with("? ") {
            status.untracked += 1;
        }
        // `! <path>` (ignored entries) are not counted — p10k doesn't use them.
    }
}

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

    // ---- porcelain fallback parser (unchanged behavior) ----

    #[test]
    fn porcelain_headers_and_counts() {
        let out = "\
# branch.oid 47a386b42798b5ed5d89bc617920d9152479013e
# branch.head main
# branch.upstream origin/main
# branch.ab +3 -2
# stash 1
1 .M N... 100644 100644 100644 aaaa bbbb src/lib.rs
1 M. N... 100644 100644 100644 aaaa bbbb src/exec.rs
1 MM N... 100644 100644 100644 aaaa bbbb src/hist.rs
2 R. N... 100644 100644 100644 aaaa bbbb R100 new.rs\tnew_old.rs
u UU N... 100644 100644 100644 100644 aaaa bbbb cccc conflict.rs
? untracked_a.rs
? untracked_b.rs
";
        let mut s = GitStatus::default();
        parse_porcelain_v2(out, &mut s);
        assert_eq!(s.commit, "47a386b42798b5ed5d89bc617920d9152479013e");
        assert_eq!(s.branch, "main");
        assert_eq!(s.remote_branch, "origin/main");
        assert_eq!(s.ahead, 3);
        assert_eq!(s.behind, 2);
        assert_eq!(s.stashes, 1);
        // staged: "M." + "MM" + "R." = 3; unstaged: ".M" + "MM" = 2
        assert_eq!(s.staged, 3);
        assert_eq!(s.unstaged, 2);
        assert_eq!(s.conflicted, 1);
        assert_eq!(s.untracked, 2);
    }

    #[test]
    fn porcelain_detached_and_initial() {
        let out = "\
# branch.oid (initial)
# branch.head (detached)
";
        let mut s = GitStatus::default();
        parse_porcelain_v2(out, &mut s);
        assert_eq!(s.commit, "");
        assert_eq!(s.branch, "");
        assert_eq!(s.remote_branch, "");
        assert_eq!(s.ahead, 0);
        assert_eq!(s.behind, 0);
        assert_eq!(s.stashes, 0);
    }

    #[test]
    fn porcelain_does_not_clobber_head_read() {
        // branch/commit already resolved from .git/HEAD win over headers.
        let out = "\
# branch.oid ffffffffffffffffffffffffffffffffffffffff
# branch.head porcelain-branch
";
        let mut s = GitStatus {
            branch: "head-branch".into(),
            commit: "1111111111111111111111111111111111111111".into(),
            ..GitStatus::default()
        };
        parse_porcelain_v2(out, &mut s);
        assert_eq!(s.branch, "head-branch");
        assert_eq!(s.commit, "1111111111111111111111111111111111111111");
    }

    #[test]
    fn porcelain_no_upstream_no_stash_line() {
        let out = "\
# branch.oid aaaa
# branch.head feature/x
1 A. N... 000000 100644 100644 0000 aaaa new_file.rs
";
        let mut s = GitStatus::default();
        parse_porcelain_v2(out, &mut s);
        assert_eq!(s.branch, "feature/x");
        assert_eq!(s.remote_branch, "");
        assert_eq!(s.ahead, 0);
        assert_eq!(s.behind, 0);
        assert_eq!(s.staged, 1);
        assert_eq!(s.unstaged, 0);
    }

    #[test]
    fn porcelain_ignores_ignored_entries_and_short_lines() {
        let out = "! ignored.log\n1\n\n? u.rs\n";
        let mut s = GitStatus::default();
        parse_porcelain_v2(out, &mut s);
        assert_eq!(s.staged, 0);
        assert_eq!(s.unstaged, 0);
        assert_eq!(s.untracked, 1);
    }

    // ---- native index parse ----

    fn caps() -> RepoCaps {
        RepoCaps {
            trust_filemode: true,
            has_symlinks: true,
            hash_len: 20,
        }
    }

    /// Build one v2 on-disk entry: 40-byte stat area + 20-byte oid + flags +
    /// NUL-padded path (entry size = (62 + len + 8) & !7).
    fn v2_entry(
        path: &[u8],
        mode: u32,
        ino: u32,
        size: u32,
        mt_s: u32,
        mt_ns: u32,
        stage: u16,
    ) -> Vec<u8> {
        let mut e = Vec::new();
        for v in [0u32, 0, mt_s, mt_ns, 0, ino, mode, 0, 0, size] {
            e.extend_from_slice(&v.to_be_bytes());
        }
        e.extend_from_slice(&[0u8; 20]); // oid (not read by the parser)
        let flags: u16 = ((stage & 0x3) << 12) | (path.len().min(0xFFF) as u16);
        e.extend_from_slice(&flags.to_be_bytes());
        e.extend_from_slice(path);
        let total = (62 + path.len() + 8) & !7;
        e.resize(total, 0);
        e
    }

    fn v2_index(entries: &[Vec<u8>]) -> Vec<u8> {
        let mut d = b"DIRC".to_vec();
        d.extend_from_slice(&2u32.to_be_bytes());
        d.extend_from_slice(&(entries.len() as u32).to_be_bytes());
        for e in entries {
            d.extend_from_slice(e);
        }
        d.extend_from_slice(&[0u8; 20]); // checksum trailer (not verified)
        d
    }

    fn temp_repo(index: &[u8]) -> (tempfile::TempDir, Repo) {
        let td = tempfile::tempdir().expect("tempdir");
        let git_dir = td.path().join(".git");
        fs::create_dir_all(&git_dir).expect("mkdir .git");
        fs::write(git_dir.join("index"), index).expect("write index");
        let repo = Repo {
            common_dir: git_dir.clone(),
            git_dir,
            work_dir: td.path().to_path_buf(),
        };
        (td, repo)
    }

    #[test]
    fn index_header_rejects_bad_magic_and_version() {
        // Bad magic on a fixture byte literal.
        let mut bad = b"XDIR".to_vec();
        bad.extend_from_slice(&2u32.to_be_bytes());
        bad.extend_from_slice(&0u32.to_be_bytes());
        bad.extend_from_slice(&[0u8; 20]);
        let (_td, repo) = temp_repo(&bad);
        assert!(read_index_counts(&repo, &caps()).is_none());

        // Unsupported version 5.
        let mut v5 = b"DIRC".to_vec();
        v5.extend_from_slice(&5u32.to_be_bytes());
        v5.extend_from_slice(&0u32.to_be_bytes());
        v5.extend_from_slice(&[0u8; 20]);
        let (_td, repo) = temp_repo(&v5);
        assert!(read_index_counts(&repo, &caps()).is_none());
    }

    #[test]
    fn index_v2_empty_and_conflicts() {
        // Header-only v2 index (fixture byte literal): 0 entries, 0 counts.
        let (_td, repo) = temp_repo(&v2_index(&[]));
        let ic = read_index_counts(&repo, &caps()).expect("empty index parses");
        assert_eq!(ic.unstaged, 0);
        assert_eq!(ic.conflicted, 0);

        // Stages 1+2 for one path = ONE conflicted path (matches one `u`
        // porcelain line), no lstat performed for unmerged entries.
        let e1 = v2_entry(b"c.rs", 0o100644, 1, 5, 1, 0, 1);
        let e2 = v2_entry(b"c.rs", 0o100644, 1, 5, 1, 0, 2);
        let (_td, repo) = temp_repo(&v2_index(&[e1, e2]));
        let ic = read_index_counts(&repo, &caps()).expect("parses");
        assert_eq!(ic.conflicted, 1);
        assert_eq!(ic.unstaged, 0);
    }

    #[test]
    fn index_v2_lstat_clean_deleted_modified() {
        use std::os::unix::fs::MetadataExt;
        let td = tempfile::tempdir().expect("tempdir");
        let f = td.path().join("a.rs");
        fs::write(&f, b"x").expect("write file");
        let st = fs::symlink_metadata(&f).expect("stat");
        let mode = S_IFREG | if st.mode() & 0o100 != 0 { 0o755 } else { 0o644 };

        // Entry stat-matching the real file → clean.
        let clean = v2_entry(
            b"a.rs",
            mode,
            st.ino() as u32,
            st.size() as u32,
            st.mtime() as u32,
            st.mtime_nsec() as u32,
            0,
        );
        // Same but wrong size → modified (index.cc:97).
        let dirty = v2_entry(
            b"b.rs",
            mode,
            0,
            st.size() as u32 + 7,
            st.mtime() as u32,
            0,
            0,
        );
        fs::write(td.path().join("b.rs"), b"x").expect("write b");
        // Entry whose worktree file does not exist → deleted (index.cc:195).
        let gone = v2_entry(b"gone.rs", mode, 0, 1, 1, 0, 0);

        let git_dir = td.path().join(".git");
        fs::create_dir_all(&git_dir).expect("mkdir");
        fs::write(git_dir.join("index"), v2_index(&[clean, dirty, gone])).expect("write index");
        let repo = Repo {
            common_dir: git_dir.clone(),
            git_dir,
            work_dir: td.path().to_path_buf(),
        };
        let ic = read_index_counts(&repo, &caps()).expect("parses");
        assert_eq!(ic.unstaged, 2); // dirty + gone; clean not counted
        assert_eq!(ic.conflicted, 0);
    }

    #[test]
    fn varint_offset_encoding() {
        // git varint.c: 0x7f → 127; 0x80 0x01 → ((0+1)<<7)|1 = 129.
        let mut p = 0;
        assert_eq!(decode_varint(&[0x7f], &mut p), Some(127));
        let mut p = 0;
        assert_eq!(decode_varint(&[0x80, 0x01], &mut p), Some(129));
        assert_eq!(p, 2);
        // Truncated continuation → None.
        let mut p = 0;
        assert_eq!(decode_varint(&[0x80], &mut p), None);
    }

    // ---- packed-refs tags + stash log + config ----

    const C: &str = "47a386b42798b5ed5d89bc617920d9152479013e";

    #[test]
    fn packed_refs_tag_peel_and_max_name() {
        let td = tempfile::tempdir().expect("tempdir");
        // Annotated v1.0.0 peels to C; lightweight v0.9.0 points at C
        // directly; v0.5.0 points elsewhere.
        let packed = format!(
            "# pack-refs with: peeled fully-peeled sorted \n\
             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa refs/tags/v0.5.0\n\
             {C} refs/tags/v0.9.0\n\
             bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb refs/tags/v1.0.0\n\
             ^{C}\n"
        );
        fs::write(td.path().join("packed-refs"), packed).expect("write");
        // Lexicographic max of the two matches (tag_db.cc:130,143).
        assert_eq!(tag_for_commit(td.path(), C), "v1.0.0");

        // Loose lightweight tag beats packed by name order and shadows a
        // same-named packed entry.
        let tags = td.path().join("refs/tags");
        fs::create_dir_all(&tags).expect("mkdir");
        fs::write(tags.join("v2.0"), format!("{C}\n")).expect("write");
        assert_eq!(tag_for_commit(td.path(), C), "v2.0");
    }

    #[test]
    fn packed_refs_without_header_drops_packed_tags() {
        // tag_db.cc:228-231 — no `#` header ⇒ packed tags unusable.
        let td = tempfile::tempdir().expect("tempdir");
        fs::write(
            td.path().join("packed-refs"),
            format!("{C} refs/tags/v9.9.9\n"),
        )
        .expect("write");
        assert_eq!(tag_for_commit(td.path(), C), "");
    }

    #[test]
    fn stash_log_count() {
        let td = tempfile::tempdir().expect("tempdir");
        assert_eq!(stash_count(td.path()), Some(0)); // absent = 0, exact
        let logs = td.path().join("logs/refs");
        fs::create_dir_all(&logs).expect("mkdir");
        fs::write(
            logs.join("stash"),
            "0000 1111 user <u@example.com> 1 +0000\tWIP one\n\
             1111 2222 user <u@example.com> 2 +0000\tWIP two\n",
        )
        .expect("write");
        assert_eq!(stash_count(td.path()), Some(2));
    }

    #[test]
    fn config_caps_and_tracking_through_fetch_refspecs() {
        let td = tempfile::tempdir().expect("tempdir");
        let common = td.path();
        let ref_file = |name: &str, oid: &str| {
            let p = common.join(name);
            fs::create_dir_all(p.parent().unwrap()).unwrap();
            fs::write(p, format!("{oid}\n")).unwrap();
        };
        ref_file("refs/remotes/origin/feature/x", &"a".repeat(40));
        ref_file("refs/remotes/mirror/feature/x", &"b".repeat(40));
        ref_file("refs/heads/main", &"c".repeat(40));
        let cfg = GitConfig::parse(
            "[core]\n\
             \tfilemode = false\n\
             \tsymlinks = true\n\
             [extensions]\n\
             \tobjectformat = sha256\n\
             [remote \"origin\"]\n\
             \turl = git@example.com:o.git\n\
             \tfetch = +refs/heads/*:refs/remotes/origin/*\n\
             [remote \"mirror\"]\n\
             \turl = git@example.com:m.git\n\
             \tfetch = +refs/heads/feature/*:refs/remotes/mirror/feature/*\n\
             [remote \"nofetch\"]\n\
             \turl = x\n\
             [remote]\n\
             \tpushDefault = mirror\n\
             [branch \"feature/x\"]\n\
             \tremote = origin\n\
             \tmerge = refs/heads/feature/x\n\
             [branch \"local\"]\n\
             \tremote = .\n\
             \tmerge = refs/heads/main\n\
             [branch \"gone\"]\n\
             \tremote = origin\n\
             \tmerge = refs/heads/gone\n\
             [branch \"nofetch\"]\n\
             \tremote = nofetch\n\
             \tmerge = refs/heads/nofetch\n\
             [branch \"pushed\"]\n\
             \tremote = origin\n\
             \tmerge = refs/heads/pushed\n\
             \tpushRemote = origin\n",
        );
        let t = tracking_of(&cfg, common, "feature/x").expect("tracking");
        assert_eq!((t.remote.as_str(), t.branch.as_str()), ("origin", "feature/x"));
        assert_eq!(t.tip, "a".repeat(40));
        let l = tracking_of(&cfg, common, "local").expect("local upstream");
        assert_eq!((l.remote.as_str(), l.branch.as_str()), (".", "main"));
        // upstream ref missing / remote without a fetch refspec / no config
        assert!(tracking_of(&cfg, common, "gone").is_none());
        assert!(tracking_of(&cfg, common, "nofetch").is_none());
        assert!(tracking_of(&cfg, common, "nope").is_none());

        // remote.pushDefault applies when the branch has no pushRemote, and
        // the branch maps through THAT remote's refspec
        let p = push_target_of(&cfg, common, "feature/x").expect("push target");
        assert_eq!(p.remote, "mirror");
        assert_eq!(p.url, "git@example.com:m.git");
        assert_eq!(p.refname, "refs/remotes/mirror/feature/x");
        assert_eq!(p.tip, "b".repeat(40));
        // the mirror refspec only covers feature/*
        assert!(push_target_of(&cfg, common, "other").is_none());
        // its tracking ref is absent
        assert!(push_target_of(&cfg, common, "pushed").is_none());

        let caps = RepoCaps::from_config(&cfg);
        assert!(!caps.trust_filemode);
        assert!(caps.has_symlinks);
        assert_eq!(caps.hash_len, 32);
    }

    #[test]
    fn refspec_transform_handles_globs_and_exact_names() {
        assert_eq!(
            refspec_transform("+refs/heads/*:refs/remotes/o/*", "refs/heads/a/b").as_deref(),
            Some("refs/remotes/o/a/b")
        );
        assert_eq!(
            refspec_transform("refs/heads/main:refs/remotes/o/trunk", "refs/heads/main").as_deref(),
            Some("refs/remotes/o/trunk")
        );
        assert_eq!(refspec_transform("refs/heads/main:x", "refs/heads/other"), None);
        assert_eq!(refspec_transform("refs/tags/*:refs/tags/*", "refs/heads/a"), None);
    }

    #[test]
    fn limits_zero_oversized_index_and_clamp_counts() {
        let mut s = GitStatus {
            staged: 5,
            unstaged: 4,
            untracked: 9,
            conflicted: 3,
            staged_new: 4,
            staged_deleted: 2,
            unstaged_deleted: 4,
            ..Default::default()
        };
        // the defaults report at most one of each
        GitLimits::default().apply(&mut s, 100);
        assert_eq!((s.staged, s.unstaged, s.untracked, s.conflicted), (1, 1, 1, 1));
        assert_eq!((s.staged_new, s.staged_deleted, s.unstaged_deleted), (1, 1, 1));
        assert!(!s.dirty_unknown);

        let mut s = GitStatus { staged: 5, unstaged: 4, untracked: 9, conflicted: 3, ..Default::default() };
        let lim = GitLimits {
            max_staged: -1,
            max_unstaged: 3,
            max_untracked: -1,
            max_conflicted: 0,
            dirty_max_index_size: 50,
            recurse_untracked_dirs: false,
        };
        lim.apply(&mut s, 49);
        assert_eq!((s.staged, s.unstaged, s.untracked, s.conflicted), (5, 3, 9, 0));
        // over the dirty index size: unstaged and untracked are zeroed, staged stays
        let mut s = GitStatus { staged: 5, unstaged: 4, untracked: 9, conflicted: 0, ..Default::default() };
        lim.apply(&mut s, 51);
        assert_eq!((s.staged, s.unstaged, s.untracked), (5, 0, 0));
        assert!(s.dirty_unknown);
    }

    #[test]
    fn porcelain_classifies_new_and_deleted() {
        let mut s = GitStatus::default();
        parse_porcelain_v2(
            "1 A. N... 000000 100644 100644 a b new.rs\n\
             1 D. N... 100644 000000 000000 a b gone.rs\n\
             1 .D N... 100644 100644 000000 a b removed.rs\n\
             1 MM N... 100644 100644 100644 a b both.rs\n",
            &mut s,
        );
        assert_eq!((s.staged, s.staged_new, s.staged_deleted), (3, 1, 1));
        assert_eq!((s.unstaged, s.unstaged_deleted), (2, 1));
    }
    #[test]
    fn commit_summary_is_the_collapsed_first_paragraph() {
        assert_eq!(commit_summary_of("fix the thing\n\nlong body\n"), "fix the thing");
        assert_eq!(commit_summary_of("\n\nleading blanks\n"), "leading blanks");
        assert_eq!(
            commit_summary_of("wrapped\nsubject  line\nthird\n\nbody"),
            "wrapped subject  line third"
        );
        // a whitespace-only line ends the paragraph; trailing space is dropped
        assert_eq!(commit_summary_of("a b  \n   \nbody"), "a b");
        assert_eq!(commit_summary_of(&"x".repeat(400)).len(), MAX_COMMIT_SUMMARY_LEN);
        assert_eq!(commit_summary_of(""), "");
    }
}