prek 0.3.9

A Git hook manager written in Rust, designed as a drop-in alternative to pre-commit.
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
use std::fmt::Write;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};

use annotate_snippets::{AnnotationKind, Level, Renderer, Snippet, renderer::DecorStyle};
use anyhow::{Context, Result};
use futures::{StreamExt, TryStreamExt};
use itertools::Itertools;
use lazy_regex::regex;
use owo_colors::OwoColorize;
use prek_consts::PRE_COMMIT_HOOKS_YAML;
use prek_consts::env_vars::EnvVars;
use rustc_hash::FxHashMap;
use rustc_hash::FxHashSet;
use semver::Version;
use toml_edit::DocumentMut;
use tracing::{debug, trace, warn};

use crate::cli::ExitStatus;
use crate::cli::reporter::AutoUpdateReporter;
use crate::cli::run::Selectors;
use crate::config::{Repo, looks_like_sha};
use crate::fs::{CWD, Simplified};
use crate::printer::Printer;
use crate::run::CONCURRENCY;
use crate::store::Store;
use crate::workspace::{Project, Workspace};
use crate::yaml::serialize_yaml_scalar;
use crate::{config, git};

/// The `rev` value to write back to config, plus an optional `# frozen:` comment.
#[derive(Default, Clone)]
struct Revision {
    /// The resolved revision string to store in `rev`.
    rev: String,
    /// The tag-like reference to preserve in a `# frozen:` comment.
    frozen: Option<String>,
}

/// One occurrence of a remote repo in a project config file.
struct RepoUsage<'a> {
    /// The project whose config contains this repo entry.
    project: &'a Project,
    /// The number of remote repos in that project config.
    remote_count: usize,
    /// The position of this remote repo among the project's remote repos.
    remote_index: usize,
    /// The 1-based line number of this repo entry's `rev` setting.
    rev_line_number: usize,
    /// The existing `# frozen:` comment for this repo entry, if present.
    current_frozen: Option<String>,
    /// The source location of the existing `# frozen:` comment, if present.
    current_frozen_site: Option<FrozenCommentSite>,
}

/// One distinct `repo + rev + hook set` target that should be evaluated.
struct RepoTarget<'a> {
    /// The remote repository URL.
    repo: &'a str,
    /// The currently configured `rev` for this target.
    current_rev: &'a str,
    /// The sorted hook ids that must still exist after updating this target.
    required_hook_ids: Vec<&'a str>,
    /// Every config usage that shares this exact `repo + rev + hook set`.
    usages: Vec<RepoUsage<'a>>,
}

/// One fetched remote repository URL with all configured revisions that use it.
struct RepoSource<'a> {
    /// The remote repository URL.
    repo: &'a str,
    /// Distinct configured revisions that should be evaluated against this fetched repo.
    targets: Vec<RepoTarget<'a>>,
}

/// The action to take when a `# frozen:` comment no longer matches a SHA `rev`.
enum FrozenMismatchAction {
    /// Rewrite the comment to this replacement tag.
    ReplaceWith(String),
    /// Remove the stale comment because no ref points at the pinned commit.
    Remove,
    /// Warn only because we cannot safely decide a comment-only fix.
    NoReplacement,
}

/// Whether the pinned SHA is available from the refs fetched for `auto-update`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CommitPresence {
    /// The commit is present in the fetched repository view.
    Present,
    /// The commit is not present in the fetched repository view.
    Absent,
    /// The current Git cannot disable lazy fetch, so presence could not be checked safely.
    Unknown,
}

/// Why an existing `# frozen:` comment no longer matches the configured `rev`.
enum FrozenMismatchReason {
    /// The frozen reference resolves successfully, but to a different commit than `rev`.
    ResolvesToDifferentCommit,
    /// The frozen reference could not be resolved at all.
    Unresolvable,
}

/// One stale `# frozen:` comment found for a specific repo entry.
struct FrozenMismatch<'a> {
    /// The project config that contains this stale comment.
    project: &'a Project,
    /// The number of remote repos in that project config.
    remote_size: usize,
    /// The position of this remote repo among the project's remote repos.
    remote_index: usize,
    /// The 1-based line number of the `rev` setting that owns this stale comment.
    rev_line_number: usize,
    /// The current `# frozen:` reference string from config.
    current_frozen: String,
    /// The source location of the current `# frozen:` comment.
    frozen_site: Option<FrozenCommentSite>,
    /// Why the existing frozen reference is stale.
    reason: FrozenMismatchReason,
    /// Whether the pinned SHA is available in the fetched repository view.
    current_rev_presence: CommitPresence,
    /// The action to take for this stale comment.
    action: FrozenMismatchAction,
}

/// The source location of a `# frozen:` comment value within a config line.
#[derive(Clone)]
struct FrozenCommentSite {
    /// The 1-based line number in the config file.
    line_number: usize,
    /// The full source line that contains the `# frozen:` comment.
    source_line: String,
    /// The byte range of the frozen reference value within `source_line`.
    span: Range<usize>,
}

/// Parsed frozen-comment metadata for one `rev` entry in config.
#[derive(Clone)]
struct FrozenRef {
    /// The 1-based line number of the `rev` setting.
    line_number: usize,
    /// The parsed frozen reference value, if the `rev` line has one.
    current_frozen: Option<String>,
    /// The source location of that frozen reference value, if present.
    site: Option<FrozenCommentSite>,
}

/// A tag reference with the metadata needed for cooldown selection and SHA matching.
struct TagTimestamp {
    /// The tag name without the `refs/tags/` prefix.
    tag: String,
    /// The tag timestamp used for cooldown ordering.
    timestamp: u64,
    /// The peeled commit SHA the tag ultimately points at.
    commit: String,
}

/// The successful result of evaluating one configured `repo + rev + hook set` target.
struct ResolvedRepoUpdate<'a> {
    /// The revision data that may be written back to config.
    revision: Revision,
    /// Any stale `# frozen:` comments found for this target's usages.
    frozen_mismatches: Vec<FrozenMismatch<'a>>,
}

/// The final outcome for one configured `repo + rev + hook set` target.
struct RepoUpdate<'a> {
    /// The target that was evaluated.
    target: &'a RepoTarget<'a>,
    /// The computed result for this target.
    result: Result<ResolvedRepoUpdate<'a>>,
}

/// Pending config mutations grouped by project config file.
type ProjectUpdates<'a> = FxHashMap<&'a Project, Vec<Option<Revision>>>;

struct ApplyRepoUpdatesResult {
    failure: bool,
    has_updates: bool,
}

enum DisplayEventKind {
    Update { current: Revision, next: Revision },
    FrozenUpdate { current: String, next: String },
    FrozenRemove { current: String },
    UpToDate,
    Failure { error: String },
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum DisplayStream {
    Stdout,
    Stderr,
}

struct DisplayEvent<'a> {
    stream: DisplayStream,
    project: &'a Project,
    repo: &'a str,
    remote_index: usize,
    line_number: usize,
    kind: DisplayEventKind,
}

struct FrozenWarningEvent<'a> {
    project: &'a Project,
    repo: &'a str,
    current_rev: &'a str,
    remote_index: usize,
    mismatch: &'a FrozenMismatch<'a>,
}

type RepoOccurrences<'a> = FxHashMap<(&'a Path, &'a str), usize>;

