mise 2026.9.4

Dev tools, env vars, and tasks in one CLI
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
use std::collections::{BTreeSet, HashMap};
use std::ffi::OsStr;
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};

use duct::Expression;
use eyre::{Result, WrapErr, eyre};
use gix::{self};
use once_cell::sync::OnceCell;
use xx::file;

use crate::cmd::CmdLineRunner;
use crate::config::Settings;
use crate::file::touch_dir;
use crate::ui::progress_report::SingleReport;

use std::ffi::OsString;

pub(crate) struct Git {
    pub dir: PathBuf,
    pub repo: OnceCell<gix::Repository>,
}

macro_rules! git_cmd {
    ( $dir:expr $(, $arg:expr )* $(,)? ) => {
        {
            let safe = format!("safe.directory={}", $dir.display());
            sanitize_git_env(cmd!("git", "-c", $crate::git::github_credential_config("github.com"), "-c", $crate::git::github_credential_config("github.com:443"), "-C", $dir, "-c", safe, "-c", "core.autocrlf=false" $(, $arg)*))
        }
    }
}

macro_rules! git_cmd_read {
    ( $dir:expr $(, $arg:expr )* $(,)? ) => {
        {
            git_cmd!($dir $(, $arg)*).read().wrap_err_with(|| {
                let args = [$($arg,)*].join(" ");
                format!("git {args} failed")
            })
        }
    }
}

impl Git {
    pub(crate) fn new<P: AsRef<Path>>(dir: P) -> Self {
        Self {
            dir: dir.as_ref().to_path_buf(),
            repo: OnceCell::new(),
        }
    }

    pub(crate) fn repo(&self) -> Result<&gix::Repository> {
        self.repo.get_or_try_init(|| {
            trace!("opening git repository via gix at {:?}", self.dir);
            gix::open(&self.dir)
                .wrap_err_with(|| format!("failed to open git repository at {:?}", self.dir))
                .inspect_err(|err| warn!("{err:#}"))
        })
    }

    pub(crate) fn is_repo(&self) -> bool {
        self.dir.join(".git").is_dir()
    }

    pub(crate) fn update(&self, gitref: Option<String>) -> Result<(String, String)> {
        match gitref {
            Some(gitref) => {
                let remote_ref_kind = self.remote_ref_kind(&gitref)?;
                self.update_ref(gitref, remote_ref_kind)
            }
            None => self.update_ref(self.current_branch()?, None),
        }
    }

    pub(crate) fn update_tag(&self, gitref: String) -> Result<(String, String)> {
        self.update_ref(gitref, Some(RemoteRefKind::Tag))
    }

    fn remote_ref_kind(&self, gitref: &str) -> Result<Option<RemoteRefKind>> {
        if gitref.starts_with("refs/") || looks_like_sha(gitref) {
            return Ok(None);
        }

        let branch_ref = format!("refs/heads/{gitref}");
        let tag_ref = format!("refs/tags/{gitref}");
        let output = git_cmd_read!(
            &self.dir,
            "ls-remote",
            "--refs",
            "origin",
            &branch_ref,
            &tag_ref
        )?;

        // Match git's usual disambiguation: a same-named branch wins over a
        // tag, while callers can select the tag with `refs/tags/<name>`.
        Ok(remote_ref_kind(&output, &branch_ref, &tag_ref))
    }

    /// Detached `git checkout --force <ref>` with no fetch. Used after `clone`
    /// when the caller asked to land on a specific SHA — the clone has already
    /// pulled all reachable objects, so a fetch with a `<sha>:<sha>` refspec
    /// would be redundant (and on servers without
    /// `uploadpack.allowReachableSHA1InWant`, would fail).
    fn checkout(&self, gitref: &str) -> Result<()> {
        let cmd = git_cmd!(
            &self.dir,
            "-c",
            "advice.detachedHead=false",
            "-c",
            "advice.objectNameWarning=false",
            "checkout",
            "--force",
            gitref,
        );
        let res = cmd
            .stderr_to_stdout()
            .stdout_capture()
            .unchecked()
            .run()
            .map_err(|err| eyre!("git failed: {cmd:?} {err:#}"))?;
        if !res.status.success() {
            return Err(eyre!(
                "git failed: {cmd:?} {}",
                String::from_utf8_lossy(&res.stdout)
            ));
        }
        touch_dir(&self.dir)?;
        Ok(())
    }

    fn update_ref(
        &self,
        gitref: String,
        remote_ref_kind: Option<RemoteRefKind>,
    ) -> Result<(String, String)> {
        debug!("updating {} to {}", self.dir.display(), gitref);
        let exec = |cmd: Expression| match cmd.stderr_to_stdout().stdout_capture().unchecked().run()
        {
            Ok(res) => {
                if res.status.success() {
                    Ok(())
                } else {
                    Err(eyre!(
                        "git failed: {cmd:?} {}",
                        String::from_utf8(res.stdout).unwrap()
                    ))
                }
            }
            Err(err) => Err(eyre!("git failed: {cmd:?} {err:#}")),
        };
        debug!("updating {} to {} with git", self.dir.display(), gitref);

        let qualified_ref = remote_ref_kind.map(|kind| qualify_remote_ref(&gitref, kind));
        let refspec = qualified_ref
            .as_ref()
            .map_or_else(|| format!("{gitref}:{gitref}"), |r| format!("{r}:{r}"));
        exec(git_cmd!(
            &self.dir,
            "fetch",
            "--prune",
            "--update-head-ok",
            "origin",
            &refspec
        ))?;
        let prev_rev = self.current_sha()?;
        let checkout_ref = match (remote_ref_kind, qualified_ref.as_deref()) {
            (Some(RemoteRefKind::Tag), Some(tag_ref)) => tag_ref,
            _ => &gitref,
        };
        exec(git_cmd!(
            &self.dir,
            "-c",
            "advice.detachedHead=false",
            "-c",
            "advice.objectNameWarning=false",
            "checkout",
            "--force",
            &checkout_ref
        ))?;
        let post_rev = self.current_sha()?;
        touch_dir(&self.dir)?;

        Ok((prev_rev, post_rev))
    }

