verctl 0.4.2

Stack-agnostic version PRs from Changesets-format fragments
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
use std::env;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail, ensure};
use git2::{
    Cred, FetchOptions, PushOptions, RemoteCallbacks, Repository, Signature, Status, StatusOptions,
};

use crate::github::Repo;

#[must_use]
pub fn current_branch(root: &Path) -> Option<String> {
    let repo = repo_covering(root)?;
    let head = repo.head().ok()?;
    let name = head.shorthand().ok()?;
    (name != "HEAD").then(|| name.to_owned())
}

/// The commit HEAD currently names, as a full hex SHA.
pub fn head_sha(root: &Path) -> Result<String> {
    let repo =
        Repository::discover(root).context("publish needs a git repository to name the tag")?;
    let commit = repo
        .head()
        .and_then(|head| head.peel_to_commit())
        .context("publish needs HEAD to name the tag")?;
    Ok(commit.id().to_string())
}

/// File contents at the merge-base of HEAD and the default branch.
///
/// Paths are relative to `root` (the directory holding `.ctl/`) and are mapped
/// onto the git workdir so `-c crates/foo/.ctl/ver.yaml` still hits the
/// right blob. One repository open for the whole list.
pub fn files_on_merge_base(
    root: &Path,
    rels: &[&Path],
    candidates: &[String],
) -> Result<Vec<Option<String>>> {
    let Some(repo) = repo_covering(root) else {
        return Ok(vec![None; rels.len()]);
    };
    let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
        return Ok(vec![None; rels.len()]);
    };
    let head = repo.head().context("cannot compare versions (need HEAD)")?;
    let head = head
        .peel_to_commit()
        .context("cannot compare versions (need HEAD)")?;
    let base = repo.merge_base(head.id(), upstream.id()).context(
        "cannot compare versions against the default branch (need a full fetch, not a shallow clone)",
    )?;
    let tree = repo.find_commit(base)?.tree()?;
    let workdir = repo.workdir().map(Path::to_path_buf);
    Ok(rels
        .iter()
        .map(|rel| {
            git_path(root, rel, workdir.as_deref()).and_then(|path| blob_at(&repo, &tree, &path))
        })
        .collect())
}

fn git_path(root: &Path, rel: &Path, workdir: Option<&Path>) -> Option<PathBuf> {
    let abs = if rel.is_absolute() {
        rel.to_path_buf()
    } else {
        root.join(rel)
    };
    let abs = abs.canonicalize().ok()?;
    let workdir = workdir?.canonicalize().ok()?;
    abs.strip_prefix(workdir).ok().map(Path::to_path_buf)
}

fn blob_at(repo: &Repository, tree: &git2::Tree<'_>, rel: &Path) -> Option<String> {
    let entry = tree.get_path(rel).ok()?;
    let blob = entry.to_object(repo).ok()?.peel_to_blob().ok()?;
    Some(String::from_utf8_lossy(blob.content()).into_owned())
}

pub fn origin_url(root: &Path) -> Result<String> {
    let repo = Repository::discover(root).context("open git repository")?;
    let remote = repo.find_remote("origin").context("git remote origin")?;
    remote
        .url()
        .context("origin has no URL")
        .map(ToOwned::to_owned)
}

/// The commit that added a file, as the changelog names it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddedBy {
    pub sha: String,
    pub subject: String,
}

/// The commit that added `path`: the newest commit on HEAD's first-parent
/// history whose tree has the file and whose first parent's tree does not. A
/// squash merge is that commit, and its subject carries the pull request
/// number. When that commit is a merge and another parent already has the
/// file, the file arrived with the merged branch, so the walk continues down
/// that parent's first-parent history: a fragment merged from `next` links the
/// pull request that added it there, not the merge. A merge titled with its
/// pull request, `Title (#12)`, whose branch commits name none is the commit
/// named instead, so a repository that merges with merge commits keeps its
/// pull request links: the deepest such merge on the way down wins.
///
/// No repository, and a file HEAD does not track, is `None`: a fixture outside
/// git, or a fragment not committed yet, has no commit to name. A shallow
/// clone that ends before the adding commit is `None` too: libgit2 reads
/// `.git/shallow` as grafts, so the boundary looks parentless, and naming it
/// would link the wrong commit. A parent that exists but cannot be loaded is
/// treated the same way.
pub fn added_by(root: &Path, path: &Path) -> Result<Option<AddedBy>> {
    let Ok(repo) = Repository::discover(root) else {
        return Ok(None);
    };
    let Some(rel) = git_path(root, path, repo.workdir()) else {
        return Ok(None);
    };
    let Ok(head) = repo.head().and_then(|head| head.peel_to_commit()) else {
        return Ok(None);
    };
    if head.tree()?.get_path(&rel).is_err() {
        return Ok(None);
    }
    let mut commit = head;
    let mut named_merge = None;
    loop {
        if commit.parent_count() == 0 && repo.is_shallow() {
            return Ok(None);
        }
        let mut holder = None;
        for index in 0..commit.parent_count() {
            let Ok(parent) = commit.parent(index) else {
                return Ok(None);
            };
            if parent.tree()?.get_path(&rel).is_ok() {
                holder = Some((index, parent));
                break;
            }
        }
        let added = named(&commit);
        let Some((index, parent)) = holder else {
            return Ok(Some(match named_merge {
                Some(merge) if pull_request_number(&added.subject).is_none() => merge,
                Some(_) | None => added,
            }));
        };
        if index > 0 && pull_request_number(&added.subject).is_some() {
            named_merge = Some(added);
        }
        commit = parent;
    }
}

fn named(commit: &git2::Commit<'_>) -> AddedBy {
    AddedBy {
        sha: commit.id().to_string(),
        subject: String::from_utf8_lossy(commit.summary_bytes().unwrap_or_default()).into_owned(),
    }
}

/// The pull request a squash-merge subject names: a trailing `(#12)`.
pub(crate) fn pull_request_number(subject: &str) -> Option<u64> {
    let (_, digits) = subject.trim_end().strip_suffix(')')?.rsplit_once("(#")?;
    if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    digits.parse().ok()
}