/// Updates remote repo revisions and, when possible, keeps existing `# frozen:` comments in sync.
#[expect(clippy::fn_params_excessive_bools)]
pub(crate) async fn auto_update(
    store: &Store,
    config: Option<PathBuf>,
    filter_repos: Vec<String>,
    bleeding_edge: bool,
    freeze: bool,
    jobs: usize,
    dry_run: bool,
    check: bool,
    cooldown_days: u8,
    printer: Printer,
) -> Result<ExitStatus> {
    let workspace_root = Workspace::find_root(config.as_deref(), &CWD)?;
    // TODO: support selectors?
    let selectors = Selectors::default();
    let workspace = Workspace::discover(store, workspace_root, config, Some(&selectors), true)?;

    let repo_sources = collect_repo_sources(&workspace)?;
    let jobs = if jobs == 0 { *CONCURRENCY } else { jobs };
    let jobs = jobs
        .min(if filter_repos.is_empty() {
            repo_sources.len()
        } else {
            filter_repos.len()
        })
        .max(1);

    let reporter = AutoUpdateReporter::new(printer);

    let sources = repo_sources.iter().filter(|repo_source| {
        filter_repos.is_empty() || filter_repos.iter().any(|repo| repo == repo_source.repo)
    });
    let outcomes: Vec<RepoUpdate<'_>> = futures::stream::iter(sources)
        .map(async |repo_source| {
            let progress = reporter.on_update_start(repo_source.repo);
            let result =
                evaluate_repo_source(repo_source, bleeding_edge, freeze, cooldown_days).await;
            reporter.on_update_complete(progress);
            result
        })
        .buffer_unordered(jobs)
        .try_collect::<Vec<_>>()
        .await?
        .into_iter()
        .flatten()
        .collect();

    reporter.on_complete();

    warn_frozen_mismatches(&outcomes, printer)?;

    // Group results by project config file
    #[expect(clippy::mutable_key_type)]
    let mut project_updates: ProjectUpdates<'_> = FxHashMap::default();
    let apply_result = apply_repo_updates(outcomes, dry_run, printer, &mut project_updates)?;

    if !dry_run {
        for (project, revisions) in project_updates {
            if revisions.iter().any(Option::is_some) {
                write_new_config(project.config_file(), &revisions).await?;
            }
        }
    }

    if apply_result.failure || (check && apply_result.has_updates) {
        return Ok(ExitStatus::Failure);
    }
    Ok(ExitStatus::Success)
}

/// Collects the configured remote repos grouped by fetch source, revision, and hook set.
fn collect_repo_sources(workspace: &Workspace) -> Result<Vec<RepoSource<'_>>> {
    let mut repo_sources: FxHashMap<&str, FxHashMap<(&str, Vec<&str>), RepoTarget<'_>>> =
        FxHashMap::default();

    for project in workspace.projects() {
        let remote_count = project
            .config()
            .repos
            .iter()
            .filter(|repo| matches!(repo, Repo::Remote(_)))
            .count();

        let frozen_refs = read_frozen_refs(project.config_file()).with_context(|| {
            format!(
                "Failed to read frozen references from `{}`",
                project.config_file().user_display()
            )
        })?;

        if frozen_refs.len() != remote_count {
            anyhow::bail!(
                "Found {} remote repos in `{}` but {} `rev:` entries while checking frozen refs",
                remote_count,
                project.config_file().user_display(),
                frozen_refs.len()
            );
        }

        let mut remote_index = 0;
        for repo in &project.config().repos {
            let Repo::Remote(remote_repo) = repo else {
                continue;
            };

            let mut required_hook_ids = remote_repo
                .hooks
                .iter()
                .map(|hook| hook.id.as_str())
                .collect::<Vec<_>>();
            required_hook_ids.sort_unstable();
            required_hook_ids.dedup();

            let target = repo_sources
                .entry(remote_repo.repo.as_str())
                .or_default()
                .entry((remote_repo.rev.as_str(), required_hook_ids.clone()))
                .or_insert_with(|| RepoTarget {
                    repo: remote_repo.repo.as_str(),
                    current_rev: remote_repo.rev.as_str(),
                    required_hook_ids,
                    usages: Vec::new(),
                });
            target.usages.push(RepoUsage {
                project,
                remote_count,
                remote_index,
                rev_line_number: frozen_refs[remote_index].line_number,
                current_frozen: frozen_refs[remote_index].current_frozen.clone(),
                current_frozen_site: frozen_refs[remote_index].site.clone(),
            });
            remote_index += 1;
        }
    }

    Ok(repo_sources
        .into_iter()
        .map(|(repo, targets)| {
            let mut targets = targets.into_values().collect::<Vec<_>>();
            targets.sort_by(|a, b| {
                a.current_rev
                    .cmp(b.current_rev)
                    .then_with(|| a.required_hook_ids.cmp(&b.required_hook_ids))
            });
            RepoSource { repo, targets }
        })
        .collect())
}

/// Emits all frozen-comment warnings before the normal update output.
fn warn_frozen_mismatches(updates: &[RepoUpdate<'_>], printer: Printer) -> Result<()> {
    let mut warnings = Vec::new();

    for update in updates {
        let Ok(resolved) = &update.result else {
            continue;
        };

        for mismatch in &resolved.frozen_mismatches {
            warnings.push(FrozenWarningEvent {
                project: mismatch.project,
                repo: update.target.repo,
                current_rev: update.target.current_rev,
                remote_index: mismatch.remote_index,
                mismatch,
            });
        }
    }

    warnings.sort_by(|a, b| {
        a.project
            .idx()
            .cmp(&b.project.idx())
            .then_with(|| a.remote_index.cmp(&b.remote_index))
    });

    for warning in warnings {
        write!(
            printer.stderr(),
            "{}",
            render_frozen_mismatch_warning(warning.repo, warning.current_rev, warning.mismatch)
        )?;
    }

    Ok(())
}

fn update_verb(dry_run: bool) -> &'static str {
    if dry_run { "would update" } else { "updating" }
}

fn remove_verb(dry_run: bool) -> &'static str {
    if dry_run { "would remove" } else { "removing" }
}

fn format_revision(rev: &str, frozen: Option<&str>) -> String {
    match frozen {
        Some(frozen) => format!(
            "`{}` {}",
            rev.cyan(),
            format!("(frozen: {frozen})").dimmed()
        ),
        None => format!("`{}`", rev.cyan()),
    }
}

fn format_display_event(kind: &DisplayEventKind, dry_run: bool) -> String {
    match kind {
        DisplayEventKind::Update { current, next } => format!(
            "{} {} -> {}",
            format!("{} rev", update_verb(dry_run)).green(),
            format_revision(&current.rev, current.frozen.as_deref()),
            format_revision(&next.rev, next.frozen.as_deref())
        ),
        DisplayEventKind::FrozenUpdate { current, next } => format!(
            "{} `{}` -> `{}`",
            format!("{} frozen comment", update_verb(dry_run)).green(),
            current.cyan(),
            next.cyan()
        ),
        DisplayEventKind::FrozenRemove { current } => format!(
            "{} `{}`",
            format!("{} frozen comment", remove_verb(dry_run)).yellow(),
            current.cyan()
        ),
        DisplayEventKind::UpToDate => "already up to date".dimmed().to_string(),
        DisplayEventKind::Failure { error } => {
            format!("{} {error}", "update failed:".red())
        }
    }
}