    pub(crate) fn clone(&self, url: &str, options: CloneOptions) -> Result<()> {
        if let Some(parent) = self.dir.parent() {
            file::mkdirp(parent)?;
        }
        // gix's `with_ref_name` and git CLI's `-b` only accept branch/tag names.
        // If the caller passed a commit SHA, clone without a ref and then
        // check out the SHA explicitly. gix in particular panics
        // ("we map by name only and have no object-id in refspec") if a SHA
        // is fed to `with_ref_name`.
        let sha_branch = options.branch.as_deref().filter(|b| looks_like_sha(b));
        let revision = options.revision.as_deref().or(sha_branch);
        let named_branch = options
            .branch
            .as_deref()
            .filter(|b| !looks_like_sha(b) && revision.is_none());
        if (Settings::get().libgit2 || Settings::get().gix)
            && std::env::var_os("MISE_GITHUB_RELAY_SOCKET").is_none()
        {
            debug!("cloning {} to {} with gix", url, self.dir.display());
            let mut prepare_clone = gix::prepare_clone(url, &self.dir)?
                .with_in_memory_config_overrides([
                    github_credential_config("github.com"),
                    github_credential_config("github.com:443"),
                ]);

            if let Some(branch) = named_branch {
                prepare_clone = prepare_clone.with_ref_name(Some(branch))?;
            }

            let (mut prepare_checkout, _) = prepare_clone
                .fetch_then_checkout(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)?;

            prepare_checkout
                .main_worktree(gix::progress::Discard, &gix::interrupt::IS_INTERRUPTED)?;

            if let Some(revision) = revision {
                self.checkout(revision)?;
            }
            return Ok(());
        }
        debug!("cloning {} to {} with git", url, self.dir.display());
        match get_git_version() {
            Ok(version) => trace!("git version: {}", version),
            Err(err) => warn!(
                "failed to get git version: {:#}\n Git is required to use mise.",
                err
            ),
        }
        if let Some(pr) = &options.pr {
            // in order to prevent hiding potential password prompt, just disable the progress bar
            pr.abandon();
        }

        let mut cmd = sanitize_git_cmd_runner(
            CmdLineRunner::new("git")
                .arg("-c")
                .arg(github_credential_config("github.com"))
                .arg("-c")
                .arg(github_credential_config("github.com:443"))
                .arg("clone")
                .arg("-q")
                .arg("-o")
                .arg("origin")
                .arg("-c")
                .arg("core.autocrlf=false"),
        );
        // `--depth 1` is incompatible with checking out an arbitrary revision
        // later, so do a full clone when the caller supplied one.
        if revision.is_none() {
            cmd = cmd.arg("--depth").arg("1");
        }
        cmd = cmd.arg(url).arg(&self.dir);

        if let Some(branch) = named_branch {
            cmd = cmd.args([
                "-b",
                branch,
                "--single-branch",
                "-c",
                "advice.detachedHead=false",
            ]);
        }

        cmd.execute()?;

        if let Some(revision) = revision {
            self.checkout(revision)?;
        }
        Ok(())
    }

    pub(crate) fn update_submodules(&self) -> Result<()> {
        debug!("updating submodules in {}", self.dir.display());

        let exec = |cmd: Expression| match cmd.stderr_to_stdout().stdout_capture().unchecked().run()
        {
            Ok(res) => {
                if res.status.success() {
                    Ok(())
                } else {
                    Err(eyre!(
                        "git failed: {cmd:?} {}",
                        String::from_utf8(res.stdout).unwrap()
                    ))
                }
            }
            Err(err) => Err(eyre!("git failed: {cmd:?} {err:#}")),
        };

        exec(
            git_cmd!(&self.dir, "submodule", "update", "--init", "--recursive")
                .env("GIT_TERMINAL_PROMPT", "0"),
        )?;

        Ok(())
    }

    pub(crate) fn current_branch(&self) -> Result<String> {
        let dir = &self.dir;
        if let Ok(repo) = self.repo() {
            let head = repo.head()?;
            let branch = head
                .referent_name()
                .map(|name| name.shorten().to_string())
                .unwrap_or_else(|| head.id().unwrap().to_string());
            debug!("current branch for {dir:?}: {branch}");
            return Ok(branch);
        }
        let branch = git_cmd_read!(&self.dir, "branch", "--show-current")?;
        debug!("current branch for {}: {}", self.dir.display(), &branch);
        Ok(branch)
    }
    pub(crate) fn current_sha(&self) -> Result<String> {
        let dir = &self.dir;
        if let Ok(repo) = self.repo() {
            let head = repo.head()?;
            let sha = head
                .id()
                .ok_or_else(|| eyre::eyre!("repository {} has no commit at HEAD", dir.display()))?
                .to_string();
            debug!("current sha for {dir:?}: {sha}");
            return Ok(sha);
        }
        let sha = git_cmd_read!(&self.dir, "rev-parse", "HEAD")?;
        debug!("current sha for {}: {}", self.dir.display(), &sha);
        Ok(sha)
    }

    pub(crate) fn current_sha_short(&self) -> Result<String> {
        let dir = &self.dir;
        if let Ok(repo) = self.repo() {
            let head = repo.head()?;
            let id = head.id();
            let sha = id.unwrap().to_string()[..7].to_string();
            debug!("current sha for {dir:?}: {sha}");
            return Ok(sha);
        }
        let sha = git_cmd_read!(&self.dir, "rev-parse", "--short", "HEAD")?;
        debug!("current sha for {dir:?}: {sha}");
        Ok(sha)
    }

    pub(crate) fn current_abbrev_ref(&self) -> Result<String> {
        let dir = &self.dir;
        if let Ok(repo) = self.repo() {
            let head = repo.head()?;
            let head = head.name().shorten().to_string();
            debug!("current abbrev ref for {dir:?}: {head}");
            return Ok(head);
        }
        let aref = git_cmd_read!(&self.dir, "rev-parse", "--abbrev-ref", "HEAD")?;
        debug!("current abbrev ref for {}: {}", self.dir.display(), &aref);
        Ok(aref)
    }

    pub(crate) fn get_remote_url(&self) -> Option<String> {
        let dir = &self.dir;
        if !self.exists() {
            return None;
        }
        if let Ok(repo) = self.repo()
            && let Ok(remote) = repo.find_remote("origin")
            && let Some(url) = remote.url(gix::remote::Direction::Fetch)
        {
            trace!("remote url for {dir:?}: {url}");
            return Some(url.to_string());
        }
        let res = git_cmd_read!(&self.dir, "config", "--get", "remote.origin.url");
        match res {
            Ok(url) => {
                debug!("remote url for {dir:?}: {url}");
                Some(url)
            }
            Err(err) => {
                warn!("failed to get remote url for {dir:?}: {err:#}");
                None
            }
        }
    }

    pub(crate) fn split_url_and_ref(url: &str) -> (String, Option<String>) {
        match url.split_once('#') {
            Some((url, _ref)) => (url.to_string(), Some(_ref.to_string())),
            None => (url.to_string(), None),
        }
    }

    pub(crate) fn remote_sha(&self, branch: &str) -> Result<Option<String>> {
        let output = git_cmd_read!(&self.dir, "ls-remote", "origin", branch)?;
        Ok(output
            .lines()
            .next()
            .and_then(|line| line.split_whitespace().next())
            .map(|sha| sha.to_string()))
    }

    pub(crate) fn exists(&self) -> bool {
        self.dir.join(".git").is_dir()
    }

    pub(crate) fn get_root() -> eyre::Result<PathBuf> {
        Ok(cmd!("git", "rev-parse", "--show-toplevel")
            .read()?
            .trim()
            .into())
    }

    /// Returns paths changed between the merge base of two revisions.
    ///
    /// Rename detection is disabled so moves report both the old and new path.
    /// Paths are relative to `self.dir`, and changes outside it are excluded.
    pub(crate) fn changed_paths(&self, base: &str, head: &str) -> Result<BTreeSet<PathBuf>> {
        validate_revisions(base, head)?;
        let range = format!("{base}...{head}");
        let output = git_cmd!(
            &self.dir,
            "diff",
            "--name-only",
            "-z",
            "--no-renames",
            "--relative",
            &range,
            "--",
            "."
        )
        .stdout_capture()
        .run()
        .wrap_err_with(|| format!("git diff for {range} failed"))?;
        output
            .stdout
            .split(|byte| *byte == 0)
            .filter(|path| !path.is_empty())
            .map(path_from_git_bytes)
            .collect()
    }