#[must_use]
pub fn upstream_default_branch(root: &Path) -> Option<String> {
    let repo = Repository::discover(root).ok()?;
    let reference = repo.find_reference("refs/remotes/origin/HEAD").ok()?;
    let target = reference.symbolic_target().ok()??;
    let name = target.trim_start_matches("refs/remotes/origin/");
    (!name.is_empty()).then(|| name.to_owned())
}

/// Fail unless HEAD is on the default-branch history.
///
/// No repository, and no `origin` remote, is a skip — local fixtures
/// have nothing to prove. A repo that has `origin` but no peelable
/// default-tracking ref fails closed. A shallow clone that cannot walk
/// the graph also fails closed.
pub fn require_on_default_history(root: &Path) -> Result<()> {
    prove_default_history(root, &candidate_names(env_base_ref().as_deref()))
}

/// How to fetch `origin/<branch>` when that ref is missing.
pub enum FetchDefault {
    /// `git fetch origin`.
    Origin,
    /// GitHub HTTPS. Credentials are the callback, never the URL.
    GitHub { token: String, repository: String },
}

impl FetchDefault {
    #[must_use]
    pub fn from_env() -> Self {
        match (env::var("GITHUB_TOKEN"), env::var("GITHUB_REPOSITORY")) {
            (Ok(token), Ok(repository)) if !token.is_empty() && !repository.is_empty() => {
                Self::GitHub { token, repository }
            }
            _ => Self::Origin,
        }
    }
}

/// HTTPS URL for an `owner/name` slug. No credentials in the URL.
#[must_use]
pub fn github_https_url(repository: &str) -> String {
    format!("https://github.com/{repository}.git")
}

/// Username GitHub git-over-HTTPS expects. Not an HTTP Bearer scheme.
#[must_use]
pub fn github_git_user() -> &'static str {
    "x-access-token"
}

/// `VERCTL_DEFAULT_BRANCH` only.
///
/// `GITHUB_BASE_REF` is a candidate for `require_on_default_history`,
/// not a name to rewrite `origin/HEAD` with.
#[must_use]
pub fn configured_default_branch() -> Option<String> {
    env::var("VERCTL_DEFAULT_BRANCH")
        .ok()
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
}

/// Point `origin/HEAD` at `origin/<branch>`. Fetch that one ref only
/// when it is missing. The fetch is the branch's history, not a
/// depth-1 tip: `require_on_default_history` walks parents.
pub fn ensure_origin_head(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
    if branch.is_empty() {
        return Ok(());
    }
    let Some(repo) = repo_covering(root) else {
        return Ok(());
    };
    if repo.find_remote("origin").is_err() {
        return Ok(());
    }
    let remote_ref = format!("refs/remotes/origin/{branch}");
    if peel_remote(&repo, &remote_ref).is_none() {
        fetch_one_branch(&repo, branch, fetch)?;
    }
    ensure!(
        peel_remote(&repo, &remote_ref).is_some(),
        "cannot resolve the default branch ({remote_ref} is missing; fetch the default branch)"
    );
    repo.reference_symbolic(
        "refs/remotes/origin/HEAD",
        &remote_ref,
        true,
        "verctl default branch",
    )
    .context("point origin/HEAD at the default branch")?;
    Ok(())
}

fn fetch_one_branch(repo: &Repository, branch: &str, fetch: &FetchDefault) -> Result<()> {
    let spec = format!("+refs/heads/{branch}:refs/remotes/origin/{branch}");
    match fetch {
        FetchDefault::Origin => {
            let mut remote = repo
                .find_remote("origin")
                .context("fetch the default branch")?;
            remote
                .fetch(&[spec.as_str()], None, None)
                .with_context(|| format!("git fetch {spec}"))?;
        }
        FetchDefault::GitHub { token, repository } => {
            let url = github_https_url(repository);
            let mut remote = repo
                .remote_anonymous(&url)
                .context("anonymous https remote")?;
            let mut callbacks = RemoteCallbacks::new();
            let token = token.clone();
            callbacks.credentials(move |_url, _username, _allowed| {
                Cred::userpass_plaintext(github_git_user(), &token)
            });
            let mut opts = FetchOptions::new();
            opts.remote_callbacks(callbacks);
            remote
                .fetch(&[spec.as_str()], Some(&mut opts), None)
                .with_context(|| format!("git fetch {spec}"))?;
        }
    }
    Ok(())
}

fn prove_default_history(root: &Path, candidates: &[String]) -> Result<()> {
    let Some(repo) = repo_covering(root) else {
        return Ok(());
    };
    let Ok(head) = repo.head() else {
        return Ok(());
    };
    let Ok(head) = head.peel_to_commit() else {
        return Ok(());
    };
    let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
        return Ok(());
    };
    if head.id() == upstream.id() {
        return Ok(());
    }
    match repo.graph_descendant_of(upstream.id(), head.id()) {
        Ok(true) => Ok(()),
        Ok(false) => bail!(
            "publish only from a Version PR commit on the default branch (HEAD {head} is not an ancestor of {upstream})",
            head = head.id(),
            upstream = upstream.id()
        ),
        Err(error) => Err(error).context(
            "publish cannot prove HEAD is on the default branch (need a full fetch, not a shallow clone)",
        ),
    }
}

/// The working tree that holds `dir`, canonicalized.
///
/// The ceiling for an upward file search: nothing above a repository
/// root belongs to the project inside it.
#[must_use]
pub fn workdir_covering(dir: &Path) -> Option<PathBuf> {
    repo_covering(dir)?
        .workdir()
        .and_then(|workdir| workdir.canonicalize().ok())
}

/// Every path git tracks under `root`, relative to `root` itself.
///
/// The index, not a directory walk: build output, vendored trees, and
/// anything else gitignored is not part of what this repo publishes. The index
/// speaks in paths from the working tree, and `root` is a project inside it —
/// one repository may hold several — so anything outside `root` is not this
/// project's, and what is left is rebased onto it. A tree with no repository
/// tracks nothing — it cannot serve a file by tag — but a repository whose
/// index cannot be read is an error, never an empty answer.
pub fn tracked(root: &Path) -> Result<Vec<PathBuf>> {
    let Some(repo) = repo_covering(root) else {
        return Ok(Vec::new());
    };
    let index = repo.index().context("git index")?;
    let project = project_prefix(&repo, root);
    Ok(index
        .iter()
        .filter_map(|entry| String::from_utf8(entry.path).ok().map(PathBuf::from))
        .filter_map(|path| path.strip_prefix(&project).ok().map(Path::to_path_buf))
        .collect())
}