fn write_display_events(
    events: &mut [DisplayEvent<'_>],
    repo_occurrences: &RepoOccurrences<'_>,
    dry_run: bool,
    printer: Printer,
) -> Result<()> {
    if events.is_empty() {
        return Ok(());
    }

    events.sort_by(|a, b| {
        a.project
            .idx()
            .cmp(&b.project.idx())
            .then_with(|| a.remote_index.cmp(&b.remote_index))
    });

    for stream in [DisplayStream::Stdout, DisplayStream::Stderr] {
        let stream_events = events
            .iter()
            .filter(|event| event.stream == stream)
            .collect::<Vec<_>>();
        if stream_events.is_empty() {
            continue;
        }

        let show_project_headers = stream_events
            .iter()
            .map(|event| event.project.config_file())
            .unique()
            .count()
            > 1;

        let mut current_project: Option<&Path> = None;
        let mut current_repo: Option<(&Path, &str)> = None;
        let mut output = String::new();

        for event in stream_events {
            let project = event.project.config_file();
            if show_project_headers && current_project != Some(project) {
                if current_project.is_some() {
                    writeln!(output)?;
                }
                writeln!(
                    output,
                    "{}",
                    format!("{}", project.user_display()).yellow().bold()
                )?;
                current_project = Some(project);
                current_repo = None;
            }

            let repo_key = (project, event.repo);
            if current_repo != Some(repo_key) {
                if current_repo.is_some() {
                    writeln!(output)?;
                }
                let indent = if show_project_headers { "  " } else { "" };
                writeln!(output, "{}{}", indent, event.repo.cyan().bold())?;
                current_repo = Some(repo_key);
            }

            let indent = if show_project_headers { "    " } else { "  " };
            let line_prefix = if repo_occurrences[&repo_key] > 1 {
                format!("{} ", format!("line {}:", event.line_number).dimmed())
            } else {
                String::new()
            };
            writeln!(
                output,
                "{}{}{}",
                indent,
                line_prefix,
                format_display_event(&event.kind, dry_run)
            )?;
        }

        match stream {
            DisplayStream::Stdout => write!(printer.stdout(), "{output}")?,
            DisplayStream::Stderr => write!(printer.stderr(), "{output}")?,
        }
    }

    Ok(())
}

/// Applies evaluated repo outcomes, recording config changes and printing stdout/stderr output.
#[expect(clippy::mutable_key_type)]
fn apply_repo_updates<'a>(
    updates: Vec<RepoUpdate<'a>>,
    dry_run: bool,
    printer: Printer,
    project_updates: &mut ProjectUpdates<'a>,
) -> Result<ApplyRepoUpdatesResult> {
    let mut failure = false;
    let mut has_updates = false;
    let mut display_events = Vec::new();

    for update in updates {
        match update.result {
            Ok(resolved) => {
                let is_changed = update.target.current_rev != resolved.revision.rev;
                let has_frozen_updates = resolved.frozen_mismatches.iter().any(|mismatch| {
                    !matches!(mismatch.action, FrozenMismatchAction::NoReplacement)
                });
                let has_frozen_notice = !resolved.frozen_mismatches.is_empty();

                has_updates |= is_changed || has_frozen_updates;

                if is_changed {
                    for usage in &update.target.usages {
                        display_events.push(DisplayEvent {
                            stream: DisplayStream::Stdout,
                            project: usage.project,
                            repo: update.target.repo,
                            remote_index: usage.remote_index,
                            line_number: usage.rev_line_number,
                            kind: DisplayEventKind::Update {
                                current: Revision {
                                    rev: update.target.current_rev.to_string(),
                                    frozen: usage.current_frozen.clone(),
                                },
                                next: resolved.revision.clone(),
                            },
                        });
                        record_project_revision(
                            project_updates,
                            usage.project,
                            usage.remote_count,
                            usage.remote_index,
                            resolved.revision.clone(),
                        );
                    }
                } else {
                    // If `rev` itself is unchanged, the normal update path above will not rewrite this
                    // repo entry. Still fix stale `# frozen:` comments in update mode so the comment
                    // continues to point at the configured commit SHA.
                    for mismatch in &resolved.frozen_mismatches {
                        match &mismatch.action {
                            FrozenMismatchAction::ReplaceWith(replacement) => {
                                display_events.push(DisplayEvent {
                                    stream: DisplayStream::Stdout,
                                    project: mismatch.project,
                                    repo: update.target.repo,
                                    remote_index: mismatch.remote_index,
                                    line_number: mismatch.rev_line_number,
                                    kind: DisplayEventKind::FrozenUpdate {
                                        current: mismatch.current_frozen.clone(),
                                        next: replacement.clone(),
                                    },
                                });
                                record_project_revision(
                                    project_updates,
                                    mismatch.project,
                                    mismatch.remote_size,
                                    mismatch.remote_index,
                                    Revision {
                                        rev: update.target.current_rev.to_string(),
                                        frozen: Some(replacement.clone()),
                                    },
                                );
                            }
                            FrozenMismatchAction::Remove => {
                                display_events.push(DisplayEvent {
                                    stream: DisplayStream::Stdout,
                                    project: mismatch.project,
                                    repo: update.target.repo,
                                    remote_index: mismatch.remote_index,
                                    line_number: mismatch.rev_line_number,
                                    kind: DisplayEventKind::FrozenRemove {
                                        current: mismatch.current_frozen.clone(),
                                    },
                                });
                                record_project_revision(
                                    project_updates,
                                    mismatch.project,
                                    mismatch.remote_size,
                                    mismatch.remote_index,
                                    Revision {
                                        rev: update.target.current_rev.to_string(),
                                        frozen: None,
                                    },
                                );
                            }
                            FrozenMismatchAction::NoReplacement => {}
                        }
                    }
                }

                if !is_changed && !has_frozen_notice {
                    for usage in &update.target.usages {
                        display_events.push(DisplayEvent {
                            stream: DisplayStream::Stdout,
                            project: usage.project,
                            repo: update.target.repo,
                            remote_index: usage.remote_index,
                            line_number: usage.rev_line_number,
                            kind: DisplayEventKind::UpToDate,
                        });
                    }
                }
            }
            Err(e) => {
                failure = true;
                let error = e.to_string();
                for usage in &update.target.usages {
                    display_events.push(DisplayEvent {
                        stream: DisplayStream::Stderr,
                        project: usage.project,
                        repo: update.target.repo,
                        remote_index: usage.remote_index,
                        line_number: usage.rev_line_number,
                        kind: DisplayEventKind::Failure {
                            error: error.clone(),
                        },
                    });
                }
            }
        }
    }

    let repo_occurrences =
        display_events
            .iter()
            .fold(RepoOccurrences::default(), |mut counts, event| {
                *counts
                    .entry((event.project.config_file(), event.repo))
                    .or_default() += 1;
                counts
            });

    write_display_events(&mut display_events, &repo_occurrences, dry_run, printer)?;

    Ok(ApplyRepoUpdatesResult {
        failure,
        has_updates,
    })
}

#[expect(clippy::mutable_key_type)]
fn record_project_revision<'a>(
    project_updates: &mut ProjectUpdates<'a>,
    project: &'a Project,
    remote_size: usize,
    remote_index: usize,
    revision: Revision,
) {
    let revisions = project_updates
        .entry(project)
        .or_insert_with(|| vec![None; remote_size]);
    revisions[remote_index] = Some(revision);
}