    /// Returns the merge base used by a triple-dot comparison.
    pub(crate) fn merge_base(&self, base: &str, head: &str) -> Result<String> {
        validate_revisions(base, head)?;
        Ok(git_cmd_read!(&self.dir, "merge-base", "--", base, head)?
            .trim()
            .to_string())
    }

    /// Reads a UTF-8 file at a Git revision, returning `None` when it does not exist there.
    pub(crate) fn file_at_revision(&self, revision: &str, path: &Path) -> Result<Option<String>> {
        validate_revision("revision", revision)?;
        let Some(path) = path.to_str() else {
            return Ok(None);
        };
        let object = format!("{revision}:{}", path.replace('\\', "/"));
        let output = git_cmd!(&self.dir, "show", "--no-textconv", &object)
            .stdout_capture()
            .stderr_capture()
            .unchecked()
            .run()
            .wrap_err_with(|| format!("git show for {object:?} failed"))?;
        if !output.status.success() {
            return Ok(None);
        }
        Ok(Some(String::from_utf8(output.stdout).wrap_err_with(
            || format!("Git file {path:?} at {revision:?} is not UTF-8"),
        )?))
    }

    pub(crate) fn get_path<P: AsRef<Path>>(path: P) -> eyre::Result<PathBuf> {
        let root = Self::get_root()?;
        let path = cmd!("git", "-C", &root, "rev-parse", "--git-path", path.as_ref()).read()?;
        let path = PathBuf::from(path.trim());
        Ok(if path.is_absolute() {
            path
        } else {
            root.join(path)
        })
    }
}

fn validate_revisions(base: &str, head: &str) -> Result<()> {
    validate_revision("base", base)?;
    validate_revision("head", head)
}

fn validate_revision(name: &str, revision: &str) -> Result<()> {
    if revision.is_empty() || revision.starts_with('-') || revision.contains('\0') {
        return Err(eyre!("invalid Git {name} revision {revision:?}"));
    }
    Ok(())
}

fn path_from_git_bytes(path: &[u8]) -> Result<PathBuf> {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStringExt;
        Ok(OsString::from_vec(path.to_vec()).into())
    }
    #[cfg(not(unix))]
    {
        Ok(String::from_utf8(path.to_vec())
            .wrap_err("Git returned a non-UTF-8 path")?
            .into())
    }
}

/// Command-local configuration: mise does not write credentials or the helper
/// into repository configuration. Existing Git helpers retain their own policy.
/// Git invokes the helper only when authentication is needed. The helper also
/// validates the protocol and host before resolving any credentials.
pub(crate) fn github_credential_config(host: &str) -> String {
    let executable = crate::env::MISE_BIN.to_string_lossy();
    #[cfg(windows)]
    let executable = std::borrow::Cow::Owned(executable.replace('\\', "/"));
    let executable = shell_escape::unix::escape(executable);
    format!("credential.https://{host}.helper=!{executable} token github --git-credential")
}

fn get_git_version() -> Result<String> {
    let version = cmd!("git", "--version").read()?;
    Ok(version.trim().into())
}

fn sanitize_git_env(cmd: Expression) -> Expression {
    GIT_CONTEXT_ENV
        .iter()
        .fold(cmd, |cmd, env| cmd.env_remove(env))
}

fn sanitize_git_cmd_runner<'a>(cmd: CmdLineRunner<'a>) -> CmdLineRunner<'a> {
    GIT_CONTEXT_ENV
        .iter()
        .fold(cmd, |cmd, env| cmd.env_remove(env))
}

pub(crate) fn sanitize_git_command(cmd: &mut std::process::Command) {
    for env in GIT_CONTEXT_ENV {
        cmd.env_remove(env);
    }
}

const GIT_CONTEXT_ENV: &[&str] = &[
    "GIT_DIR",
    "GIT_WORK_TREE",
    "GIT_INDEX_FILE",
    "GIT_COMMON_DIR",
    "GIT_OBJECT_DIRECTORY",
    "GIT_ALTERNATE_OBJECT_DIRECTORIES",
    "GIT_NAMESPACE",
];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RemoteRefKind {
    Branch,
    Tag,
}

fn qualify_remote_ref(gitref: &str, kind: RemoteRefKind) -> String {
    let prefix = match kind {
        RemoteRefKind::Branch => "refs/heads/",
        RemoteRefKind::Tag => "refs/tags/",
    };
    if gitref.starts_with(prefix) {
        gitref.to_string()
    } else {
        format!("{prefix}{gitref}")
    }
}

fn remote_ref_kind(output: &str, branch_ref: &str, tag_ref: &str) -> Option<RemoteRefKind> {
    let has_ref = |expected: &str| {
        output.lines().any(|line| {
            line.split_once(char::is_whitespace)
                .is_some_and(|(_, name)| name == expected)
        })
    };

    if has_ref(branch_ref) {
        Some(RemoteRefKind::Branch)
    } else if has_ref(tag_ref) {
        Some(RemoteRefKind::Tag)
    } else {
        None
    }
}

/// Heuristic for whether a ref string is a commit SHA (full SHA-1 or SHA-256).
///
/// Branch and tag names that happen to be all-hex would also match, but git
/// disallows refs that are valid object IDs anyway (see `git check-ref-format`),
/// so the heuristic is safe in practice. Abbreviated SHAs are intentionally not
/// matched — they are ambiguous with short branch names and need server-side
/// resolution before they can be checked out.
fn looks_like_sha(s: &str) -> bool {
    matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit())
}

/// If `path` is inside a linked git worktree, returns the equivalent path in
/// the repository's main checkout, e.g. `/repo-wt/sub/mise.toml` →
/// `/repo/sub/mise.toml`. Returns None for paths in a main checkout, outside
/// any git repository, or in worktrees of a bare repository.
///
/// Detection is filesystem-only (no git subprocess): a linked worktree root
/// contains a `.git` *file* pointing at `<main>/.git/worktrees/<name>`.
pub(crate) fn main_checkout_equivalent(path: &Path) -> Option<PathBuf> {
    static CACHE: LazyLock<Mutex<HashMap<PathBuf, Option<PathBuf>>>> =
        LazyLock::new(Default::default);
    for wt_root in path.ancestors() {
        let dotgit = wt_root.join(".git");
        if dotgit.is_dir() {
            // A `.git` directory is either the main checkout or a nested
            // independent repository. Either way stop: a nested repo's
            // contents are not derived from the outer repo's history, so its
            // configs must keep their own trust records rather than
            // inheriting the outer main checkout's via path mapping.
            return None;
        }
        if dotgit.is_file() {
            // `.git` files are used by both linked worktrees and submodules.
            // Only a linked worktree resolves to a main checkout here; for
            // anything else (submodule, bare-repo worktree) keep walking up —
            // a submodule may itself live inside a linked worktree.
            let main_root = CACHE
                .lock()
                .unwrap()
                .entry(wt_root.to_path_buf())
                .or_insert_with(|| main_checkout_root(&dotgit))
                .clone();
            if let Some(main_root) = main_root {
                let equiv = main_root.join(path.strip_prefix(wt_root).ok()?);
                return (equiv != path).then_some(equiv);
            }
        }
    }
    None
}