/// Whether the repository is told to ignore `rel`, a path relative to `root`.
///
/// Ignoring a file is a repo saying it is not part of what it publishes — the
/// same statement `tracked` already reads the index for. So an ignored file is
/// not a forgotten one, and nothing should ask its author to commit it.
#[must_use]
pub fn is_ignored(root: &Path, rel: &Path) -> bool {
    repo_covering(root).is_some_and(|repo| {
        let project = project_prefix(&repo, root);
        repo.is_path_ignored(project.join(rel)).unwrap_or(false)
    })
}

/// Whether a repository covers `root` at all.
///
/// `tracked` answers "nothing" both for an empty index and for a tree with no
/// repository, and those are different states: a file the index does not carry
/// is untracked only where an index exists to not carry it.
#[must_use]
pub fn is_repository(root: &Path) -> bool {
    repo_covering(root).is_some()
}

/// Where `root` sits inside the working tree: empty when it is the root.
fn project_prefix(repo: &Repository, root: &Path) -> PathBuf {
    let Some(workdir) = repo.workdir().and_then(|dir| dir.canonicalize().ok()) else {
        return PathBuf::new();
    };
    root.canonicalize()
        .ok()
        .and_then(|root| root.strip_prefix(&workdir).ok().map(Path::to_path_buf))
        .unwrap_or_default()
}

fn repo_covering(root: &Path) -> Option<Repository> {
    if let Ok(repo) = Repository::open(root) {
        return Some(repo);
    }
    let repo = Repository::discover(root).ok()?;
    let workdir = repo.workdir()?.canonicalize().ok()?;
    let root = root.canonicalize().ok()?;
    root.starts_with(workdir).then_some(repo)
}

fn peel_remote<'a>(repo: &'a Repository, name: &str) -> Option<git2::Commit<'a>> {
    repo.find_reference(name)
        .ok()
        .and_then(|reference| reference.peel_to_commit().ok())
}

fn origin_head_ref(repo: &Repository) -> Option<String> {
    let reference = repo.find_reference("refs/remotes/origin/HEAD").ok()?;
    let target = reference.symbolic_target().ok()??;
    let name = target.trim_start_matches("refs/remotes/origin/");
    (!name.is_empty()).then(|| format!("refs/remotes/origin/{name}"))
}

fn env_base_ref() -> Option<String> {
    env::var("GITHUB_BASE_REF")
        .ok()
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
}

/// `GITHUB_BASE_REF` (PR base) then `main` / `master`.
///
/// `GITHUB_REF_NAME` is not a candidate: on push it is the branch
/// being pushed, so `origin/<that branch>` would always match HEAD.
/// A non-main default on Actions is `origin/HEAD`, which
/// `ensure_origin_head` fetches and points at
/// `VERCTL_DEFAULT_BRANCH`.
#[must_use]
pub fn default_branch_candidates() -> Vec<String> {
    candidate_names(env_base_ref().as_deref())
}

#[must_use]
pub fn default_branch_candidates_from(base_ref: Option<&str>) -> Vec<String> {
    candidate_names(base_ref)
}

fn candidate_names(base_ref: Option<&str>) -> Vec<String> {
    let mut names = Vec::new();
    if let Some(value) = base_ref.map(str::trim).filter(|value| !value.is_empty()) {
        names.push(value.to_owned());
    }
    for stock in ["main", "master"] {
        if !names.iter().any(|name| name == stock) {
            names.push(stock.to_owned());
        }
    }
    names
}

fn default_upstream_commit<'a>(
    repo: &'a Repository,
    candidates: &[String],
) -> Result<Option<git2::Commit<'a>>> {
    if let Some(name) = origin_head_ref(repo) {
        return match peel_remote(repo, &name) {
            Some(commit) => Ok(Some(commit)),
            None => bail!(
                "cannot resolve the default branch ({name} is missing; fetch the default branch)"
            ),
        };
    }
    for name in candidates {
        let reference = format!("refs/remotes/origin/{name}");
        if let Some(commit) = peel_remote(repo, &reference) {
            return Ok(Some(commit));
        }
    }
    if repo.find_remote("origin").is_ok() {
        bail!(
            "cannot resolve the default branch (origin exists but origin/HEAD, origin/main, and origin/master are missing; fetch the default branch)"
        );
    }
    Ok(None)
}

fn matches_stage(pattern: &str, rel: &str) -> bool {
    glob::Pattern::new(pattern)
        .is_ok_and(|compiled| compiled.matches(rel) || compiled.matches(&format!("./{rel}")))
}