/// Collects stale `# frozen:` comments for one configured `repo + rev + hook set` target.
async fn collect_frozen_mismatches<'a>(
    repo_path: &Path,
    target: &'a RepoTarget<'a>,
    tag_timestamps: &[TagTimestamp],
) -> Result<Vec<FrozenMismatch<'a>>> {
    if !(target.current_rev.len() == 40 && looks_like_sha(target.current_rev)) {
        return Ok(Vec::new());
    }

    let frozen_refs_to_check = target
        .usages
        .iter()
        .filter_map(|usage| usage.current_frozen.as_deref())
        .collect::<FxHashSet<_>>();
    if frozen_refs_to_check.is_empty() {
        return Ok(Vec::new());
    }

    let current_rev_presence = is_commit_present(repo_path, target.current_rev).await?;
    let rev_tags = get_tags_pointing_at_revision(tag_timestamps, target.current_rev);
    let mut resolved_frozen_refs = FxHashMap::default();
    for frozen_ref in frozen_refs_to_check {
        let resolved = resolve_revision_to_commit(repo_path, frozen_ref).await.ok();
        resolved_frozen_refs.insert(frozen_ref, resolved);
    }

    Ok(target
        .usages
        .iter()
        .filter_map(|usage| {
            let current_frozen = usage.current_frozen.as_deref()?;
            let frozen_commit = resolved_frozen_refs.get(current_frozen).cloned().flatten();

            let reason = match frozen_commit.as_deref() {
                Some(frozen_commit) if frozen_commit.eq_ignore_ascii_case(target.current_rev) => {
                    return None;
                }
                Some(_) => FrozenMismatchReason::ResolvesToDifferentCommit,
                None => FrozenMismatchReason::Unresolvable,
            };
            let action = match select_best_tag(&rev_tags, current_frozen, true) {
                Some(replacement) => FrozenMismatchAction::ReplaceWith(replacement.to_string()),
                None => match current_rev_presence {
                    CommitPresence::Present => FrozenMismatchAction::Remove,
                    CommitPresence::Absent | CommitPresence::Unknown => {
                        // The pinned SHA is not present in this repo view, so we cannot prove
                        // that the stale frozen ref should be replaced or removed.
                        FrozenMismatchAction::NoReplacement
                    }
                },
            };
            Some(FrozenMismatch {
                project: usage.project,
                remote_size: usage.remote_count,
                remote_index: usage.remote_index,
                rev_line_number: usage.rev_line_number,
                current_frozen: current_frozen.to_string(),
                frozen_site: usage.current_frozen_site.clone(),
                reason,
                current_rev_presence,
                action,
            })
        })
        .collect())
}

/// Fetches a remote repository once, then evaluates all configured revisions that use it.
async fn evaluate_repo_source<'a>(
    repo_source: &'a RepoSource<'a>,
    bleeding_edge: bool,
    freeze: bool,
    cooldown_days: u8,
) -> Result<Vec<RepoUpdate<'a>>> {
    let tmp_dir = tempfile::tempdir()?;
    let repo_path = tmp_dir.path();

    let result = async {
        trace!(
            "Cloning repository `{}` to `{}`",
            repo_source.repo,
            repo_path.display()
        );
        setup_and_fetch_repo(repo_source.repo, repo_path).await?;
        let metadata = list_tag_metadata(repo_path).await?;

        anyhow::Ok(metadata)
    }
    .await;

    let tag_timestamps = match result {
        Ok(metadata) => metadata,
        Err(e) => {
            let error = format!("{e:#}");
            return Ok(repo_source
                .targets
                .iter()
                .map(|target| RepoUpdate {
                    target,
                    result: Err(anyhow::anyhow!(error.clone())),
                })
                .collect());
        }
    };

    let mut updates = Vec::with_capacity(repo_source.targets.len());
    for target in &repo_source.targets {
        let result = evaluate_repo_target(
            repo_path,
            target,
            bleeding_edge,
            freeze,
            cooldown_days,
            &tag_timestamps,
        )
        .await;

        updates.push(RepoUpdate { target, result });
    }

    Ok(updates)
}

/// Resolves one configured `repo + rev + hook set` entry within an already-fetched remote repository.
async fn evaluate_repo_target<'a>(
    repo_path: &Path,
    target: &'a RepoTarget<'a>,
    bleeding_edge: bool,
    freeze: bool,
    cooldown_days: u8,
    tag_timestamps: &[TagTimestamp],
) -> Result<ResolvedRepoUpdate<'a>> {
    let frozen_mismatches = match collect_frozen_mismatches(repo_path, target, tag_timestamps).await
    {
        Ok(mismatches) => mismatches,
        Err(e) => {
            warn!(
                "Failed to collect frozen comment context for repo `{}`: {e}",
                target.repo
            );
            Vec::new()
        }
    };

    let rev = select_update_revision(
        repo_path,
        target.current_rev,
        bleeding_edge,
        cooldown_days,
        tag_timestamps,
    )
    .await?;

    let Some(rev) = rev else {
        debug!("No suitable revision found for repo `{}`", target.repo);
        return Ok(ResolvedRepoUpdate {
            revision: Revision {
                rev: target.current_rev.to_string(),
                frozen: None,
            },
            frozen_mismatches,
        });
    };

    let (rev, frozen) = if freeze {
        let exact = resolve_revision_to_commit(repo_path, &rev).await?;
        if rev.eq_ignore_ascii_case(&exact) {
            (rev, None)
        } else {
            debug!("Freezing revision `{rev}` to `{exact}`");
            (exact, Some(rev))
        }
    } else {
        (rev, None)
    };

    checkout_and_validate_manifest(repo_path, &rev, &target.required_hook_ids).await?;

    Ok(ResolvedRepoUpdate {
        revision: Revision { rev, frozen },
        frozen_mismatches,
    })
}

/// Initializes a temporary git repo and fetches the remote HEAD plus tags.
async fn setup_and_fetch_repo(repo_url: &str, repo_path: &Path) -> Result<()> {
    git::init_repo(repo_url, repo_path).await?;
    git::git_cmd("git fetch")?
        .arg("fetch")
        .arg("origin")
        .arg("HEAD")
        .arg("--quiet")
        .arg("--filter=blob:none")
        .arg("--tags")
        .current_dir(repo_path)
        .remove_git_envs()
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .await?;

    Ok(())
}