/// Resolves a linked worktree's `.git` file to the root of the main checkout
fn main_checkout_root(dotgit_file: &Path) -> Option<PathBuf> {
    let contents = std::fs::read_to_string(dotgit_file).ok()?;
    let gitdir = PathBuf::from(contents.strip_prefix("gitdir:")?.trim());
    let gitdir = if gitdir.is_relative() {
        dotgit_file.parent()?.join(gitdir)
    } else {
        gitdir
    };
    // Linked worktrees keep their private git dir at
    // `<common>/worktrees/<name>`, containing a `commondir` file pointing to
    // the shared git dir (usually `../..`, i.e. `<main>/.git`). Submodule git
    // dirs live under `modules/` and have neither, which is what
    // distinguishes them here.
    if gitdir.parent()?.file_name() != Some(OsStr::new("worktrees")) {
        return None;
    }
    let common = PathBuf::from(
        std::fs::read_to_string(gitdir.join("commondir"))
            .ok()?
            .trim(),
    );
    let common = if common.is_relative() {
        gitdir.join(common)
    } else {
        common
    };
    let common = common.canonicalize().ok()?;
    if common.file_name() == Some(OsStr::new(".git")) {
        common.parent().map(|p| p.to_path_buf())
    } else {
        None // bare repository — no main checkout to share trust with
    }
}

/// A git binary mise can run unattended for its own plumbing, or None.
///
/// On macOS `/usr/bin/git` is a shim that opens the Xcode Command Line Tools
/// installer dialog when the tools are absent, so it only counts once
/// `xcode-select -p` confirms an installation. Any other git on PATH
/// (Homebrew, MacPorts) is taken as-is.
pub(crate) fn plumbing_binary() -> Option<&'static Path> {
    static BIN: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
        // spawnable as-is: on Windows that is `git.exe`, which a plain
        // lookup of `git` does not find
        let git = crate::file::which_spawnable("git")?;
        if cfg!(target_os = "macos") && git == Path::new("/usr/bin/git") {
            let installed = std::process::Command::new("xcode-select")
                .arg("-p")
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status()
                .is_ok_and(|status| status.success());
            if !installed {
                return None;
            }
        }
        Some(git)
    });
    BIN.as_deref()
}

/// One invocation of git plumbing against a [`GitPlumbing`] repository.
#[derive(Debug, Default)]
pub(crate) struct PlumbingCall<'a> {
    pub args: Vec<OsString>,
    /// Adds `--work-tree=<path>`.
    pub work_tree: Option<&'a Path>,
    /// Sets `GIT_INDEX_FILE` so the call never touches the repository's own
    /// index. Applied after [`sanitize_git_command`], which strips it.
    pub index_file: Option<&'a Path>,
    pub cwd: Option<&'a Path>,
    pub stdin: Option<&'a [u8]>,
}

impl<'a> PlumbingCall<'a> {
    pub(crate) fn new<I, S>(args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<OsString>,
    {
        Self {
            args: args.into_iter().map(Into::into).collect(),
            ..Default::default()
        }
    }

    pub(crate) fn work_tree(mut self, path: &'a Path) -> Self {
        self.work_tree = Some(path);
        self
    }

    pub(crate) fn index_file(mut self, path: &'a Path) -> Self {
        self.index_file = Some(path);
        self
    }

    pub(crate) fn stdin(mut self, bytes: &'a [u8]) -> Self {
        self.stdin = Some(bytes);
        self
    }
}

/// Runs git plumbing against a repository mise owns (a bare "shadow" repo),
/// isolated from the user's git configuration.
///
/// Every call ignores the system and global gitconfig, so `filter.*`
/// (git-crypt, LFS), `core.hooksPath`, `core.excludesFile`, aliases, and
/// credential helpers from the user's setup cannot act on mise's repository,
/// and pins a fixed committer identity. Only plumbing commands should be run
/// through it; porcelain (`commit`, `checkout`) would consult hooks.
#[derive(Debug)]
pub(crate) struct GitPlumbing {
    git_dir: PathBuf,
    disabled_hooks: std::sync::Mutex<Option<tempfile::TempDir>>,
}

impl GitPlumbing {
    pub(crate) fn new(git_dir: impl Into<PathBuf>) -> Self {
        Self {
            git_dir: git_dir.into(),
            disabled_hooks: std::sync::Mutex::new(None),
        }
    }

    pub(crate) fn git_dir(&self) -> &Path {
        &self.git_dir
    }

    /// Whether the repository has been initialised.
    pub(crate) fn exists(&self) -> bool {
        self.git_dir.join("HEAD").is_file()
    }

    /// Creates the bare repository if needed. Idempotent.
    pub(crate) fn init_bare(&self) -> Result<()> {
        if self.exists() {
            return Ok(());
        }
        if let Some(parent) = self.git_dir.parent() {
            crate::file::create_dir_all(parent)?;
        }
        let mut cmd = self.base_command()?;
        cmd.args(["init", "--bare", "--quiet"]).arg(&self.git_dir);
        run_plumbing(cmd, None)?;
        for (key, value) in [
            ("core.autocrlf", "false"),
            ("core.logAllRefUpdates", "false"),
            ("gc.auto", "0"),
            #[cfg(unix)]
            ("core.symlinks", "true"),
        ] {
            self.run(PlumbingCall::new(["config", key, value]))?;
        }
        Ok(())
    }

    /// Runs the call, failing on a non-zero exit with stderr in the error.
    pub(crate) fn run(&self, call: PlumbingCall<'_>) -> Result<()> {
        self.output(call).map(|_| ())
    }

    /// Runs the call and returns its stdout bytes.
    pub(crate) fn output(&self, call: PlumbingCall<'_>) -> Result<Vec<u8>> {
        let cmd = self.command(&call)?;
        run_plumbing(cmd, call.stdin)
    }

    /// Inspect a blob without buffering its full contents. Reap the reader
    /// after the prefix so large ordinary files need no encryption-size cap.
    pub(crate) fn blob_starts_with(&self, oid: &str, prefix: &[u8]) -> Result<bool> {
        use std::io::Read;
        use std::process::Stdio;
        let mut child = self
            .command(&PlumbingCall::new(["cat-file", "blob", oid]))?
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .spawn()?;
        let mut bytes = Vec::new();
        // Keep the pipe open until Git has exited: dropping it before kill
        // can make a large blob emit a spurious broken-pipe error on stderr.
        let mut output = child
            .stdout
            .take()
            .expect("stdout was piped")
            .take(prefix.len() as u64);
        let read = output.read_to_end(&mut bytes);
        let complete = bytes.len() == prefix.len();
        if complete || read.is_err() {
            let _ = child.kill();
        }
        let status = child.wait()?;
        read?;
        if !complete && !status.success() {
            eyre::bail!("failed to inspect Git blob {oid}");
        }
        Ok(bytes == prefix)
    }