/// Fail if the worktree has dirty paths outside `allowed` and `globs`.
///
/// Returns dirty paths that match `globs` (modified, untracked, or
/// deleted files). Directories are skipped. Same `git status` walk as
/// the unexpected-dirty check; not a filesystem glob.
pub fn assert_only_allowed(
    root: &Path,
    allowed: &[PathBuf],
    globs: &[String],
    stage_ignored: bool,
) -> Result<Vec<PathBuf>> {
    let Ok(repo) = Repository::open(root).or_else(|_| Repository::discover(root)) else {
        return Ok(Vec::new());
    };
    let mut opts = StatusOptions::new();
    opts.include_untracked(true)
        .recurse_untracked_dirs(true)
        .include_ignored(false);
    let statuses = repo.statuses(Some(&mut opts)).context("git status")?;
    let workdir = repo.workdir().unwrap_or(root);
    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let workdir = workdir
        .canonicalize()
        .unwrap_or_else(|_| workdir.to_path_buf());
    let mut extra = Vec::new();
    let mut staged = Vec::new();
    for entry in &statuses {
        let Ok(rel) = entry.path() else {
            continue;
        };
        let abs = workdir.join(rel);
        if !abs.starts_with(&root) {
            continue;
        }
        if abs.is_dir() {
            continue;
        }
        if allowed
            .iter()
            .any(|path| path == &abs || path.ends_with(rel))
        {
            continue;
        }
        if globs.iter().any(|pattern| matches_stage(pattern, rel)) {
            staged.push(abs);
            continue;
        }
        extra.push(rel.to_owned());
    }
    if stage_ignored && !globs.is_empty() {
        let mut ignored = StatusOptions::new();
        ignored
            .include_ignored(true)
            .recurse_ignored_dirs(true)
            .include_untracked(false);
        for pattern in globs {
            ignored.pathspec(pattern.as_str());
        }
        let ignored = repo
            .statuses(Some(&mut ignored))
            .context("git status (ignored)")?;
        for entry in &ignored {
            if !entry.status().intersects(Status::IGNORED) {
                continue;
            }
            let Ok(rel) = entry.path() else {
                continue;
            };
            let abs = workdir.join(rel);
            if !abs.starts_with(&root) || abs.is_dir() {
                continue;
            }
            if globs.iter().any(|pattern| matches_stage(pattern, rel))
                && !staged.iter().any(|path| path == &abs)
            {
                staged.push(abs);
            }
        }
    }
    if extra.is_empty() {
        return Ok(staged);
    }
    bail!(
        "prepare produced unexpected paths (declare them in prepare.stage): {}",
        extra.join(", ")
    );
}

/// Commit `paths` onto `branch` without moving HEAD. `Empty` if the tree is
/// unchanged.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum PushOutcome {
    /// No version files changed.
    Empty,
    /// Branch was updated and pushed.
    Pushed,
}

pub fn commit_branch_and_push(
    root: &Path,
    branch: &str,
    message: &str,
    token: &str,
    github: &Repo,
    paths: &[PathBuf],
) -> Result<PushOutcome> {
    let repo = Repository::discover(root).context("open git repository")?;
    let workdir = repo
        .workdir()
        .context("repository has no workdir")?
        .to_path_buf();
    let parent = repo
        .head()
        .context("git HEAD")?
        .peel_to_commit()
        .context("HEAD commit")?;
    let Some(_) = write_commit_on_branch(&repo, &workdir, &parent, branch, message, paths)? else {
        return Ok(PushOutcome::Empty);
    };

    let owner = &github.owner;
    let name = &github.name;
    let https = format!("https://github.com/{owner}/{name}.git");
    let mut remote = repo
        .remote_anonymous(&https)
        .context("anonymous https remote")?;
    let mut callbacks = RemoteCallbacks::new();
    callbacks
        .credentials(|_url, _username, _allowed| Cred::userpass_plaintext("x-access-token", token));
    let mut opts = PushOptions::new();
    opts.remote_callbacks(callbacks);
    let refspec = format!("+refs/heads/{branch}:refs/heads/{branch}");
    remote
        .push(&[&refspec], Some(&mut opts))
        .context("git push")?;
    Ok(PushOutcome::Pushed)
}

fn write_commit_on_branch(
    repo: &Repository,
    workdir: &Path,
    parent: &git2::Commit<'_>,
    branch: &str,
    message: &str,
    paths: &[PathBuf],
) -> Result<Option<git2::Oid>> {
    let parent_tree = parent.tree().context("HEAD tree")?;
    let mut index = repo.index().context("git index")?;
    index
        .read_tree(&parent_tree)
        .context("reset index to HEAD")?;
    for path in paths {
        let rel = workdir_rel(workdir, path)?;
        if workdir.join(&rel).exists() {
            index
                .add_path(&rel)
                .with_context(|| format!("git add {}", rel.display()))?;
        } else {
            let _ = index.remove_path(&rel);
        }
    }
    let tree_id = index.write_tree().context("write tree")?;
    if tree_id == parent_tree.id() {
        return Ok(None);
    }
    let tree = repo.find_tree(tree_id).context("find tree")?;
    let sig = signature(repo)?;
    let oid = repo
        .commit(
            Some(&format!("refs/heads/{branch}")),
            &sig,
            &sig,
            message,
            &tree,
            &[parent],
        )
        .context("git commit")?;
    Ok(Some(oid))
}

fn workdir_rel(workdir: &Path, path: &Path) -> Result<PathBuf> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        workdir.join(path)
    };
    let normalized: PathBuf = absolute
        .components()
        .filter(|component| !matches!(component, std::path::Component::CurDir))
        .collect();
    normalized
        .strip_prefix(workdir)
        .with_context(|| format!("path outside workdir: {}", normalized.display()))
        .map(Path::to_path_buf)
}