/// Resolves any revision-like string to the underlying commit SHA.
async fn resolve_revision_to_commit(repo_path: &Path, rev: &str) -> Result<String> {
    let output = git::git_cmd("git rev-parse")?
        .arg("rev-parse")
        .arg(format!("{rev}^{{}}"))
        .check(true)
        .current_dir(repo_path)
        .remove_git_envs()
        .output()
        .await?;

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Returns whether a pinned commit SHA is already present in the refs fetched for `auto-update`.
///
/// `auto-update` fetches only `origin/HEAD` and tags, using `--filter=blob:none`. That filter
/// still downloads commits and trees reachable from those refs, but omits blobs. We intentionally
/// use `git --no-lazy-fetch cat-file -e` here instead of `rev-parse`: in a partial clone,
/// `rev-parse` may lazily fetch a missing commit from the promisor remote on demand. On GitHub,
/// that can make a fork-only "impostor commit" appear to belong to the parent repository.
///
/// `auto-update` only selects updates from tags, or from `HEAD` in `--bleeding-edge` mode. It
/// does not normally update to arbitrary branches, so we currently fetch only those refs here.
///
/// So this helper answers a narrower question than "is this SHA valid anywhere on the remote?".
/// It only checks whether the commit is already available from the refs we fetched for update
/// selection. That means branch-only commits outside `HEAD` and tags are treated as absent for
/// now. If that leads to false positives in practice, we can revisit this and fetch branches too.
///
/// On older Git versions that do not support `--no-lazy-fetch`, we skip this check entirely and
/// return `CommitPresence::Unknown` so the caller can avoid presenting inaccurate presence details.
async fn is_commit_present(repo_path: &Path, commit: &str) -> Result<CommitPresence> {
    static GIT_SUPPORTS_NO_LAZY_FETCH: OnceLock<bool> = OnceLock::new();

    if matches!(GIT_SUPPORTS_NO_LAZY_FETCH.get(), Some(false)) {
        return Ok(CommitPresence::Unknown);
    }

    let output = git::git_cmd("git cat-file")?
        .arg("--no-lazy-fetch")
        .arg("cat-file")
        .arg("-e")
        .arg(format!("{commit}^{{commit}}"))
        .env(EnvVars::LC_ALL, "C")
        .check(false)
        .current_dir(repo_path)
        .remove_git_envs()
        .stdout(Stdio::null())
        .output()
        .await?;

    if output.status.success() {
        let _ = GIT_SUPPORTS_NO_LAZY_FETCH.set(true);
        return Ok(CommitPresence::Present);
    }

    if no_lazy_fetch_unsupported(&output.stderr) {
        let _ = GIT_SUPPORTS_NO_LAZY_FETCH.set(false);
        return Ok(CommitPresence::Unknown);
    }

    let _ = GIT_SUPPORTS_NO_LAZY_FETCH.set(true);
    Ok(CommitPresence::Absent)
}

fn no_lazy_fetch_unsupported(stderr: &[u8]) -> bool {
    let stderr = String::from_utf8_lossy(stderr);
    stderr.contains("--no-lazy-fetch") && stderr.contains("unknown option")
}

fn get_tags_pointing_at_revision<'a>(
    tag_timestamps: &'a [TagTimestamp],
    rev: &str,
) -> Vec<&'a str> {
    tag_timestamps
        .iter()
        .filter(|tag_timestamp| tag_timestamp.commit.eq_ignore_ascii_case(rev))
        .map(|tag_timestamp| tag_timestamp.tag.as_str())
        .collect()
}

/// Formats one stale `# frozen:` warning as an annotated source snippet.
fn render_frozen_mismatch_warning(
    repo: &str,
    current_rev: &str,
    mismatch: &FrozenMismatch<'_>,
) -> String {
    let label = match mismatch.reason {
        FrozenMismatchReason::ResolvesToDifferentCommit => {
            format!(
                "`{}` resolves to a different commit",
                mismatch.current_frozen
            )
        }
        FrozenMismatchReason::Unresolvable => {
            format!("`{}` could not be resolved", mismatch.current_frozen)
        }
    };
    let details = match &mismatch.action {
        FrozenMismatchAction::ReplaceWith(replacement) => Some(format!(
            "pinned commit `{current_rev}` is referenced by `{replacement}`"
        )),
        FrozenMismatchAction::Remove => Some(format!(
            "no tag points at the pinned commit `{current_rev}`"
        )),
        FrozenMismatchAction::NoReplacement
            if matches!(mismatch.current_rev_presence, CommitPresence::Absent) =>
        {
            Some(format!(
                "pinned commit `{current_rev}` is not present in the repo"
            ))
        }
        FrozenMismatchAction::NoReplacement => None,
    };
    let title = format!(
        "[{repo}] frozen ref `{}` does not match `{current_rev}`",
        mismatch.current_frozen
    );

    let site = mismatch
        .frozen_site
        .as_ref()
        .expect("frozen comment site must exist when rendering a frozen mismatch warning");
    let mut report = Level::WARNING.primary_title(title).element(
        Snippet::source(&site.source_line)
            .line_start(site.line_number)
            .path(mismatch.project.config_file().user_display().to_string())
            .annotation(AnnotationKind::Primary.span(site.span.clone()).label(label)),
    );
    if let Some(details) = details {
        report = report.element(Level::NOTE.message(details));
    }

    let renderer = Renderer::styled().decor_style(DecorStyle::Ascii);
    format!("{}\n", renderer.render(&[report]))
}

fn parse_frozen_ref(line: &str, line_number: usize) -> FrozenRef {
    let Some(captures) = regex!(r#"#\s*frozen:\s*([^\s#]+)"#).captures(line) else {
        return FrozenRef {
            line_number,
            current_frozen: None,
            site: None,
        };
    };
    let frozen_match = captures.get(1).expect("capture group 1 must exist");
    FrozenRef {
        line_number,
        current_frozen: Some(frozen_match.as_str().to_string()),
        site: Some(FrozenCommentSite {
            line_number,
            source_line: line.to_string(),
            span: frozen_match.start()..frozen_match.end(),
        }),
    }
}