    /// Runs the call and returns its full output without treating a non-zero
    /// exit as an error, for commands whose status carries meaning.
    pub(crate) fn output_unchecked(&self, call: PlumbingCall<'_>) -> Result<std::process::Output> {
        let cmd = self.command(&call)?;
        spawn_plumbing(cmd, call.stdin)
    }

    /// Runs the call with stdout and stderr inherited, for output that goes
    /// straight to the terminal (a patch can be as large as a snapshot), and
    /// returns its status without treating a non-zero exit as an error.
    pub(crate) fn status_inherited(
        &self,
        call: PlumbingCall<'_>,
    ) -> Result<std::process::ExitStatus> {
        let mut cmd = self.command(&call)?;
        cmd.stdout(std::process::Stdio::inherit())
            .stderr(std::process::Stdio::inherit())
            .stdin(std::process::Stdio::null());
        cmd.status()
            .wrap_err_with(|| format!("failed to run {}", describe_plumbing(&cmd)))
    }

    /// Runs the call and returns its trimmed stdout.
    pub(crate) fn output_str(&self, call: PlumbingCall<'_>) -> Result<String> {
        let out = self.output(call)?;
        Ok(String::from_utf8_lossy(&out).trim().to_string())
    }

    /// Runs a network command (`fetch`, `push`, `ls-remote`) against this
    /// repository with the user's normal git configuration: credential
    /// helpers, ssh settings, and URL rewrites apply, while hooks, filters,
    /// and aliases still cannot act on mise's repository because only
    /// plumbing runs here. Prompts are disabled when nobody is attending.
    pub(crate) fn network_output(&self, call: PlumbingCall<'_>) -> Result<std::process::Output> {
        eyre::ensure!(
            call.work_tree.is_none() && call.index_file.is_none() && call.stdin.is_none(),
            "network Git calls do not accept a work tree, alternate index, or stdin"
        );
        let git =
            plumbing_binary().ok_or_else(|| eyre!("no unattended git executable is available"))?;
        let mut cmd = std::process::Command::new(git);
        sanitize_git_command(&mut cmd);
        if !console::user_attended_stderr() {
            cmd.env("GIT_TERMINAL_PROMPT", "0");
        }
        cmd.args([
            "-c",
            &github_credential_config("github.com"),
            "-c",
            &github_credential_config("github.com:443"),
        ]);
        cmd.env("GIT_OPTIONAL_LOCKS", "0")
            .env("LC_ALL", "C")
            .stdin(std::process::Stdio::null());
        let mut git_dir = OsString::from("--git-dir=");
        git_dir.push(&self.git_dir);
        cmd.arg(git_dir);
        // A private empty directory is an unambiguous hooks path on every
        // platform, unlike Unix null-device spellings on native Windows.
        let hooks = tempfile::tempdir()?;
        let mut hooks_config = OsString::from("core.hooksPath=");
        hooks_config.push(hooks.path());
        cmd.arg("-c")
            .arg(hooks_config)
            .args(["-c", "advice.fetchShowForcedUpdates=false"]);
        cmd.args(&call.args);
        if let Some(cwd) = call.cwd {
            cmd.current_dir(cwd);
        }
        spawn_plumbing(cmd, None)
    }

    fn base_command(&self) -> Result<std::process::Command> {
        let git =
            plumbing_binary().ok_or_else(|| eyre!("no unattended git executable is available"))?;
        let mut cmd = std::process::Command::new(git);
        sanitize_git_command(&mut cmd);
        // Internal object and ref operations must not inherit configuration
        // injected by the calling shell. Network commands intentionally keep
        // these variables for credential helpers and the GitHub relay.
        cmd.env_remove("GIT_CONFIG_COUNT")
            .env_remove("GIT_CONFIG_PARAMETERS");
        let mut hooks = self
            .disabled_hooks
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if hooks.is_none() {
            *hooks = Some(tempfile::tempdir()?);
        }
        let mut hooks_config = OsString::from("core.hooksPath=");
        hooks_config.push(hooks.as_ref().expect("hooks directory initialized").path());
        cmd.arg("-c").arg(hooks_config);
        let null = if cfg!(windows) { "NUL" } else { "/dev/null" };
        cmd.env("GIT_CONFIG_NOSYSTEM", "1")
            .env("GIT_CONFIG_GLOBAL", null)
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_OPTIONAL_LOCKS", "0")
            .env("GIT_AUTHOR_NAME", "mise")
            .env("GIT_AUTHOR_EMAIL", "mise@localhost")
            .env("GIT_COMMITTER_NAME", "mise")
            .env("GIT_COMMITTER_EMAIL", "mise@localhost")
            .env("LC_ALL", "C")
            .stdin(std::process::Stdio::null());
        Ok(cmd)
    }

    fn command(&self, call: &PlumbingCall<'_>) -> Result<std::process::Command> {
        let mut cmd = self.base_command()?;
        let mut git_dir = OsString::from("--git-dir=");
        git_dir.push(&self.git_dir);
        cmd.arg(git_dir);
        if let Some(work_tree) = call.work_tree {
            let mut arg = OsString::from("--work-tree=");
            arg.push(work_tree);
            cmd.arg(arg);
        }
        cmd.args([
            "-c",
            "core.autocrlf=false",
            "-c",
            "core.quotePath=false",
            "-c",
            "advice.addEmbeddedRepo=false",
        ]);
        cmd.args(&call.args);
        if let Some(index) = call.index_file {
            cmd.env("GIT_INDEX_FILE", index);
        }
        if let Some(cwd) = call.cwd {
            cmd.current_dir(cwd);
        }
        if call.stdin.is_some() {
            cmd.stdin(std::process::Stdio::piped());
        }
        Ok(cmd)
    }
}

fn describe_plumbing(cmd: &std::process::Command) -> String {
    let args = cmd
        .get_args()
        .map(|arg| arg.to_string_lossy().into_owned())
        .collect::<Vec<_>>();
    format!("git {}", args.join(" "))
}

fn spawn_plumbing(
    mut cmd: std::process::Command,
    stdin: Option<&[u8]>,
) -> Result<std::process::Output> {
    use std::io::Write;

    cmd.stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped());
    let mut child = cmd
        .spawn()
        .wrap_err_with(|| format!("failed to spawn {}", describe_plumbing(&cmd)))?;
    if let Some(bytes) = stdin {
        let mut pipe = child.stdin.take().expect("stdin was piped");
        // git may exit before reading everything (a bad pathspec, say); that
        // shows up in its status, so a broken pipe here is not the error.
        let _ = pipe.write_all(bytes);
        drop(pipe);
    }
    child
        .wait_with_output()
        .wrap_err_with(|| format!("failed to run {}", describe_plumbing(&cmd)))
}

fn run_plumbing(cmd: std::process::Command, stdin: Option<&[u8]>) -> Result<Vec<u8>> {
    let describe = describe_plumbing(&cmd);
    let output = spawn_plumbing(cmd, stdin)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(eyre!(
            "{describe} failed ({}): {}",
            output.status,
            stderr.trim()
        ));
    }
    Ok(output.stdout)
}