fn signature(repo: &Repository) -> Result<Signature<'static>> {
    if let Ok(sig) = repo.signature() {
        return Signature::now(
            sig.name().unwrap_or("verctl"),
            sig.email().unwrap_or("verctl@users.noreply.github.com"),
        )
        .context("commit signature");
    }
    let name = env::var("GIT_AUTHOR_NAME")
        .or_else(|_| env::var("GITHUB_ACTOR"))
        .unwrap_or_else(|_| "verctl".into());
    let email =
        env::var("GIT_AUTHOR_EMAIL").unwrap_or_else(|_| format!("{name}@users.noreply.github.com"));
    Signature::now(&name, &email).context("commit signature")
}

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

    use git2::{Repository, Signature};
    use indoc::indoc;

    use super::{AddedBy, added_by, origin_url};

    fn commit_all(repo: &Repository, subject: &str) -> git2::Oid {
        let sig = Signature::now("t", "t@example.com").unwrap();
        let mut index = repo.index().unwrap();
        index
            .add_all(["."].iter(), git2::IndexAddOption::DEFAULT, None)
            .unwrap();
        index.write().unwrap();
        let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
        let parent = repo.head().ok().and_then(|head| head.peel_to_commit().ok());
        let parents: Vec<&git2::Commit<'_>> = parent.iter().collect();
        repo.commit(Some("HEAD"), &sig, &sig, subject, &tree, &parents)
            .unwrap()
    }

    #[test]
    fn added_by_names_the_commit_that_added_the_file() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        std::fs::write(dir.path().join("README"), "start\n").unwrap();
        commit_all(&repo, "chore: start");
        std::fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
        let added = commit_all(&repo, "fix: the parser (#12)");
        std::fs::write(dir.path().join("README"), "later\n").unwrap();
        commit_all(&repo, "docs: later");
        assert_eq!(
            added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
            Some(AddedBy {
                sha: added.to_string(),
                subject: "fix: the parser (#12)".into(),
            })
        );
    }

    /// A fragment that reached HEAD through a merge commit names the commit
    /// that added it on the merged branch, not the merge.
    #[test]
    fn added_by_follows_a_merge_to_the_commit_that_added_the_file() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        std::fs::write(dir.path().join("README"), "start\n").unwrap();
        let base = commit_all(&repo, "chore: start");
        std::fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
        let side = commit_all(&repo, "fix: the parser (#12)");
        repo.reset(
            &repo.find_object(base, None).unwrap(),
            git2::ResetType::Hard,
            None,
        )
        .unwrap();
        std::fs::write(dir.path().join("README"), "later\n").unwrap();
        let main = commit_all(&repo, "docs: later (#13)");
        std::fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
        let mut index = repo.index().unwrap();
        index
            .add_all(["."].iter(), git2::IndexAddOption::DEFAULT, None)
            .unwrap();
        let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        repo.commit(
            Some("HEAD"),
            &sig,
            &sig,
            "feat: release next (#14)",
            &tree,
            &[
                &repo.find_commit(main).unwrap(),
                &repo.find_commit(side).unwrap(),
            ],
        )
        .unwrap();
        assert_eq!(
            added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
            Some(AddedBy {
                sha: side.to_string(),
                subject: "fix: the parser (#12)".into(),
            })
        );
    }

    /// A merge titled with its pull request is named when the branch commit
    /// that added the file names none: merge-commit repositories keep their
    /// pull request links.
    #[test]
    fn added_by_names_a_titled_merge_over_an_unnamed_branch_commit() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        std::fs::write(dir.path().join("README"), "start\n").unwrap();
        let base = commit_all(&repo, "chore: start");
        std::fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
        let side = commit_all(&repo, "wip");
        repo.reset(
            &repo.find_object(base, None).unwrap(),
            git2::ResetType::Hard,
            None,
        )
        .unwrap();
        std::fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
        let mut index = repo.index().unwrap();
        index
            .add_all(["."].iter(), git2::IndexAddOption::DEFAULT, None)
            .unwrap();
        let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        let merge = repo
            .commit(
                Some("HEAD"),
                &sig,
                &sig,
                "fix: the parser (#12)",
                &tree,
                &[
                    &repo.find_commit(base).unwrap(),
                    &repo.find_commit(side).unwrap(),
                ],
            )
            .unwrap();
        assert_eq!(
            added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
            Some(AddedBy {
                sha: merge.to_string(),
                subject: "fix: the parser (#12)".into(),
            })
        );
    }

    /// A shallow clone ends at a commit libgit2 reports as parentless. When the
    /// adding commit lies beyond it, naming the boundary would be wrong.
    #[test]
    fn added_by_names_nothing_past_a_shallow_boundary() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        std::fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
        commit_all(&repo, "fix: the parser (#12)");
        std::fs::write(dir.path().join("README"), "later\n").unwrap();
        let boundary = commit_all(&repo, "docs: later (#13)");
        std::fs::write(repo.path().join("shallow"), format!("{boundary}\n")).unwrap();
        let shallow = Repository::open(dir.path()).unwrap();
        assert!(shallow.is_shallow());
        assert_eq!(
            added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
            None
        );
    }

    #[test]
    fn origin_url_from_discovered_repo() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        repo.remote(
            "origin",
            "https://github.com/victor-software-house/verctl.git",
        )
        .unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        {
            let mut index = repo.index().unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        assert_eq!(
            origin_url(dir.path()).unwrap(),
            "https://github.com/victor-software-house/verctl.git"
        );
    }

    #[test]
    fn empty_paths_do_not_switch_head() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        {
            let mut index = repo.index().unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        let before = repo.head().unwrap().name().unwrap().to_owned();
        let repo_id = crate::github::Repo {
            owner: "victor-software-house".into(),
            name: "verctl".into(),
        };
        let out = super::commit_branch_and_push(
            dir.path(),
            "version-packages",
            "chore",
            "unused",
            &repo_id,
            &[],
        )
        .unwrap();
        assert_eq!(out, super::PushOutcome::Empty);
        assert_eq!(repo.head().unwrap().name().unwrap(), before);
    }

    #[test]
    fn unexpected_dirty_fails_unless_globbed() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.0"
            "#},
        )
        .unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new("Cargo.toml")).unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        std::fs::write(dir.path().join("secret.env"), "TOKEN=leak\n").unwrap();
        let allowed = [dir.path().join("Cargo.toml")];
        let err = super::assert_only_allowed(dir.path(), &allowed, &[], false).unwrap_err();
        assert!(format!("{err:#}").contains("secret.env"), "{err:#}");
        let staged =
            super::assert_only_allowed(dir.path(), &allowed, &["*.env".into()], false).unwrap();
        assert_eq!(staged.len(), 1);
        assert!(staged[0].ends_with("secret.env"), "{staged:?}");
    }

    #[test]
    fn stage_glob_collects_a_deleted_file() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        std::fs::write(dir.path().join("Cargo.lock"), "old\n").unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.0"
            "#},
        )
        .unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new("Cargo.toml")).unwrap();
            index.add_path(Path::new("Cargo.lock")).unwrap();
            index.write().unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        std::fs::remove_file(dir.path().join("Cargo.lock")).unwrap();
        let staged = super::assert_only_allowed(
            dir.path(),
            &[dir.path().join("Cargo.toml")],
            &["Cargo.lock".into()],
            false,
        )
        .unwrap();
        assert_eq!(staged.len(), 1);
        assert!(staged[0].ends_with("Cargo.lock"), "{staged:?}");
        assert!(!dir.path().join("Cargo.lock").exists());
    }

    #[test]
    fn stage_glob_collects_files_under_a_tree_not_the_directory() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.0"
            "#},
        )
        .unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new("Cargo.toml")).unwrap();
            index.write().unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        std::fs::write(dir.path().join("src/lib.rs"), "fn x() {}\n").unwrap();
        let staged = super::assert_only_allowed(
            dir.path(),
            &[dir.path().join("Cargo.toml")],
            &["src/**".into()],
            false,
        )
        .unwrap();
        assert_eq!(staged.len(), 1);
        assert!(staged[0].ends_with("src/lib.rs"), "{staged:?}");
        assert!(!staged.iter().any(|path| path.ends_with("src")));
    }

    #[test]
    fn ignored_workdir_paths_are_not_unexpected() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        std::fs::write(dir.path().join(".gitignore"), "/target\n").unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.0"
            "#},
        )
        .unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new(".gitignore")).unwrap();
            index.add_path(Path::new("Cargo.toml")).unwrap();
            index.write().unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        std::fs::create_dir_all(dir.path().join("target/debug")).unwrap();
        std::fs::write(dir.path().join("target/debug/verctl"), "bin\n").unwrap();
        super::assert_only_allowed(dir.path(), &[dir.path().join("Cargo.toml")], &[], false)
            .unwrap();
    }

    #[test]
    fn stage_ignored_opt_in_collects_gitignored_files() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        std::fs::write(dir.path().join(".gitignore"), "/generated.rs\n").unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.0"
            "#},
        )
        .unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new(".gitignore")).unwrap();
            index.add_path(Path::new("Cargo.toml")).unwrap();
            index.write().unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        std::fs::write(dir.path().join("generated.rs"), "gen\n").unwrap();
        let allowed = [dir.path().join("Cargo.toml")];
        let off = super::assert_only_allowed(dir.path(), &allowed, &["generated.rs".into()], false)
            .unwrap();
        assert!(off.is_empty(), "{off:?}");
        let on = super::assert_only_allowed(dir.path(), &allowed, &["generated.rs".into()], true)
            .unwrap();
        assert_eq!(on.len(), 1);
        assert!(on[0].ends_with("generated.rs"), "{on:?}");
    }

    #[test]
    fn stage_ignored_recurses_a_gitignored_directory() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        std::fs::write(dir.path().join(".gitignore"), "/dist\n").unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.0"
            "#},
        )
        .unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new(".gitignore")).unwrap();
            index.add_path(Path::new("Cargo.toml")).unwrap();
            index.write().unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        std::fs::create_dir_all(dir.path().join("dist")).unwrap();
        std::fs::write(dir.path().join("dist/out.js"), "ok\n").unwrap();
        let allowed = [dir.path().join("Cargo.toml")];
        let staged =
            super::assert_only_allowed(dir.path(), &allowed, &["dist/**".into()], true).unwrap();
        assert_eq!(staged.len(), 1);
        assert!(staged[0].ends_with("dist/out.js"), "{staged:?}");
    }

    #[test]
    fn stage_ignored_pathspec_does_not_collect_other_ignored_trees() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        std::fs::write(dir.path().join(".gitignore"), "/dist\n/target\n").unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.0"
            "#},
        )
        .unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new(".gitignore")).unwrap();
            index.add_path(Path::new("Cargo.toml")).unwrap();
            index.write().unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        std::fs::create_dir_all(dir.path().join("dist")).unwrap();
        std::fs::write(dir.path().join("dist/out.js"), "ok\n").unwrap();
        std::fs::create_dir_all(dir.path().join("target/debug")).unwrap();
        std::fs::write(dir.path().join("target/debug/verctl"), "bin\n").unwrap();
        std::fs::write(dir.path().join("target/CACHEDIR.TAG"), "tag\n").unwrap();
        let staged = super::assert_only_allowed(
            dir.path(),
            &[dir.path().join("Cargo.toml")],
            &["dist/**".into()],
            true,
        )
        .unwrap();
        assert_eq!(staged.len(), 1, "{staged:?}");
        assert!(staged[0].ends_with("dist/out.js"), "{staged:?}");
        assert!(
            !staged
                .iter()
                .any(|path| path.to_string_lossy().contains("target")),
            "{staged:?}"
        );
    }

    #[test]
    fn write_commit_on_branch_removes_a_deleted_staged_path() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        std::fs::write(dir.path().join("Cargo.lock"), "old\n").unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.0"
            "#},
        )
        .unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new("Cargo.toml")).unwrap();
            index.add_path(Path::new("Cargo.lock")).unwrap();
            index.write().unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        std::fs::remove_file(dir.path().join("Cargo.lock")).unwrap();
        let parent = repo.head().unwrap().peel_to_commit().unwrap();
        let workdir = repo.workdir().unwrap().to_path_buf();
        let staged = super::assert_only_allowed(
            dir.path(),
            &[dir.path().join("Cargo.toml")],
            &["Cargo.lock".into()],
            false,
        )
        .unwrap();
        let oid = super::write_commit_on_branch(
            &repo,
            &workdir,
            &parent,
            "version-packages",
            "chore",
            &staged,
        )
        .unwrap()
        .expect("deletion should commit");
        let tree = repo.find_commit(oid).unwrap().tree().unwrap();
        assert!(tree.get_name("Cargo.lock").is_none());
        assert!(tree.get_name("Cargo.toml").is_some());
    }

    #[test]
    fn commit_only_lists_given_paths() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.0"
            "#},
        )
        .unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new("Cargo.toml")).unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.1"
            "#},
        )
        .unwrap();
        std::fs::write(
            dir.path().join("secret.env"),
            indoc! {"
                TOKEN=leak
            "},
        )
        .unwrap();
        let parent = repo.head().unwrap().peel_to_commit().unwrap();
        let oid = super::write_commit_on_branch(
            &repo,
            dir.path(),
            &parent,
            "version-packages",
            "chore",
            &[dir.path().join("Cargo.toml")],
        )
        .unwrap()
        .expect("commit");
        let tree = repo.find_commit(oid).unwrap().tree().unwrap();
        assert!(tree.get_name("Cargo.toml").is_some());
        assert!(tree.get_name("secret.env").is_none());
        assert_eq!(
            repo.head().unwrap().peel_to_commit().unwrap().id(),
            parent.id()
        );
    }

    #[test]
    fn dotted_relative_paths_stage() {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let sig = Signature::now("t", "t@example.com").unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.0"
            "#},
        )
        .unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new("Cargo.toml")).unwrap();
            let tid = index.write_tree().unwrap();
            let tree = repo.find_tree(tid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
                .unwrap();
        }
        std::fs::write(
            dir.path().join("Cargo.toml"),
            indoc! {r#"
                [package]
                version = "1.0.1"
            "#},
        )
        .unwrap();
        let parent = repo.head().unwrap().peel_to_commit().unwrap();
        let oid = super::write_commit_on_branch(
            &repo,
            dir.path(),
            &parent,
            "version-packages",
            "chore",
            &[Path::new("./Cargo.toml").to_path_buf()],
        )
        .unwrap()
        .expect("commit");
        assert!(
            repo.find_commit(oid)
                .unwrap()
                .tree()
                .unwrap()
                .get_name("Cargo.toml")
                .is_some()
        );
    }

    fn commit_tree(repo: &Repository, message: &str) -> git2::Oid {
        let sig = Signature::now("t", "t@example.com").unwrap();
        let mut index = repo.index().unwrap();
        let tid = index.write_tree().unwrap();
        let tree = repo.find_tree(tid).unwrap();
        let parent = repo.head().ok().and_then(|head| head.peel_to_commit().ok());
        let parents: Vec<&git2::Commit<'_>> = parent.as_ref().into_iter().collect();
        repo.commit(Some("HEAD"), &sig, &sig, message, &tree, &parents)
            .unwrap()
    }

    fn stock() -> Vec<String> {
        super::candidate_names(None)
    }

    fn fixture() -> (tempfile::TempDir, Repository, git2::Oid) {
        let dir = tempfile::TempDir::new().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        let oid = commit_tree(&repo, "init");
        (dir, repo, oid)
    }

    fn add_origin(repo: &Repository) {
        repo.remote(
            "origin",
            "https://github.com/victor-software-house/verctl.git",
        )
        .unwrap();
    }

    fn track(repo: &Repository, name: &str, oid: git2::Oid) {
        repo.reference(&format!("refs/remotes/origin/{name}"), oid, true, "test")
            .unwrap();
    }

    fn set_origin_head(repo: &Repository, name: &str) {
        repo.reference_symbolic(
            "refs/remotes/origin/HEAD",
            &format!("refs/remotes/origin/{name}"),
            true,
            "test",
        )
        .unwrap();
    }

    fn prove(root: &std::path::Path, candidates: &[String]) -> anyhow::Result<()> {
        super::prove_default_history(root, candidates)
    }

    #[test]
    fn candidate_names_are_base_ref_then_main_master() {
        assert_eq!(super::candidate_names(None), ["main", "master"]);
        assert_eq!(super::candidate_names(Some("")), ["main", "master"]);
        assert_eq!(super::candidate_names(Some("   ")), ["main", "master"]);
        assert_eq!(
            super::candidate_names(Some("trunk")),
            ["trunk", "main", "master"]
        );
        assert_eq!(super::candidate_names(Some("main")), ["main", "master"]);
        assert_eq!(
            super::candidate_names(Some("release/1.0")),
            ["release/1.0", "main", "master"]
        );
    }

    #[test]
    fn no_repository_skips() {
        let dir = tempfile::TempDir::new().unwrap();
        prove(dir.path(), &stock()).unwrap();
    }

    #[test]
    fn default_history_skips_when_origin_is_missing() {
        let (dir, _, _) = fixture();
        prove(dir.path(), &stock()).unwrap();
    }

    #[test]
    fn head_on_origin_main_is_ok() {
        let (dir, repo, oid) = fixture();
        add_origin(&repo);
        track(&repo, "main", oid);
        prove(dir.path(), &stock()).unwrap();
    }

    #[test]
    fn head_sha_is_the_peeled_head_commit() {
        let (dir, _, oid) = fixture();
        assert_eq!(super::head_sha(dir.path()).unwrap(), oid.to_string());
    }

    #[test]
    fn origin_master_without_head_is_ok() {
        let (dir, repo, oid) = fixture();
        add_origin(&repo);
        track(&repo, "master", oid);
        prove(dir.path(), &stock()).unwrap();
    }

    #[test]
    fn origin_head_to_non_main_is_ok() {
        let (dir, repo, oid) = fixture();
        add_origin(&repo);
        track(&repo, "trunk", oid);
        set_origin_head(&repo, "trunk");
        prove(dir.path(), &stock()).unwrap();
    }

    #[test]
    fn base_ref_trunk_without_origin_head_is_ok() {
        let (dir, repo, oid) = fixture();
        add_origin(&repo);
        track(&repo, "trunk", oid);
        prove(dir.path(), &super::candidate_names(Some("trunk"))).unwrap();
    }

    #[test]
    fn origin_without_default_tracking_ref_fails() {
        let (dir, repo, _) = fixture();
        add_origin(&repo);
        let err = prove(dir.path(), &stock()).unwrap_err();
        assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
    }

    #[test]
    fn origin_trunk_alone_needs_head_or_base_ref() {
        let (dir, repo, oid) = fixture();
        add_origin(&repo);
        track(&repo, "trunk", oid);
        let err = prove(dir.path(), &stock()).unwrap_err();
        assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
        prove(dir.path(), &super::candidate_names(Some("trunk"))).unwrap();
        set_origin_head(&repo, "trunk");
        prove(dir.path(), &stock()).unwrap();
    }

    #[test]
    fn origin_hotfix_alone_is_not_the_default() {
        let (dir, repo, oid) = fixture();
        add_origin(&repo);
        track(&repo, "hotfix", oid);
        let err = prove(dir.path(), &stock()).unwrap_err();
        assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
    }

    #[test]
    fn unpeelable_origin_head_does_not_fall_through_to_main() {
        let (dir, repo, oid) = fixture();
        add_origin(&repo);
        track(&repo, "main", oid);
        set_origin_head(&repo, "trunk");
        let err = prove(dir.path(), &stock()).unwrap_err();
        assert!(format!("{err:#}").contains("origin/trunk"), "{err:#}");
    }

    #[test]
    fn github_https_url_has_no_credentials() {
        let url = super::github_https_url("victor-software-house/qctl");
        assert_eq!(url, "https://github.com/victor-software-house/qctl.git");
        let lower = url.to_ascii_lowercase();
        assert!(!lower.contains("bearer"), "{url}");
        assert!(!lower.contains("token"), "{url}");
        assert!(!lower.contains("x-access-token"), "{url}");
    }

    #[test]
    fn github_git_user_is_x_access_token() {
        assert_eq!(super::github_git_user(), "x-access-token");
    }

    #[test]
    fn ensure_origin_head_skips_fetch_when_the_ref_exists() {
        let (dir, repo, oid) = fixture();
        repo.remote("origin", "https://127.0.0.1:1/nope.git")
            .unwrap();
        track(&repo, "main", oid);
        super::ensure_origin_head(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
        let head = repo.find_reference("refs/remotes/origin/HEAD").unwrap();
        assert_eq!(
            head.symbolic_target().unwrap(),
            Some("refs/remotes/origin/main")
        );
    }

    #[test]
    fn ensure_origin_head_fetches_a_missing_ref_from_origin() {
        let mut opts = git2::RepositoryInitOptions::new();
        opts.initial_head("main");

        let upstream_dir = tempfile::TempDir::new().unwrap();
        let upstream = git2::Repository::init_opts(upstream_dir.path(), &opts).unwrap();
        commit_tree(&upstream, "init");

        let work_dir = tempfile::TempDir::new().unwrap();
        let work = git2::Repository::init_opts(work_dir.path(), &opts).unwrap();
        commit_tree(&work, "local");
        let url = format!("file://{}", upstream_dir.path().display());
        work.remote("origin", &url).unwrap();

        super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
        assert!(
            work.find_reference("refs/remotes/origin/main")
                .unwrap()
                .peel_to_commit()
                .is_ok()
        );
        let head = work.find_reference("refs/remotes/origin/HEAD").unwrap();
        assert_eq!(
            head.symbolic_target().unwrap(),
            Some("refs/remotes/origin/main")
        );
    }

    #[test]
    fn fetch_one_branch_does_not_set_depth() {
        let src = include_str!("git.rs");
        let prod = src.split("#[cfg(test)]").next().expect("production");
        assert!(
            !prod.contains("opts.depth"),
            "a depth-limited fetch leaves the tip parentless so graph_descendant_of cannot prove ancestry"
        );
    }

    #[test]
    fn configured_default_branch_is_only_verctl_default_branch() {
        let src = include_str!("git.rs");
        let start = src
            .find("pub fn configured_default_branch")
            .expect("configured_default_branch");
        let rest = &src[start..];
        let end = rest
            .find("pub fn ensure_origin_head")
            .expect("ensure_origin_head");
        let body = &rest[..end];
        assert!(!body.contains("GITHUB_BASE_REF"), "{body}");
        assert!(!body.contains("env_base_ref"), "{body}");
    }

    #[test]
    fn fetched_default_branch_keeps_parents_for_ancestry() {
        let mut opts = git2::RepositoryInitOptions::new();
        opts.initial_head("main");

        let upstream_dir = tempfile::TempDir::new().unwrap();
        let upstream = git2::Repository::init_opts(upstream_dir.path(), &opts).unwrap();
        commit_tree(&upstream, "A");

        let work_dir = tempfile::TempDir::new().unwrap();
        let work = git2::Repository::init_opts(work_dir.path(), &opts).unwrap();
        let url = format!("file://{}", upstream_dir.path().display());
        work.remote("origin", &url).unwrap();
        super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
        let first = work
            .find_reference("refs/remotes/origin/main")
            .unwrap()
            .peel_to_commit()
            .unwrap()
            .id();
        work.set_head_detached(first).unwrap();

        std::fs::write(upstream_dir.path().join("b.txt"), "b\n").unwrap();
        {
            let mut index = upstream.index().unwrap();
            index.add_path(Path::new("b.txt")).unwrap();
            index.write().unwrap();
        }
        commit_tree(&upstream, "B");
        std::fs::write(upstream_dir.path().join("c.txt"), "c\n").unwrap();
        {
            let mut index = upstream.index().unwrap();
            index.add_path(Path::new("c.txt")).unwrap();
            index.write().unwrap();
        }
        commit_tree(&upstream, "C");

        work.find_reference("refs/remotes/origin/main")
            .unwrap()
            .delete()
            .unwrap();
        work.find_reference("refs/remotes/origin/HEAD")
            .unwrap()
            .delete()
            .unwrap();
        super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
        prove(work_dir.path(), &stock()).unwrap();
    }

    #[test]
    fn origin_head_wins_over_main_when_they_differ() {
        let (dir, repo, first) = fixture();
        add_origin(&repo);
        std::fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new("extra.txt")).unwrap();
            index.write().unwrap();
        }
        let second = commit_tree(&repo, "ahead");
        track(&repo, "main", first);
        track(&repo, "trunk", second);
        set_origin_head(&repo, "trunk");
        prove(dir.path(), &stock()).unwrap();
    }

    #[test]
    fn head_off_default_history_fails() {
        let (dir, repo, first) = fixture();
        add_origin(&repo);
        track(&repo, "main", first);
        repo.reference("refs/heads/other", first, true, "branch")
            .unwrap();
        repo.set_head("refs/heads/other").unwrap();
        std::fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new("extra.txt")).unwrap();
            index.write().unwrap();
        }
        commit_tree(&repo, "ahead");
        let err = prove(dir.path(), &stock()).unwrap_err();
        assert!(format!("{err:#}").contains("not an ancestor"), "{err:#}");
    }

    #[test]
    fn head_behind_origin_main_is_ok() {
        let (dir, repo, first) = fixture();
        add_origin(&repo);
        std::fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
        {
            let mut index = repo.index().unwrap();
            index.add_path(Path::new("extra.txt")).unwrap();
            index.write().unwrap();
        }
        let second = commit_tree(&repo, "ahead");
        track(&repo, "main", second);
        repo.set_head_detached(first).unwrap();
        prove(dir.path(), &stock()).unwrap();
    }
}