fn read_frozen_refs(path: &Path) -> Result<Vec<FrozenRef>> {
    let content = fs_err::read_to_string(path)?;

    match path.extension() {
        Some(ext) if ext.eq_ignore_ascii_case("toml") => Ok(content
            .lines()
            .enumerate()
            .filter(|(_, line)| regex!(r#"^\s*rev\s*="#).is_match(line))
            .map(|(index, line)| parse_frozen_ref(line, index + 1))
            .collect()),
        _ => {
            let rev_regex = regex!(r#"^\s+rev:\s*['"]?[^\s#]+(?P<comment>.*)$"#);
            Ok(content
                .lines()
                .enumerate()
                .filter_map(|(index, line)| {
                    rev_regex
                        .captures(line)
                        .map(|_| parse_frozen_ref(line, index + 1))
                })
                .collect())
        }
    }
}

/// Resolves the default branch tip to an exact tag when possible, otherwise to a commit SHA.
async fn resolve_bleeding_edge(repo_path: &Path) -> Result<Option<String>> {
    let output = git::git_cmd("git describe")?
        .arg("describe")
        .arg("FETCH_HEAD")
        // Instead of using only the annotated tags, use any tag found in refs/tags namespace.
        // This option enables matching a lightweight (non-annotated) tag.
        .arg("--tags")
        // Only output exact matches (a tag directly references the supplied commit).
        // This is a synonym for --candidates=0.
        .arg("--exact-match")
        .check(false)
        .current_dir(repo_path)
        .remove_git_envs()
        .output()
        .await?;
    let rev = if output.status.success() {
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    } else {
        debug!("No matching tag for `FETCH_HEAD`, using rev-parse instead");
        // "fatal: no tag exactly matches xxx"
        let output = git::git_cmd("git rev-parse")?
            .arg("rev-parse")
            .arg("FETCH_HEAD")
            .check(true)
            .current_dir(repo_path)
            .remove_git_envs()
            .output()
            .await?;
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    };

    debug!("Resolved `FETCH_HEAD` to `{rev}`");
    Ok(Some(rev))
}

/// Lists fetched tag metadata sorted from newest to oldest timestamp.
///
/// Within groups of tags sharing the same timestamp, semver-parseable tags
/// are sorted highest version first; non-semver tags sort after them.
async fn list_tag_metadata(repo: &Path) -> Result<Vec<TagTimestamp>> {
    let output = git::git_cmd("git for-each-ref")?
        .arg("for-each-ref")
        .arg("--sort=-creatordate")
        // `creatordate` is the date the tag was created (annotated tags) or the commit date (lightweight tags)
        // `lstrip=2` removes the "refs/tags/" prefix
        // `objectname` is the tag object SHA for annotated tags, while `*objectname`
        // peels annotated tags to their target object. For lightweight tags the peeled
        // value is empty, so we fall back to `objectname`.
        .arg("--format=%(refname:lstrip=2)\t%(creatordate:unix)\t%(objectname)\t%(*objectname)")
        .arg("refs/tags")
        .check(true)
        .current_dir(repo)
        .remove_git_envs()
        .output()
        .await?;

    let mut tags: Vec<TagTimestamp> = String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| {
            let mut parts = line.split('\t');
            let tag = parts.next()?.trim_ascii();
            let ts_str = parts.next()?.trim_ascii();
            let object = parts.next()?.trim_ascii();
            let peeled = parts.next().unwrap_or_default().trim_ascii();
            let ts: u64 = ts_str.parse().ok()?;
            let commit = if peeled.is_empty() { object } else { peeled };
            Some(TagTimestamp {
                tag: tag.to_string(),
                timestamp: ts,
                commit: commit.to_string(),
            })
        })
        .collect();

    // Deterministic sort: primary key is timestamp (newest first).
    // Within equal timestamps, prefer higher semver versions; non-semver tags
    // sort after semver ones. As a final tie-breaker, compare the tag refname
    // so ordering is stable across platforms/filesystems.
    tags.sort_by(|tag_a, tag_b| {
        tag_b.timestamp.cmp(&tag_a.timestamp).then_with(|| {
            let ver_a = Version::parse(tag_a.tag.strip_prefix('v').unwrap_or(&tag_a.tag));
            let ver_b = Version::parse(tag_b.tag.strip_prefix('v').unwrap_or(&tag_b.tag));
            match (ver_a, ver_b) {
                (Ok(a), Ok(b)) => b.cmp(&a).then_with(|| tag_a.tag.cmp(&tag_b.tag)),
                (Ok(_), Err(_)) => std::cmp::Ordering::Less,
                (Err(_), Ok(_)) => std::cmp::Ordering::Greater,
                (Err(_), Err(_)) => tag_a.tag.cmp(&tag_b.tag),
            }
        })
    });

    Ok(tags)
}

/// Selects the revision string that `auto-update` should write for one fetched repo target.
///
/// In normal mode this chooses the newest tag that satisfies the cooldown window.
/// In bleeding-edge mode it resolves `FETCH_HEAD` instead.
async fn select_update_revision(
    repo_path: &Path,
    current_rev: &str,
    bleeding_edge: bool,
    cooldown_days: u8,
    tag_timestamps: &[TagTimestamp],
) -> Result<Option<String>> {
    if bleeding_edge {
        return resolve_bleeding_edge(repo_path).await;
    }

    let cutoff_secs = u64::from(cooldown_days) * 86400;
    let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
    let cutoff = now.saturating_sub(cutoff_secs);

    // `tag_timestamps` is sorted newest -> oldest; find the first bucket where ts <= cutoff.
    let left = match tag_timestamps.binary_search_by(|tag| tag.timestamp.cmp(&cutoff).reverse()) {
        Ok(i) | Err(i) => i,
    };

    let Some(target_tag) = tag_timestamps.get(left) else {
        trace!("No tags meet cooldown cutoff {cutoff_secs}s");
        return Ok(None);
    };

    debug!(
        "Using tag `{}` cutoff timestamp {}",
        target_tag.tag, target_tag.timestamp
    );

    let tags = get_tags_pointing_at_revision(tag_timestamps, &target_tag.commit);
    let best = select_best_tag(&tags, current_rev, false)
        .unwrap_or(target_tag.tag.as_str())
        .to_string();
    debug!(
        "Using best candidate tag `{best}` for revision `{}`",
        target_tag.tag
    );

    Ok(Some(best))
}

/// Orders version-like tags from newest to oldest semantic version.
fn compare_tag_versions_desc(tag_a: &str, tag_b: &str) -> std::cmp::Ordering {
    let version_a = Version::parse(tag_a.strip_prefix('v').unwrap_or(tag_a));
    let version_b = Version::parse(tag_b.strip_prefix('v').unwrap_or(tag_b));

    match (version_a, version_b) {
        (Ok(a), Ok(b)) => b.cmp(&a),
        (Ok(_), Err(_)) => std::cmp::Ordering::Less,
        (Err(_), Ok(_)) => std::cmp::Ordering::Greater,
        (Err(_), Err(_)) => std::cmp::Ordering::Equal,
    }
}

/// Multiple tags can exist on an SHA. Sometimes a moving tag is attached to a
/// version tag. Prefer tags that look like versions, then pick the one most
/// similar to the current reference.
fn select_best_tag<'a>(
    tags: &[&'a str],
    current_ref: &str,
    allow_non_version_like: bool,
) -> Option<&'a str> {
    let has_version_like = tags.iter().any(|tag| tag.contains('.'));
    let mut candidates = if has_version_like {
        tags.iter()
            .filter(|tag| tag.contains('.'))
            .copied()
            .collect::<Vec<_>>()
    } else if allow_non_version_like {
        tags.to_vec()
    } else {
        return None;
    };

    candidates.sort_by(|tag_a, tag_b| {
        levenshtein::levenshtein(tag_a, current_ref)
            .cmp(&levenshtein::levenshtein(tag_b, current_ref))
            .then_with(|| compare_tag_versions_desc(tag_a, tag_b))
            .then_with(|| tag_a.cmp(tag_b))
    });

    candidates.into_iter().next()
}

/// Checks out the candidate manifest and verifies all configured hook ids still exist.
async fn checkout_and_validate_manifest(
    repo_path: &Path,
    rev: &str,
    required_hook_ids: &[&str],
) -> Result<()> {
    // Workaround for Windows: https://github.com/pre-commit/pre-commit/issues/2865,
    // https://github.com/j178/prek/issues/614
    if cfg!(windows) {
        git::git_cmd("git show")?
            .arg("show")
            .arg(format!("{rev}:{PRE_COMMIT_HOOKS_YAML}"))
            .current_dir(repo_path)
            .remove_git_envs()
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .await?;
    }

    git::git_cmd("git checkout")?
        .arg("checkout")
        .arg("--quiet")
        .arg(rev)
        .arg("--")
        .arg(PRE_COMMIT_HOOKS_YAML)
        .current_dir(repo_path)
        .remove_git_envs()
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .await?;

    let manifest = config::read_manifest(&repo_path.join(PRE_COMMIT_HOOKS_YAML))?;
    let new_hook_ids = manifest
        .hooks
        .into_iter()
        .map(|h| h.id)
        .collect::<FxHashSet<_>>();
    let hooks_missing = required_hook_ids
        .iter()
        .filter(|hook_id| !new_hook_ids.contains(**hook_id))
        .collect::<Vec<_>>();
    if !hooks_missing.is_empty() {
        anyhow::bail!(
            "Cannot update to rev `{}`, hook{} {} missing: {}",
            rev,
            if hooks_missing.len() > 1 { "s" } else { "" },
            if hooks_missing.len() > 1 { "are" } else { "is" },
            hooks_missing.into_iter().join(", ")
        );
    }

    Ok(())
}

/// Rewrites one config file with the resolved revisions for its remote repos.
async fn write_new_config(path: &Path, revisions: &[Option<Revision>]) -> Result<()> {
    let content = fs_err::tokio::read_to_string(path).await?;
    let new_content = match path.extension() {
        Some(ext) if ext.eq_ignore_ascii_case("toml") => {
            render_updated_toml_config(path, &content, revisions)?
        }
        _ => render_updated_yaml_config(path, &content, revisions)?,
    };

    fs_err::tokio::write(path, new_content)
        .await
        .with_context(|| {
            format!(
                "Failed to write updated config file `{}`",
                path.user_display()
            )
        })?;

    Ok(())
}

/// Updates `rev` values and `# frozen:` comments in a TOML config while preserving formatting.
fn render_updated_toml_config(
    path: &Path,
    content: &str,
    revisions: &[Option<Revision>],
) -> Result<String> {
    let mut doc = content.parse::<DocumentMut>()?;
    let Some(repos) = doc
        .get_mut("repos")
        .and_then(|item| item.as_array_of_tables_mut())
    else {
        anyhow::bail!("Missing `[[repos]]` array in `{}`", path.user_display());
    };

    let mut remote_repos = Vec::new();
    for table in repos.iter_mut() {
        let repo_value = table
            .get("repo")
            .and_then(|item| item.as_value())
            .and_then(|value| value.as_str())
            .unwrap_or_default();

        if matches!(repo_value, "local" | "meta" | "builtin") {
            continue;
        }

        if !table.contains_key("rev") {
            anyhow::bail!(
                "Found remote repo without `rev` in `{}`",
                path.user_display()
            );
        }

        remote_repos.push(table);
    }

    if remote_repos.len() != revisions.len() {
        anyhow::bail!(
            "Found {} remote repos in `{}` but expected {}, file content may have changed",
            remote_repos.len(),
            path.user_display(),
            revisions.len()
        );
    }

    for (table, revision) in remote_repos.into_iter().zip_eq(revisions) {
        let Some(revision) = revision else {
            continue;
        };

        let Some(value) = table.get_mut("rev").and_then(|item| item.as_value_mut()) else {
            continue;
        };

        let suffix = value
            .decor()
            .suffix()
            .and_then(|s| s.as_str())
            .filter(|s| !s.trim_start().starts_with("# frozen:"))
            .map(str::to_string);

        *value = toml_edit::Value::from(revision.rev.clone());

        if let Some(frozen) = &revision.frozen {
            value.decor_mut().set_suffix(format!(" # frozen: {frozen}"));
        } else if let Some(suffix) = suffix {
            value.decor_mut().set_suffix(suffix);
        }
    }

    Ok(doc.to_string())
}

/// Updates `rev` values and `# frozen:` comments in a YAML config while preserving line layout.
fn render_updated_yaml_config(
    path: &Path,
    content: &str,
    revisions: &[Option<Revision>],
) -> Result<String> {
    let mut lines = content
        .split_inclusive('\n')
        .map(ToString::to_string)
        .collect::<Vec<_>>();

    let rev_regex = regex!(r#"^(\s+)rev:(\s*)(['"]?)([^\s#]+)(.*)(\r?\n)$"#);

    let rev_lines = lines
        .iter()
        .enumerate()
        .filter_map(|(line_no, line)| {
            if rev_regex.is_match(line) {
                Some(line_no)
            } else {
                None
            }
        })
        .collect::<Vec<_>>();

    if rev_lines.len() != revisions.len() {
        anyhow::bail!(
            "Found {} `rev:` lines in `{}` but expected {}, file content may have changed",
            rev_lines.len(),
            path.user_display(),
            revisions.len()
        );
    }

    for (line_no, revision) in rev_lines.iter().zip_eq(revisions) {
        let Some(revision) = revision else {
            // This repo was not updated, skip
            continue;
        };

        let caps = rev_regex
            .captures(&lines[*line_no])
            .context("Failed to capture rev line")?;

        let new_rev = serialize_yaml_scalar(&revision.rev, &caps[3])?;

        let comment = if let Some(frozen) = &revision.frozen {
            format!("  # frozen: {frozen}")
        } else if caps[5].trim_start().starts_with("# frozen:") {
            String::new()
        } else {
            caps[5].to_string()
        };

        lines[*line_no] = format!(
            "{}rev:{}{}{}{}",
            &caps[1], &caps[2], new_rev, comment, &caps[6]
        );
    }

    Ok(lines.join(""))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::process::Cmd;
    use std::time::{SystemTime, UNIX_EPOCH};

    async fn setup_test_repo() -> tempfile::TempDir {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path();

        // Initialize git repo
        git::git_cmd("git init")
            .unwrap()
            .arg("init")
            .current_dir(repo)
            .remove_git_envs()
            .output()
            .await
            .unwrap();

        // Configure git user
        git::git_cmd("git config")
            .unwrap()
            .args(["config", "user.email", "test@test.com"])
            .current_dir(repo)
            .remove_git_envs()
            .output()
            .await
            .unwrap();

        git::git_cmd("git config")
            .unwrap()
            .args(["config", "user.name", "Test"])
            .current_dir(repo)
            .remove_git_envs()
            .output()
            .await
            .unwrap();

        // First commit (required before creating a branch)
        git::git_cmd("git commit")
            .unwrap()
            .args([
                "-c",
                "commit.gpgsign=false",
                "commit",
                "--allow-empty",
                "-m",
                "initial",
            ])
            .current_dir(repo)
            .remove_git_envs()
            .output()
            .await
            .unwrap();

        // Create a trunk branch (avoid dangling commits)
        git::git_cmd("git checkout")
            .unwrap()
            .args(["branch", "-M", "trunk"])
            .current_dir(repo)
            .remove_git_envs()
            .output()
            .await
            .unwrap();

        tmp
    }

    fn git_cmd(dir: impl AsRef<Path>, summary: &str) -> Cmd {
        let mut cmd = git::git_cmd(summary).unwrap();
        cmd.current_dir(dir)
            .args(["-c", "commit.gpgsign=false"])
            .args(["-c", "tag.gpgsign=false"]);
        cmd
    }

    async fn create_commit(repo: &Path, message: &str) {
        git_cmd(repo, "git commit")
            .args(["commit", "--allow-empty", "-m", message])
            .remove_git_envs()
            .output()
            .await
            .unwrap();
    }

    async fn create_backdated_commit(repo: &Path, message: &str, days_ago: u64) {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - (days_ago * 86400);

        let date_str = format!("{timestamp} +0000");

        git_cmd(repo, "git commit")
            .args(["commit", "--allow-empty", "-m", message])
            .env("GIT_AUTHOR_DATE", &date_str)
            .env("GIT_COMMITTER_DATE", &date_str)
            .remove_git_envs()
            .output()
            .await
            .unwrap();
    }

    async fn create_lightweight_tag(repo: &Path, tag: &str) {
        git_cmd(repo, "git tag")
            .arg("tag")
            .arg(tag)
            .remove_git_envs()
            .output()
            .await
            .unwrap();
    }

    async fn create_annotated_tag(repo: &Path, tag: &str, days_ago: u64) {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - (days_ago * 86400);

        let date_str = format!("{timestamp} +0000");

        git_cmd(repo, "git tag")
            .arg("tag")
            .arg(tag)
            .arg("-m")
            .arg(tag)
            .env("GIT_AUTHOR_DATE", &date_str)
            .env("GIT_COMMITTER_DATE", &date_str)
            .remove_git_envs()
            .output()
            .await
            .unwrap();
    }

    fn get_backdated_timestamp(days_ago: u64) -> u64 {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        now - (days_ago * 86400)
    }

    #[tokio::test]
    async fn test_list_tag_metadata() {
        let tmp = setup_test_repo().await;
        let repo = tmp.path();

        create_backdated_commit(repo, "old", 5).await;
        create_lightweight_tag(repo, "v0.1.0").await;

        create_backdated_commit(repo, "new", 2).await;
        create_lightweight_tag(repo, "v0.2.0").await;
        create_annotated_tag(repo, "alias-v0.2.0", 0).await;

        let timestamps = list_tag_metadata(repo).await.unwrap();
        assert_eq!(timestamps.len(), 3);
        assert_eq!(timestamps[0].tag, "alias-v0.2.0");
        assert_eq!(timestamps[1].tag, "v0.2.0");
        assert_eq!(timestamps[2].tag, "v0.1.0");
        assert_eq!(timestamps[0].commit, timestamps[1].commit);
    }

    #[tokio::test]
    async fn test_resolve_bleeding_edge_prefers_exact_tag() {
        let tmp = setup_test_repo().await;
        let repo = tmp.path();

        create_commit(repo, "tagged").await;
        create_lightweight_tag(repo, "v1.2.3").await;

        git::git_cmd("git fetch")
            .unwrap()
            .args(["fetch", ".", "HEAD"])
            .current_dir(repo)
            .remove_git_envs()
            .output()
            .await
            .unwrap();

        let rev = resolve_bleeding_edge(repo).await.unwrap();
        assert_eq!(rev, Some("v1.2.3".to_string()));
    }

    #[tokio::test]
    async fn test_resolve_bleeding_edge_falls_back_to_rev_parse() {
        let tmp = setup_test_repo().await;
        let repo = tmp.path();

        create_commit(repo, "untagged").await;

        git::git_cmd("git fetch")
            .unwrap()
            .args(["fetch", ".", "HEAD"])
            .current_dir(repo)
            .remove_git_envs()
            .output()
            .await
            .unwrap();

        let rev = resolve_bleeding_edge(repo).await.unwrap();

        let head = git::git_cmd("git rev-parse")
            .unwrap()
            .args(["rev-parse", "HEAD"])
            .current_dir(repo)
            .remove_git_envs()
            .output()
            .await
            .unwrap()
            .stdout;
        let head = String::from_utf8_lossy(&head).trim().to_string();

        assert_eq!(rev, Some(head));
    }

    #[tokio::test]
    async fn test_select_update_revision_uses_cooldown_bucket() {
        let tmp = setup_test_repo().await;
        let repo = tmp.path();

        create_backdated_commit(repo, "candidate", 5).await;
        create_lightweight_tag(repo, "v2.0.0-rc1").await;
        create_lightweight_tag(repo, "totally-different").await;

        create_backdated_commit(repo, "latest", 1).await;
        create_lightweight_tag(repo, "v2.0.0").await;

        let tag_timestamps = list_tag_metadata(repo).await.unwrap();
        let rev = select_update_revision(repo, "v2.0.0", false, 3, &tag_timestamps)
            .await
            .unwrap();

        assert_eq!(rev, Some("v2.0.0-rc1".to_string()));
    }

    #[tokio::test]
    async fn test_select_update_revision_returns_none_when_all_tags_too_new() {
        let tmp = setup_test_repo().await;
        let repo = tmp.path();

        create_backdated_commit(repo, "recent-1", 2).await;
        create_lightweight_tag(repo, "v1.0.0").await;

        create_backdated_commit(repo, "recent-2", 1).await;
        create_lightweight_tag(repo, "v1.1.0").await;

        let tag_timestamps = list_tag_metadata(repo).await.unwrap();
        let rev = select_update_revision(repo, "v1.1.0", false, 5, &tag_timestamps)
            .await
            .unwrap();

        assert_eq!(rev, None);
    }

    #[tokio::test]
    async fn test_select_update_revision_picks_oldest_eligible_bucket() {
        let tmp = setup_test_repo().await;
        let repo = tmp.path();

        create_backdated_commit(repo, "oldest", 10).await;
        create_lightweight_tag(repo, "v1.0.0").await;

        create_backdated_commit(repo, "mid", 4).await;
        create_lightweight_tag(repo, "v1.1.0").await;

        create_backdated_commit(repo, "newest", 1).await;
        create_lightweight_tag(repo, "v1.2.0").await;

        let tag_timestamps = list_tag_metadata(repo).await.unwrap();
        let rev = select_update_revision(repo, "v1.2.0", false, 5, &tag_timestamps)
            .await
            .unwrap();

        assert_eq!(rev, Some("v1.0.0".to_string()));
    }

    #[tokio::test]
    async fn test_select_update_revision_prefers_version_like_tags() {
        let tmp = setup_test_repo().await;
        let repo = tmp.path();

        create_backdated_commit(repo, "eligible", 2).await;
        create_lightweight_tag(repo, "moving-tag").await;
        create_lightweight_tag(repo, "v1.0.0").await;

        // Even though the current rev matches the moving tag exactly, the dotted tag
        // should be preferred.
        let tag_timestamps = list_tag_metadata(repo).await.unwrap();
        let rev = select_update_revision(repo, "moving-tag", false, 1, &tag_timestamps)
            .await
            .unwrap();

        assert_eq!(rev, Some("v1.0.0".to_string()));
    }

    #[tokio::test]
    async fn test_select_update_revision_picks_closest_version_string() {
        let tmp = setup_test_repo().await;
        let repo = tmp.path();

        create_backdated_commit(repo, "eligible", 3).await;
        create_lightweight_tag(repo, "v1.2.0").await;
        create_lightweight_tag(repo, "foo-1.2.0").await;
        create_lightweight_tag(repo, "v2.0.0").await;

        let tag_timestamps = list_tag_metadata(repo).await.unwrap();
        let rev = select_update_revision(repo, "v1.2.3", false, 1, &tag_timestamps)
            .await
            .unwrap();

        assert_eq!(rev, Some("v1.2.0".to_string()));
    }

    #[tokio::test]
    async fn test_list_tag_metadata_stable_order_for_equal_timestamps() {
        let tmp = setup_test_repo().await;
        let repo = tmp.path();

        // Create multiple tags on the same commit (same timestamp)
        create_backdated_commit(repo, "release", 5).await;
        create_lightweight_tag(repo, "v1.0.0").await;
        create_lightweight_tag(repo, "v1.0.3").await;
        create_lightweight_tag(repo, "v1.0.5").await;
        create_lightweight_tag(repo, "v1.0.2").await;

        let timestamps = list_tag_metadata(repo).await.unwrap();

        // All timestamps are equal (tags on same commit).
        // Within equal timestamps, semver tags should sort highest version first.
        let tags: Vec<&str> = timestamps.iter().map(|tag| tag.tag.as_str()).collect();
        assert_eq!(tags, vec!["v1.0.5", "v1.0.3", "v1.0.2", "v1.0.0"]);
    }

    #[tokio::test]
    async fn test_list_tag_metadata_deterministic_order_for_equal_timestamp_non_semver() {
        let tmp = setup_test_repo().await;
        let repo = tmp.path();

        // Lightweight tags on the same commit share a timestamp.
        create_backdated_commit(repo, "release", 5).await;
        create_lightweight_tag(repo, "beta").await;
        create_lightweight_tag(repo, "alpha").await;
        create_lightweight_tag(repo, "gamma").await;

        let timestamps = list_tag_metadata(repo).await.unwrap();
        let tags: Vec<&str> = timestamps.iter().map(|tag| tag.tag.as_str()).collect();
        assert_eq!(tags, vec!["alpha", "beta", "gamma"]);
    }

    #[test]
    fn test_no_lazy_fetch_unsupported() {
        assert!(no_lazy_fetch_unsupported(
            b"unknown option: --no-lazy-fetch\n"
        ));
        assert!(!no_lazy_fetch_unsupported(
            b"fatal: Not a valid object name 1234567890abcdef1234567890abcdef12345678^{commit}\n"
        ));
    }
}