impl Debug for Git {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Git").field("dir", &self.dir).finish()
    }
}

#[derive(Default)]
pub(crate) struct CloneOptions<'a> {
    pr: Option<&'a dyn SingleReport>,
    branch: Option<String>,
    revision: Option<String>,
}

impl<'a> CloneOptions<'a> {
    pub(crate) fn pr(mut self, pr: &'a dyn SingleReport) -> Self {
        self.pr = Some(pr);
        self
    }

    pub(crate) fn branch(mut self, branch: &str) -> Self {
        self.branch = Some(branch.to_string());
        self.revision = None;
        self
    }

    /// Clone the complete repository and check out a revision afterwards.
    ///
    /// Unlike `branch`, this accepts abbreviated commit IDs and avoids passing
    /// them to `git clone -b` or gix's ref-name-only clone API.
    pub(crate) fn revision(mut self, revision: &str) -> Self {
        self.branch = None;
        self.revision = Some(revision.to_string());
        self
    }
}

#[cfg(test)]
mod tests {
    use super::{CloneOptions, Git, looks_like_sha, sanitize_git_cmd_runner, sanitize_git_env};
    use crate::cmd::CmdLineRunner;
    use crate::config::Settings;
    use std::process::Command;

    #[test]
    fn network_calls_reject_unsupported_plumbing_fields() {
        use super::{GitPlumbing, PlumbingCall};
        let temp = tempfile::tempdir().unwrap();
        let repo = GitPlumbing::new(temp.path().join("unused.git"));
        for call in [
            PlumbingCall::new(["fetch"]).work_tree(temp.path()),
            PlumbingCall::new(["fetch"]).index_file(temp.path()),
            PlumbingCall::new(["fetch"]).stdin(b"unexpected"),
        ] {
            assert!(
                repo.network_output(call)
                    .unwrap_err()
                    .to_string()
                    .contains("network Git calls do not accept")
            );
        }
    }

    #[test]
    fn sha_detection() {
        assert!(looks_like_sha("0123456789abcdef0123456789abcdef01234567"));
        assert!(looks_like_sha(
            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
        ));
        assert!(!looks_like_sha("main"));
        assert!(!looks_like_sha("v1.2.3"));
        assert!(!looks_like_sha("abcdef1")); // short SHA not supported
        assert!(!looks_like_sha(""));
        assert!(!looks_like_sha("g123456789abcdef0123456789abcdef01234567")); // non-hex
    }

    #[test]
    fn remote_ref_parser_prefers_branches_over_tags() {
        let output = "\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\trefs/heads/release
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\trefs/tags/release
";
        assert_eq!(
            super::remote_ref_kind(output, "refs/heads/release", "refs/tags/release"),
            Some(super::RemoteRefKind::Branch)
        );
        assert_eq!(
            super::remote_ref_kind(output, "refs/heads/missing", "refs/tags/release"),
            Some(super::RemoteRefKind::Tag)
        );
        assert_eq!(
            super::remote_ref_kind(output, "refs/heads/missing", "refs/tags/missing"),
            None
        );
    }

    #[test]
    fn reads_files_from_the_merge_base_and_head() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let git = |args: &[&str]| {
            let output = Command::new("git")
                .args(args)
                .current_dir(root)
                .output()
                .unwrap();
            assert!(
                output.status.success(),
                "git {args:?} failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            String::from_utf8(output.stdout).unwrap().trim().to_string()
        };
        git(&["-c", "init.defaultBranch=main", "init", "-q"]);
        git(&["config", "user.email", "test@example.com"]);
        git(&["config", "user.name", "Test"]);
        std::fs::write(root.join("lockfile"), "before\n").unwrap();
        git(&["add", "lockfile"]);
        git(&["commit", "-q", "-m", "before"]);
        let base = git(&["rev-parse", "HEAD"]);
        std::fs::write(root.join("lockfile"), "after\n").unwrap();
        git(&["commit", "-q", "-am", "after"]);
        let head = git(&["rev-parse", "HEAD"]);

        let repo = Git::new(root);
        assert_eq!(repo.merge_base(&base, &head).unwrap(), base);
        assert_eq!(
            repo.file_at_revision(&base, std::path::Path::new("lockfile"))
                .unwrap()
                .as_deref(),
            Some("before\n")
        );
        assert_eq!(
            repo.file_at_revision(&head, std::path::Path::new("lockfile"))
                .unwrap()
                .as_deref(),
            Some("after\n")
        );
        assert_eq!(
            repo.file_at_revision(&head, std::path::Path::new("missing"))
                .unwrap(),
            None
        );
    }

    #[test]
    fn update_resolves_short_branches_and_tags() {
        let tmp = tempfile::tempdir().unwrap();
        let origin = tmp.path().join("origin");
        std::fs::create_dir_all(&origin).unwrap();

        let git_in = |dir: &std::path::Path, args: &[&str]| {
            let out = Command::new("git")
                .args(args)
                .current_dir(dir)
                .output()
                .expect("spawn git");
            assert!(
                out.status.success(),
                "git {args:?} failed: {}",
                String::from_utf8_lossy(&out.stderr)
            );
            String::from_utf8(out.stdout).unwrap().trim().to_string()
        };
        git_in(&origin, &["-c", "init.defaultBranch=main", "init", "-q"]);
        git_in(&origin, &["config", "user.email", "test@example.com"]);
        git_in(&origin, &["config", "user.name", "Test"]);

        std::fs::write(origin.join("version"), "release\n").unwrap();
        git_in(&origin, &["add", "version"]);
        git_in(&origin, &["commit", "-q", "-m", "release"]);
        let release_sha = git_in(&origin, &["rev-parse", "HEAD"]);
        git_in(&origin, &["branch", "release-branch"]);
        git_in(&origin, &["branch", "collision"]);
        git_in(&origin, &["tag", "lightweight-v1"]);
        git_in(
            &origin,
            &["tag", "-a", "annotated-v1", "-m", "annotated-v1"],
        );

        std::fs::write(origin.join("version"), "tag-collision\n").unwrap();
        git_in(&origin, &["commit", "-q", "-am", "tag collision"]);
        let tag_collision_sha = git_in(&origin, &["rev-parse", "HEAD"]);
        git_in(&origin, &["tag", "-a", "collision", "-m", "collision"]);

        std::fs::write(origin.join("version"), "main\n").unwrap();
        git_in(&origin, &["commit", "-q", "-am", "main"]);

        let cases = [
            ("release-branch", release_sha.as_str()),
            ("lightweight-v1", release_sha.as_str()),
            ("annotated-v1", release_sha.as_str()),
            ("refs/tags/annotated-v1", release_sha.as_str()),
            (release_sha.as_str(), release_sha.as_str()),
            ("collision", release_sha.as_str()),
            ("refs/tags/collision", tag_collision_sha.as_str()),
        ];
        let url = format!("file://{}", origin.display());
        for (index, (selector, expected_sha)) in cases.into_iter().enumerate() {
            let clone = tmp.path().join(format!("clone-{index}"));
            git_in(tmp.path(), &["clone", "-q", &url, clone.to_str().unwrap()]);
            if selector == "annotated-v1" {
                // A stale local branch must not override a remote tag after the
                // remote branch has disappeared.
                git_in(&clone, &["branch", "annotated-v1"]);
            }

            Git::new(&clone)
                .update(Some(selector.to_string()))
                .unwrap_or_else(|err| panic!("update {selector} failed: {err:#}"));
            assert_eq!(
                git_in(&clone, &["rev-parse", "HEAD"]),
                expected_sha,
                "selector {selector} checked out the wrong commit"
            );
        }

        let clone = tmp.path().join("clone-update-tag-full-ref");
        git_in(tmp.path(), &["clone", "-q", &url, clone.to_str().unwrap()]);
        Git::new(&clone)
            .update_tag("refs/tags/annotated-v1".to_string())
            .unwrap_or_else(|err| panic!("update_tag with full ref failed: {err:#}"));
        assert_eq!(git_in(&clone, &["rev-parse", "HEAD"]), release_sha);
    }

    #[test]
    fn worktree_main_checkout_equivalent() {
        let tmp = tempfile::tempdir().unwrap();
        let base = tmp.path().canonicalize().unwrap();
        let main = base.join("main");
        let wt = base.join("wt");
        std::fs::create_dir_all(main.join(".git/worktrees/wt")).unwrap();
        std::fs::create_dir_all(wt.join("sub")).unwrap();
        std::fs::write(main.join(".git/worktrees/wt/commondir"), "../..\n").unwrap();
        std::fs::write(
            wt.join(".git"),
            format!("gitdir: {}\n", main.join(".git/worktrees/wt").display()),
        )
        .unwrap();

        // worktree root and nested paths map to the main checkout
        assert_eq!(super::main_checkout_equivalent(&wt), Some(main.clone()));
        assert_eq!(
            super::main_checkout_equivalent(&wt.join("sub/mise.toml")),
            Some(main.join("sub/mise.toml"))
        );
        // main checkout and non-repo paths do not map
        assert_eq!(super::main_checkout_equivalent(&main), None);
        assert_eq!(super::main_checkout_equivalent(&base), None);

        // worktree of a bare repo does not map
        let bare = base.join("bare.git");
        let bare_wt = base.join("bare-wt");
        std::fs::create_dir_all(bare.join("worktrees/bare-wt")).unwrap();
        std::fs::create_dir_all(&bare_wt).unwrap();
        std::fs::write(bare.join("worktrees/bare-wt/commondir"), "../..\n").unwrap();
        std::fs::write(
            bare_wt.join(".git"),
            format!("gitdir: {}\n", bare.join("worktrees/bare-wt").display()),
        )
        .unwrap();
        assert_eq!(super::main_checkout_equivalent(&bare_wt), None);

        // a submodule also uses a `.git` file but is not a linked worktree:
        // its configs must not inherit the parent checkout's trust
        let subm = main.join("subm");
        std::fs::create_dir_all(main.join(".git/modules/subm")).unwrap();
        std::fs::create_dir_all(&subm).unwrap();
        std::fs::write(
            subm.join(".git"),
            format!("gitdir: {}\n", main.join(".git/modules/subm").display()),
        )
        .unwrap();
        assert_eq!(super::main_checkout_equivalent(&subm), None);
        assert_eq!(
            super::main_checkout_equivalent(&subm.join("mise.toml")),
            None
        );

        // a submodule checked out inside a linked worktree maps through the
        // outer worktree to the same submodule path in the main checkout
        let wt_subm = wt.join("subm");
        std::fs::create_dir_all(&wt_subm).unwrap();
        std::fs::write(
            wt_subm.join(".git"),
            format!("gitdir: {}\n", main.join(".git/modules/subm").display()),
        )
        .unwrap();
        assert_eq!(
            super::main_checkout_equivalent(&wt_subm.join("mise.toml")),
            Some(subm.join("mise.toml"))
        );
    }

    #[test]
    fn git_commands_ignore_inherited_work_tree() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        let cache = tmp.path().join("cache");
        let work_tree = tmp.path().join("work-tree");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::create_dir_all(&work_tree).unwrap();

        let git_in = |dir: &std::path::Path, args: &[&str]| {
            let out = Command::new("git")
                .args(args)
                .current_dir(dir)
                .output()
                .expect("spawn git");
            assert!(
                out.status.success(),
                "git {args:?} failed: {}",
                String::from_utf8_lossy(&out.stderr)
            );
            out
        };
        git_in(&src, &["-c", "init.defaultBranch=main", "init", "-q"]);
        std::fs::write(src.join("file.txt"), "hello\n").unwrap();
        git_in(&src, &["add", "file.txt"]);
        git_in(
            &src,
            &[
                "-c",
                "user.email=t@t",
                "-c",
                "user.name=t",
                "commit",
                "-q",
                "-m",
                "main",
            ],
        );
        let url = format!("file://{}", src.display());
        let clone = Command::new("git")
            .args(["clone", "-q", &url])
            .arg(&cache)
            .output()
            .expect("spawn git clone");
        assert!(
            clone.status.success(),
            "git clone failed: {}",
            String::from_utf8_lossy(&clone.stderr)
        );
        std::fs::remove_file(cache.join("file.txt")).unwrap();

        let output = sanitize_git_env(
            git_cmd!(&cache, "checkout", "--force", "HEAD")
                .env("GIT_WORK_TREE", &work_tree)
                .env("GIT_INDEX_FILE", work_tree.join("index")),
        )
        .stderr_to_stdout()
        .stdout_capture()
        .unchecked()
        .run()
        .expect("run git checkout");
        assert!(
            output.status.success(),
            "git checkout failed: {}",
            String::from_utf8_lossy(&output.stdout)
        );

        assert!(cache.join("file.txt").exists());
        assert!(!work_tree.join("file.txt").exists());
        assert!(!work_tree.join("index").exists());

        let clone_cache = tmp.path().join("clone-cache");
        sanitize_git_cmd_runner(
            CmdLineRunner::new("git")
                .arg("clone")
                .arg("-q")
                .arg(&url)
                .arg(&clone_cache)
                .env("GIT_WORK_TREE", &work_tree),
        )
        .execute()
        .expect("git clone should ignore inherited GIT_WORK_TREE");

        assert!(clone_cache.join("file.txt").exists());
        assert!(!work_tree.join("file.txt").exists());
    }

    /// Regression test for https://github.com/jdx/mise/discussions/9472:
    /// gix's `with_ref_name` panics ("we map by name only and have no
    /// object-id in refspec") when given a commit SHA. Our `clone()` must
    /// detect that case and fall back to a plain clone + checkout.
    ///
    /// Covers both the gix backend (where the panic originates) and a SHA
    /// reachable only from a non-default branch (so the clone must be full,
    /// not shallow, for the checkout to find the object).
    #[test]
    fn clone_by_sha_does_not_panic() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();

        let git_in = |dir: &std::path::Path, args: &[&str]| {
            let out = Command::new("git")
                .args(args)
                .current_dir(dir)
                .output()
                .expect("spawn git");
            assert!(
                out.status.success(),
                "git {args:?} failed: {}",
                String::from_utf8_lossy(&out.stderr)
            );
            out
        };
        git_in(&src, &["-c", "init.defaultBranch=main", "init", "-q"]);
        git_in(
            &src,
            &[
                "-c",
                "user.email=t@t",
                "-c",
                "user.name=t",
                "commit",
                "-q",
                "--allow-empty",
                "-m",
                "main",
            ],
        );
        // Park the SHA we want to check out on a non-default branch, so the
        // test would fail if `clone()` did a shallow / single-branch clone.
        git_in(&src, &["checkout", "-q", "-b", "feature"]);
        git_in(
            &src,
            &[
                "-c",
                "user.email=t@t",
                "-c",
                "user.name=t",
                "commit",
                "-q",
                "--allow-empty",
                "-m",
                "feature",
            ],
        );
        let sha = String::from_utf8(git_in(&src, &["rev-parse", "HEAD"]).stdout)
            .unwrap()
            .trim()
            .to_string();
        assert_eq!(sha.len(), 40);
        // Move feature off HEAD so the SHA isn't on the default branch.
        git_in(&src, &["checkout", "-q", "main"]);

        let url = format!("file://{}", src.display());

        // gix path — the panic site. Settings::gix defaults to true, but make
        // it explicit so the test is robust to future default changes.
        let backups = (Settings::get().gix, Settings::get().libgit2);
        Settings::override_with(|s| {
            s.gix = Some(true);
            s.libgit2 = Some(false);
        });
        let dst_gix = tmp.path().join("dst-gix");
        Git::new(&dst_gix)
            .clone(&url, CloneOptions::default().revision(&sha))
            .expect("gix clone with SHA must not panic and must succeed");
        let head = git_in(&dst_gix, &["rev-parse", "HEAD"]);
        assert_eq!(String::from_utf8(head.stdout).unwrap().trim(), sha);

        // Explicit revisions also accept an unambiguous abbreviated commit ID.
        let short_sha = &sha[..12];
        let dst_short = tmp.path().join("dst-short");
        Git::new(&dst_short)
            .clone(&url, CloneOptions::default().revision(short_sha))
            .expect("clone with abbreviated revision must succeed");
        let head = git_in(&dst_short, &["rev-parse", "HEAD"]);
        assert_eq!(String::from_utf8(head.stdout).unwrap().trim(), sha);

        let dst_invalid = tmp.path().join("dst-invalid");
        let err = Git::new(&dst_invalid)
            .clone(&url, CloneOptions::default().revision("deadbeef"))
            .expect_err("unknown revision must fail");
        assert!(format!("{err:#}").contains("deadbeef"));

        // CLI path — `git clone -b <sha>` is rejected; verify the SHA
        // bypass works there too.
        Settings::override_with(|s| {
            s.gix = Some(false);
            s.libgit2 = Some(false);
        });
        let dst_cli = tmp.path().join("dst-cli");
        Git::new(&dst_cli)
            .clone(&url, CloneOptions::default().branch(&sha))
            .expect("CLI clone with SHA must succeed");
        let head = git_in(&dst_cli, &["rev-parse", "HEAD"]);
        assert_eq!(String::from_utf8(head.stdout).unwrap().trim(), sha);

        // Restore so we don't leak settings into other tests.
        Settings::override_with(|s| {
            s.gix = Some(backups.0);
            s.libgit2 = Some(backups.1);
        });
    }
}

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

    #[test]
    fn plumbing_isolates_user_config_and_keeps_the_scratch_index() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = GitPlumbing::new(tmp.path().join("shadow.git"));
        let index = tmp.path().join("scratch-index");
        let work_tree = tmp.path().join("tree");
        let cmd = repo
            .command(
                &PlumbingCall::new(["write-tree"])
                    .work_tree(&work_tree)
                    .index_file(&index),
            )
            .unwrap();
        let envs: HashMap<_, _> = cmd
            .get_envs()
            .map(|(k, v)| (k.to_os_string(), v.map(|v| v.to_os_string())))
            .collect();
        // sanitize_git_command strips GIT_INDEX_FILE; the call sets it afterwards
        assert_eq!(
            envs.get(OsStr::new("GIT_INDEX_FILE")).cloned().flatten(),
            Some(index.into_os_string())
        );
        assert_eq!(
            envs.get(OsStr::new("GIT_DIR")).cloned(),
            Some(None),
            "GIT_DIR must be removed rather than inherited"
        );
        assert_eq!(
            envs.get(OsStr::new("GIT_CONFIG_NOSYSTEM"))
                .cloned()
                .flatten(),
            Some(OsString::from("1"))
        );
        assert!(envs.contains_key(OsStr::new("GIT_CONFIG_GLOBAL")));
        for variable in ["GIT_CONFIG_COUNT", "GIT_CONFIG_PARAMETERS"] {
            assert_eq!(envs.get(OsStr::new(variable)), Some(&None));
        }
        let args: Vec<String> = cmd
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(
            args.iter().any(|arg| arg.starts_with("--git-dir=")),
            "{args:?}"
        );
        assert!(
            args.iter().any(|arg| arg.starts_with("--work-tree=")),
            "{args:?}"
        );
        assert_eq!(args.last().map(String::as_str), Some("write-tree"));
    }

    #[test]
    fn init_bare_is_idempotent_and_ignores_global_config() {
        if plumbing_binary().is_none() {
            return;
        }
        let tmp = tempfile::tempdir().unwrap();
        let repo = GitPlumbing::new(tmp.path().join("shadow.git"));
        assert!(!repo.exists());
        repo.init_bare().unwrap();
        assert!(repo.exists());
        repo.init_bare().unwrap();
        let hooks = repo
            .output_str(PlumbingCall::new(["config", "--get", "gc.auto"]))
            .unwrap();
        assert_eq!(hooks, "0");
        // a global hooksPath or filter must not reach the shadow repository
        let global = repo
            .output_unchecked(PlumbingCall::new([
                "config",
                "--global",
                "--get",
                "core.hooksPath",
            ]))
            .unwrap();
        assert!(!global.status.success() || global.stdout.is_empty());
    }

    #[test]
    fn network_commands_override_hooks_with_a_private_directory() {
        if plumbing_binary().is_none() {
            return;
        }
        let temp = tempfile::tempdir().unwrap();
        let repo = GitPlumbing::new(temp.path().join("network.git"));
        repo.init_bare().unwrap();
        repo.run(PlumbingCall::new([
            "config",
            "core.hooksPath",
            "untrusted-hooks",
        ]))
        .unwrap();
        let internal = repo
            .output_str(PlumbingCall::new(["config", "--get", "core.hooksPath"]))
            .unwrap();
        assert!(Path::new(&internal).is_dir());
        assert_eq!(std::fs::read_dir(&internal).unwrap().count(), 0);
        let out = repo
            .network_output(PlumbingCall::new(["config", "--get", "core.hooksPath"]))
            .unwrap();
        assert!(out.status.success());
        let hooks = String::from_utf8(out.stdout).unwrap();
        let hooks = Path::new(hooks.trim());
        assert!(hooks.is_absolute());
        assert_ne!(hooks, Path::new("/dev/null"));
        assert!(
            !hooks.exists(),
            "temporary hooks directory was not cleaned up"
        );
    }
}