prek 0.5.5

A fast Git hook manager written in Rust, designed as a drop-in alternative to pre-commit, reimagined.
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
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::str::Utf8Error;
use std::sync::{LazyLock, OnceLock};

use anyhow::Result;
use itertools::Itertools;
use prek_consts::env_vars::{EnvVars, EnvVarsRead};
use rustc_hash::FxHashSet;
use same_file::is_same_file;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tracing::{debug, instrument, warn};

use crate::fs::PathClean;
use crate::process;
use crate::process::{Cmd, StatusError};

#[derive(Debug, thiserror::Error)]
pub(crate) enum Error {
    #[error(transparent)]
    Command(#[from] process::Error),

    #[error("Failed to find git: {0}")]
    GitNotFound(#[from] which::Error),

    #[error(
        "Not in a Git repository. Change to a Git repository, or run `git init` to create one."
    )]
    NotRepository,

    #[error(transparent)]
    Io(#[from] std::io::Error),

    #[error(transparent)]
    UTF8(#[from] Utf8Error),

    #[error("Invalid file record in Git diff output")]
    InvalidDiffFile,

    #[error(
        "Git resolved hooks directory to the current directory (`{0}`). Unset `core.hooksPath` or set it to a real directory path."
    )]
    InvalidHooksPath(PathBuf),
}

pub(crate) static GIT: LazyLock<Result<PathBuf, which::Error>> = LazyLock::new(|| {
    let git = which::which("git")?;
    // Resolve Apple's developer-tool shim once instead of looking up the toolchain
    // on every Git invocation. Leave custom Git executables and wrappers alone.
    #[cfg(target_os = "macos")]
    if git == Path::new("/usr/bin/git")
        && let Ok(output) = Command::new("/usr/bin/xcrun")
            .args(["--find", "git"])
            .output()
        && output.status.success()
    {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt as _;

        let stdout = output.stdout.strip_suffix(b"\n").unwrap_or(&output.stdout);
        return Ok(PathBuf::from(OsStr::from_bytes(stdout)));
    }
    Ok(git)
});

// Git can expose `GIT_DIR` without `GIT_WORK_TREE` to hooks. Keep the derived
// work tree in process-local state and add it only when preserving the current
// repository requires it.
static GIT_WORK_TREE: OnceLock<Option<PathBuf>> = OnceLock::new();

pub(crate) fn init_git_work_tree() -> Result<()> {
    if !EnvVars.is_set(EnvVars::GIT_DIR) || EnvVars.is_set(EnvVars::GIT_WORK_TREE) {
        let _ = GIT_WORK_TREE.set(None);
        return Ok(());
    }

    let cwd = std::env::current_dir()?;
    debug!(
        "Using {} `{}` for git commands",
        EnvVars::GIT_WORK_TREE,
        cwd.display()
    );
    let _ = GIT_WORK_TREE.set(Some(cwd));
    Ok(())
}

/// Return the absolute worktree path saved for hook subprocesses, if one was needed.
fn git_work_tree() -> Option<&'static Path> {
    GIT_WORK_TREE.get().and_then(Option::as_deref)
}

#[derive(Debug)]
struct Repo {
    root: Result<PathBuf, Error>,
    git_dir: PathBuf,
    common_dir: PathBuf,
    hooks_dir: PathBuf,
}

static REPO: LazyLock<Result<Repo, Error>> =
    LazyLock::new(|| Repo::discover(&std::env::current_dir()?));

/// Return the absolute path of the current repository's working tree.
pub(crate) fn root() -> Result<&'static Path, &'static Error> {
    REPO.as_ref()?.root.as_deref()
}

/// Return the absolute Git directory of the current worktree, even after changing directory.
pub(crate) fn git_dir() -> Result<&'static Path, &'static Error> {
    Ok(&REPO.as_ref()?.git_dir)
}

/// Return the absolute Git directory shared by the current repository's worktrees.
pub(crate) fn common_dir() -> Result<&'static Path, &'static Error> {
    Ok(&REPO.as_ref()?.common_dir)
}

/// Repository-local environment variables cleared before operating on another repository.
///
/// `GIT_CONFIG_PARAMETERS`, `GIT_CONFIG_COUNT`, `GIT_CONFIG_KEY_*`, and `GIT_CONFIG_VALUE_*`
/// are deliberately excluded so nested Git commands retain caller-supplied command-scoped settings.
static GIT_REPO_LOCAL_ENVS: &[&str] = &[
    "GIT_ALTERNATE_OBJECT_DIRECTORIES",
    "GIT_CONFIG",
    "GIT_OBJECT_DIRECTORY",
    "GIT_DIR",
    "GIT_WORK_TREE",
    "GIT_IMPLICIT_WORK_TREE",
    "GIT_GRAFT_FILE",
    "GIT_INDEX_FILE",
    "GIT_NO_REPLACE_OBJECTS",
    "GIT_REPLACE_REF_BASE",
    "GIT_PREFIX",
    "GIT_INTERNAL_SUPER_PREFIX",
    "GIT_SHALLOW_FILE",
    "GIT_COMMON_DIR",
];

pub(crate) trait GitCommandExt {
    /// Keep nested Git commands operating on the repository that invoked the hook.
    ///
    /// Git treats the current directory as the work tree when `GIT_DIR` is set but
    /// `GIT_WORK_TREE` is not. If prek starts the hook in a subdirectory, this method passes
    /// the original work tree explicitly so Git commands in the hook still use the repository
    /// that invoked prek.
    ///
    /// A hook that intentionally operates on another repository must clear Git's
    /// repository-local environment before starting Git.
    fn preserve_current_worktree(&mut self, hook_cwd: &Path) -> &mut Self;

    fn sanitize_git_repo_env(&mut self) -> &mut Self;
}

pub(crate) fn apply_git_work_tree(cmd: &mut Command) -> &mut Command {
    if let Some(work_tree) = git_work_tree() {
        cmd.env(EnvVars::GIT_WORK_TREE, work_tree);
    }
    cmd
}

impl GitCommandExt for Cmd {
    fn preserve_current_worktree(&mut self, hook_cwd: &Path) -> &mut Self {
        let Some(work_tree) = git_work_tree() else {
            return self;
        };
        let is_work_tree_root =
            hook_cwd == work_tree || is_same_file(hook_cwd, work_tree).unwrap_or(false);
        if !is_work_tree_root {
            self.env(EnvVars::GIT_WORK_TREE, work_tree);
        }
        self
    }

    fn sanitize_git_repo_env(&mut self) -> &mut Self {
        for key in GIT_REPO_LOCAL_ENVS {
            self.env_remove(key);
        }
        self
    }
}

pub(crate) fn git_cmd() -> Result<Cmd, Error> {
    let mut cmd = Cmd::new(GIT.as_ref().map_err(|&e| Error::GitNotFound(e))?);
    cmd.hidden_args(["-c", "core.useBuiltinFSMonitor=false"]);
    if let Some(work_tree) = git_work_tree() {
        cmd.env(EnvVars::GIT_WORK_TREE, work_tree);
    }

    Ok(cmd)
}

/// Decode NUL-separated paths without changing their spelling or base directory.
fn zsplit(s: &[u8]) -> Result<Vec<PathBuf>, Utf8Error> {
    s.split(|&b| b == b'\0')
        .filter(|slice| !slice.is_empty())
        .map(path_from_git_bytes)
        .collect()
}

/// Decode a Git path without resolving it against a directory.
#[cfg(unix)]
#[expect(clippy::unnecessary_wraps)]
fn path_from_git_bytes(bytes: &[u8]) -> Result<PathBuf, Utf8Error> {
    use std::ffi::OsStr;
    use std::os::unix::ffi::OsStrExt as _;

    Ok(PathBuf::from(OsStr::from_bytes(bytes)))
}

/// Decode a Git path without resolving it against a directory.
#[cfg(not(unix))]
fn path_from_git_bytes(bytes: &[u8]) -> Result<PathBuf, Utf8Error> {
    str::from_utf8(bytes).map(PathBuf::from)
}

/// Encode a path for Git without changing its spelling or base directory.
#[cfg(unix)]
#[expect(clippy::unnecessary_wraps)]
fn path_to_git_bytes(path: &Path) -> std::io::Result<&[u8]> {
    use std::os::unix::ffi::OsStrExt as _;

    Ok(path.as_os_str().as_bytes())
}

/// Encode a path for Git without changing its spelling or base directory.
#[cfg(not(unix))]
fn path_to_git_bytes(path: &Path) -> std::io::Result<&[u8]> {
    path.to_str().map(str::as_bytes).ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("Path is not valid UTF-8: `{}`", path.display()),
        )
    })
}

/// Return newly staged paths under `root`, relative to `root` (the hook's working directory).
///
/// For example, with `root = <repo>/project`, `<repo>/project/file.rs` is returned as `file.rs`.
pub(crate) async fn staged_added_files(root: &Path) -> Result<Vec<PathBuf>, Error> {
    let output = git_cmd()?
        .current_dir(root)
        .arg("diff")
        .hidden_args(["--no-ext-diff"])
        .arg("--cached")
        .arg("--relative")
        .arg("--name-only")
        .arg("--diff-filter=A")
        .arg("-z")
        .check(true)
        .output()
        .await?;
    Ok(zsplit(&output.stdout)?)
}

/// Return changed paths relative to the repository root.
///
/// `root` selects the repository. Results cover the whole repository, even when
/// `root` is a subdirectory; each `FileEntry.path` retains its repository-relative prefix.
pub(crate) async fn changed_files(
    old: &str,
    new: &str,
    root: &Path,
    include_deleted: bool,
) -> Result<Vec<FileEntry>, Error> {
    // Try three-dot syntax first (merge-base diff), which works for commits
    let output = diff_files_cmd(include_deleted)?
        .current_dir(root)
        .arg(format!("{old}...{new}"))
        .check(false)
        .output()
        .await?;

    if output.status.success() {
        return parse_diff_files(&output.stdout);
    }

    // Fall back to two-dot syntax, which works with both commits and trees
    let output = diff_files_cmd(include_deleted)?
        .current_dir(root)
        .arg(format!("{old}..{new}"))
        .check(true)
        .output()
        .await?;
    parse_diff_files(&output.stdout)
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum FileMode {
    Regular,
    Executable,
    Symlink,
    Submodule,
}

pub(crate) struct FileEntry {
    pub(crate) path: PathBuf,
    pub(crate) deleted_mode: Option<FileMode>,
}

impl From<PathBuf> for FileEntry {
    fn from(path: PathBuf) -> Self {
        Self {
            path,
            deleted_mode: None,
        }
    }
}

fn diff_files_cmd(include_deleted: bool) -> Result<Cmd, Error> {
    let mut cmd = git_cmd()?;
    // Each raw record must have one path. Renames become additions and deletions,
    // so old paths can trigger hooks independently of Git's similarity heuristics.
    cmd.args(["diff", "--raw", "--no-renames", "--no-relative", "-z"])
        .hidden_args(["--no-ext-diff"]);
    if !include_deleted {
        cmd.arg("--diff-filter=d");
    }
    Ok(cmd)
}

/// Parse raw diff records without changing the paths' spelling or base directory.
/// Output from `diff_files_cmd` contains repository-relative paths.
fn parse_diff_files(output: &[u8]) -> Result<Vec<FileEntry>, Error> {
    let mut fields = output.split(|&byte| byte == b'\0');
    let mut files = Vec::new();
    while let Some(header) = fields.next().filter(|header| !header.is_empty()) {
        let deleted_mode = if header.ends_with(b" D") {
            Some(match header.split(|&byte| byte == b' ').next() {
                Some(b":100644") => FileMode::Regular,
                Some(b":100755") => FileMode::Executable,
                Some(b":120000") => FileMode::Symlink,
                Some(b":160000") => FileMode::Submodule,
                _ => return Err(Error::InvalidDiffFile),
            })
        } else {
            None
        };
        let path = fields
            .next()
            .filter(|path| !path.is_empty())
            .ok_or(Error::InvalidDiffFile)?;
        files.push(FileEntry {
            path: path_from_git_bytes(path)?,
            deleted_mode,
        });
    }
    Ok(files)
}

/// Return indexed paths matching `paths`, relative to `cwd`.
///
/// Relative input paths are also interpreted relative to `cwd`. Absolute input
/// paths still produce paths relative to `cwd`.
#[instrument(level = "trace", skip(paths))]
pub(crate) async fn ls_files<P>(
    cwd: &Path,
    paths: impl IntoIterator<Item = P>,
) -> Result<Vec<PathBuf>, Error>
where
    P: AsRef<Path>,
{
    let mut cmd = git_cmd()?;
    cmd.current_dir(cwd)
        .arg("--literal-pathspecs")
        .arg("ls-files")
        .arg("-z")
        .arg("--");
    for path in paths {
        cmd.arg(path.as_ref());
    }
    let output = cmd.check(true).output().await?;

    Ok(zsplit(&output.stdout)?)
}

/// Return the absolute hooks directory, including any `core.hooksPath` override.
pub(crate) async fn hooks_dir() -> Result<&'static Path> {
    let hooks_dir = &REPO.as_ref()?.hooks_dir;
    // `core.hooksPath=` is a particularly dangerous case: Git treats it as
    // configured, but resolves `--git-path hooks` to the current directory. If
    // we accepted that value, install/uninstall would write or remove hook
    // shims from the worktree root. Keep the explicit `core.hooksPath=.` case
    // working, but reject the empty-string variant.
    if hooks_dir.clean() == *crate::fs::CWD && config_value_is_empty(None, "core.hooksPath").await?
    {
        Err(Error::InvalidHooksPath(PathBuf::from(".")).into())
    } else {
        Ok(hooks_dir)
    }
}

/// Return staged paths relative to the repository root.
///
/// `root` selects the repository. Results cover the whole repository, even when
/// `root` is a subdirectory; each `FileEntry.path` retains its repository-relative prefix.
pub(crate) async fn staged_files(
    root: &Path,
    include_deleted: bool,
) -> Result<Vec<FileEntry>, Error> {
    let output = diff_files_cmd(include_deleted)?
        .current_dir(root)
        .arg("--cached")
        .check(true)
        .output()
        .await?;
    parse_diff_files(&output.stdout)
}

pub(crate) struct WorktreeStatus {
    pub(crate) unmerged: bool,
    pub(crate) unstaged: Vec<PathBuf>,
    pub(crate) intent_to_add: Vec<PathBuf>,
}

/// Check conflicts and unstaged changes together. Paths are relative to the repository root.
pub(crate) async fn worktree_status(cwd: &Path) -> Result<WorktreeStatus, Error> {
    let output = git_cmd()?
        .current_dir(cwd)
        .args([
            "diff",
            "--name-status",
            "-z",
            "--no-renames",
            "--no-relative",
            "--no-ext-diff",
            "--ignore-submodules",
        ])
        .check(true)
        .output()
        .await?;
    parse_worktree_status(&output.stdout)
}

fn parse_worktree_status(output: &[u8]) -> Result<WorktreeStatus, Error> {
    let mut status = WorktreeStatus {
        unmerged: false,
        unstaged: Vec::new(),
        intent_to_add: Vec::new(),
    };
    // Disabling renames gives each status exactly one NUL-terminated, unquoted path.
    let mut fields = output.split(|&byte| byte == b'\0');
    while let Some(change) = fields.next().filter(|field| !field.is_empty()) {
        let path = fields
            .next()
            .filter(|path| !path.is_empty())
            .ok_or(Error::InvalidDiffFile)?;
        let path = path_from_git_bytes(path)?;
        match change {
            b"U" => status.unmerged = true,
            // Unstaged additions are intent-to-add entries; untracked files are omitted.
            b"A" => status.intent_to_add.push(path.clone()),
            _ => {}
        }
        status.unstaged.push(path);
    }
    Ok(status)
}

/// Check for changes against `rev` anywhere in the repository containing `path`.
///
/// `path` selects the repository without limiting the check to that directory.
pub(crate) async fn has_diff(rev: &str, path: &Path) -> Result<bool> {
    let status = git_cmd()?
        .current_dir(path)
        .arg("diff")
        .hidden_args(["--no-ext-diff"])
        .arg("--quiet")
        .arg("--no-relative")
        .arg(rev)
        .check(false)
        .status()
        .await?;
    Ok(status.code() == Some(1))
}

pub(crate) fn is_in_merge_conflict() -> Result<bool> {
    let git_dir = git_dir()?;
    Ok(git_dir.join("MERGE_HEAD").try_exists()? && git_dir.join("MERGE_MSG").try_exists()?)
}

/// Return paths involved in the merge relative to the repository root.
///
/// `root` selects the repository. Both the diff and `MERGE_MSG` paths use the
/// repository root as their base, including when `root` is a subdirectory.
pub(crate) async fn conflicted_files(root: &Path) -> Result<Vec<PathBuf>> {
    let tree = git_cmd()?
        .current_dir(root)
        .arg("write-tree")
        .check(true)
        .output()
        .await?;

    let output = git_cmd()?
        .current_dir(root)
        .arg("diff")
        .arg("--name-only")
        .arg("--no-relative")
        .hidden_args(["--no-ext-diff"])
        .arg("-z")
        .arg("-m") // Show diffs for merge commits in the default format.
        .arg(str::from_utf8(&tree.stdout)?.trim_ascii())
        .arg("HEAD")
        .arg("MERGE_HEAD")
        .check(true)
        .output()
        .await?;

    Ok(zsplit(&output.stdout)?
        .into_iter()
        .chain(parse_merge_msg_for_conflicts().await?)
        .collect::<HashSet<PathBuf>>()
        .into_iter()
        .collect())
}

/// Return conflict paths recorded in `MERGE_MSG`, relative to the repository root.
async fn parse_merge_msg_for_conflicts() -> Result<Vec<PathBuf>> {
    let git_dir = git_dir()?;
    let merge_msg = git_dir.join("MERGE_MSG");
    let content = fs_err::tokio::read_to_string(&merge_msg).await?;
    let conflicts = content
        .lines()
        // Conflicted files start with tabs
        .filter(|line| line.starts_with('\t') || line.starts_with("#\t"))
        .map(|line| line.trim_start_matches('#').trim().to_string())
        .map(PathBuf::from)
        .collect();

    Ok(conflicts)
}

/// Return a patch for unstaged changes under the absolute directory `path`.
///
/// File names are repository-relative by default, or relative to `path` when
/// `diff.relative=true`. Git's patch prefixes are retained.
#[instrument(level = "trace")]
pub(crate) async fn diff_worktree(path: &Path) -> Result<Vec<u8>, Error> {
    let output = git_cmd()?
        .current_dir(path)
        .arg("diff")
        .hidden_args([
            "--full-index",
            "--no-ext-diff",
            "--no-textconv",
            "--ignore-submodules",
        ])
        .arg("--")
        .arg(path)
        // This diff is only used as a best-effort before/after snapshot of
        // hook changes. Some CI environments keep enough of `.git` for
        // `git ls-files` but omit blob objects needed by `git diff`; Git then
        // exits 128 on stderr with empty stdout. Keep comparing stdout in that
        // case so `run --all-files` can still run against the files Git can
        // enumerate.
        .check(false)
        .output()
        .await?;
    if !output.status.success() {
        debug!(
            status = %output.status,
            stderr = %String::from_utf8_lossy(&output.stderr),
            "Continuing with git diff stdout despite non-zero exit status"
        );
    }
    Ok(output.stdout)
}

/// Create a tree object from the current index.
///
/// The name of the new tree object is printed to standard output.
/// The index must be in a fully merged state.
pub(crate) fn write_tree() -> Result<String, Error> {
    let output = git_cmd()?.arg("write-tree").check(true).output_sync()?;
    Ok(str::from_utf8(output.stdout.trim_ascii())?.to_string())
}

impl Repo {
    /// Discover repository directories from an absolute `cwd`, storing absolute paths.
    #[instrument(level = "trace")]
    fn discover(cwd: &Path) -> Result<Self, Error> {
        let rev_parse = |args: &[&str]| -> Result<_, Error> {
            let mut cmd = git_cmd()?;
            cmd.current_dir(cwd)
                .arg("rev-parse")
                .args(args)
                // Keep diagnostics stable so discovery errors can be identified.
                .env(EnvVars::LC_ALL, "C");
            let output = cmd.inner.as_std_mut().output()?;
            // Preserve errors from an invalid GIT_DIR or .git file.
            if !output.status.success()
                && output
                    .stderr
                    .split(|&b| b == b'\n')
                    .any(|line| line.starts_with(b"fatal: not a git repository (or any"))
            {
                return Err(Error::NotRepository);
            }
            Ok((cmd, output))
        };

        // Keep --show-toplevel last: bare repositories can resolve the Git paths
        // even though querying their working tree fails.
        // Keep Git's default path format for hooks. With core.hooksPath=,
        // --path-format=absolute fails instead of returning the current directory.
        let (cmd, output) = rev_parse(&[
            "--absolute-git-dir",
            "--git-common-dir",
            "--git-path",
            "hooks",
            "--show-toplevel",
        ])?;
        let output = if output.stdout.is_empty() {
            cmd.check_output(output)?
        } else {
            output
        };
        let stdout = output.stdout.strip_suffix(b"\n").unwrap_or(&output.stdout);

        let (git_dir, common_dir, hooks_dir, root) = if output.status.success()
            && let Some((git_dir, common_dir, hooks_dir, root)) =
                stdout.split(|&b| b == b'\n').collect_tuple()
        {
            (
                path_from_git_bytes(git_dir)?,
                path_from_git_bytes(common_dir)?,
                path_from_git_bytes(hooks_dir)?,
                Ok(path_from_git_bytes(root)?),
            )
        } else {
            // rev-parse cannot NUL-delimit these paths. Query them separately
            // for paths containing newlines or a repository without a worktree.
            let path = |args: &[&str]| -> Result<PathBuf, Error> {
                let (cmd, output) = rev_parse(args)?;
                let output = cmd.check_output(output)?;
                let stdout = output.stdout.strip_suffix(b"\n").unwrap_or(&output.stdout);
                path_from_git_bytes(stdout).map_err(Error::from)
            };
            (
                path(&["--absolute-git-dir"])?,
                path(&["--git-common-dir"])?,
                path(&["--git-path", "hooks"])?,
                path(&["--show-toplevel"]),
            )
        };
        let state = Self {
            root: root.map(|root| dunce::canonicalize(&root).unwrap_or(root)),
            git_dir,
            common_dir: cwd.join(common_dir),
            hooks_dir: cwd.join(hooks_dir),
        };
        debug!(?state, "Git repository state");
        Ok(state)
    }
}

pub(crate) async fn init_repo(url: &str, path: &Path) -> Result<(), Error> {
    git_cmd()?
        // Unset `extensions.objectFormat` if set, just follow what hash the remote uses.
        .arg("-c")
        .arg("init.defaultObjectFormat=")
        .arg("init")
        .arg("--template=")
        .arg(path)
        .sanitize_git_repo_env()
        .check(true)
        .output()
        .await?;

    git_cmd()?
        .current_dir(path)
        .arg("remote")
        .arg("add")
        .arg("origin")
        .arg(url)
        .sanitize_git_repo_env()
        .check(true)
        .output()
        .await?;

    Ok(())
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum TerminalPrompt {
    Disabled,
    Enabled,
}

impl TerminalPrompt {
    fn env_value(self) -> &'static str {
        match self {
            Self::Disabled => "0",
            Self::Enabled => "1",
        }
    }
}

/// Return whether a git clone failure looks like an authentication error.
pub(crate) fn is_auth_error(err: &Error) -> bool {
    let Error::Command(process::Error::Status {
        error: StatusError {
            output: Some(output),
            ..
        },
        ..
    }) = err
    else {
        return false;
    };

    let error = String::from_utf8_lossy(&output.stderr).to_lowercase();

    [
        "terminal prompts disabled",
        "could not read username",
        "could not read password",
        "authentication failed",
        "http basic: access denied",
        "missing or invalid credentials",
        "could not authenticate to server",
    ]
    .iter()
    .any(|needle| error.contains(needle))
}

async fn shallow_clone(
    rev: &str,
    path: &Path,
    terminal_prompt: TerminalPrompt,
) -> Result<(), Error> {
    git_cmd()?
        .current_dir(path)
        .hidden_args(["-c", "protocol.version=2"])
        .arg("fetch")
        .arg("origin")
        .arg(rev)
        .arg("--depth=1")
        .sanitize_git_repo_env()
        .env(EnvVars::LC_ALL, "C")
        .env(EnvVars::GIT_TERMINAL_PROMPT, terminal_prompt.env_value())
        .check(true)
        .output()
        .await?;

    git_cmd()?
        .current_dir(path)
        .arg("checkout")
        .arg("FETCH_HEAD")
        .sanitize_git_repo_env()
        .env(EnvVars::PREK_INTERNAL__SKIP_POST_CHECKOUT, "1")
        .env(EnvVars::LC_ALL, "C")
        .env(EnvVars::GIT_TERMINAL_PROMPT, terminal_prompt.env_value())
        .check(true)
        .output()
        .await?;

    update_submodules(path, terminal_prompt, true).await?;

    Ok(())
}

async fn full_clone(rev: &str, path: &Path, terminal_prompt: TerminalPrompt) -> Result<(), Error> {
    git_cmd()?
        .current_dir(path)
        .arg("fetch")
        .arg("origin")
        .arg("--tags")
        .sanitize_git_repo_env()
        .env(EnvVars::LC_ALL, "C")
        .env(EnvVars::GIT_TERMINAL_PROMPT, terminal_prompt.env_value())
        .check(true)
        .output()
        .await?;

    git_cmd()?
        .current_dir(path)
        .arg("checkout")
        .arg(rev)
        .sanitize_git_repo_env()
        .env(EnvVars::PREK_INTERNAL__SKIP_POST_CHECKOUT, "1")
        .env(EnvVars::LC_ALL, "C")
        .env(EnvVars::GIT_TERMINAL_PROMPT, terminal_prompt.env_value())
        .check(true)
        .output()
        .await?;

    update_submodules(path, terminal_prompt, false).await?;

    Ok(())
}

async fn update_submodules(
    path: &Path,
    terminal_prompt: TerminalPrompt,
    shallow: bool,
) -> Result<(), Error> {
    if !should_update_submodules(path).await? {
        return Ok(());
    }

    let mut cmd = git_cmd()?;
    cmd.current_dir(path)
        .hidden_args(["-c", "protocol.version=2"]);
    cmd.arg("submodule")
        .arg("update")
        .arg("--init")
        .arg("--recursive");
    if shallow {
        cmd.arg("--depth=1");
    }
    cmd.sanitize_git_repo_env()
        .env(EnvVars::LC_ALL, "C")
        .env(EnvVars::GIT_TERMINAL_PROMPT, terminal_prompt.env_value())
        .check(true)
        .output()
        .await?;

    Ok(())
}

async fn should_update_submodules(path: &Path) -> Result<bool, Error> {
    if path.join(".gitmodules").try_exists()? {
        return Ok(true);
    }

    let output = git_cmd()?
        .current_dir(path)
        .arg("ls-files")
        .arg("-z")
        .arg("-s")
        .sanitize_git_repo_env()
        .env(EnvVars::LC_ALL, "C")
        .check(true)
        .output()
        .await?;

    Ok(output
        .stdout
        .split(|&byte| byte == b'\0')
        .any(|entry| entry.starts_with(b"160000 ")))
}

async fn clone_repo_attempt(
    rev: &str,
    path: &Path,
    terminal_prompt: TerminalPrompt,
) -> Result<(), Error> {
    if let Err(err) = shallow_clone(rev, path, terminal_prompt).await {
        if is_auth_error(&err) {
            warn!(?err, "Failed to shallow clone due to authentication error");
            return Err(err);
        }

        warn!(?err, "Failed to shallow clone, falling back to full clone");
        return full_clone(rev, path, terminal_prompt).await;
    }

    Ok(())
}

/// Clone a repository into an initialized destination with the requested terminal prompt mode.
pub(crate) async fn clone_repo(
    url: &str,
    rev: &str,
    path: &Path,
    terminal_prompt: TerminalPrompt,
) -> Result<(), Error> {
    init_repo(url, path).await?;
    clone_repo_attempt(rev, path, terminal_prompt).await
}

async fn config_value(scope: Option<&str>, key: &str) -> Result<Option<Vec<u8>>, Error> {
    let mut cmd = git_cmd()?;
    cmd.arg("config").arg("--includes");
    if let Some(scope) = scope {
        cmd.arg(scope);
    }
    let output = cmd
        .arg("--null")
        .arg("--get")
        .arg(key)
        .check(false)
        .output()
        .await?;
    Ok(output.status.success().then_some(output.stdout))
}

async fn has_config_value(scope: Option<&str>, key: &str) -> Result<bool, Error> {
    // An empty config value still counts as configured and can affect Git's
    // path resolution, e.g. `core.hooksPath=` makes `--git-path hooks`
    // resolve to the current directory.
    Ok(config_value(scope, key).await?.is_some())
}

async fn config_value_is_empty(scope: Option<&str>, key: &str) -> Result<bool, Error> {
    Ok(config_value(scope, key)
        .await?
        .as_deref()
        .is_some_and(|value| value.strip_suffix(b"\0").unwrap_or(value).is_empty()))
}

pub(crate) async fn has_hooks_path_set() -> Result<bool, Error> {
    has_config_value(None, "core.hooksPath").await
}

pub(crate) async fn has_repo_hooks_path_set() -> Result<bool, Error> {
    Ok(has_config_value(Some("--local"), "core.hooksPath").await?
        || has_config_value(Some("--worktree"), "core.hooksPath").await?)
}

/// Compute the file mode for a newly created file based on `core.sharedRepository`.
///
/// This mirrors the relevant parts of Git's `git_config_perm` in `setup.c`
/// and `calc_shared_perm` in `path.c`.
fn apply_shared_repository_file_mode(value: &str, mode: u32) -> Option<u32> {
    const PERM_GROUP: u32 = 0o660;
    const PERM_EVERYBODY: u32 = 0o664;

    fn apply(mode: u32, mut tweak: u32, replace: bool) -> u32 {
        // From Git's `calc_shared_perm`: if the original file is not
        // user-writable, do not introduce any write bits via the shared
        // repository permission tweak.
        if mode & 0o200 == 0 {
            tweak &= !0o222;
        }
        // Also from `calc_shared_perm`: for executable files, mirror read bits
        // into execute bits so an explicit mode like 0640 becomes 0750 when
        // applied to a 0755 file.
        if mode & 0o100 != 0 {
            tweak |= (tweak & 0o444) >> 2;
        }
        // Named values like `group` and `all` add permissions on top of the
        // existing mode, while octal values replace the low permission bits.
        if replace {
            (mode & !0o777) | tweak
        } else {
            mode | tweak
        }
    }

    let value = value.trim().to_ascii_lowercase();
    let (tweak, replace) = match value.as_str() {
        "" | "umask" | "false" | "no" | "off" | "0" => return None,
        "group" | "true" | "yes" | "on" | "1" => (PERM_GROUP, false),
        "all" | "world" | "everybody" | "2" => (PERM_EVERYBODY, false),
        // Parsed like Git's `git_config_perm`, which also accepts explicit
        // octal modes such as `0640`.
        _ => (u32::from_str_radix(&value, 8).ok()?, true),
    };

    // `git_config_perm` rejects explicit modes that do not grant user read/write.
    if replace && tweak & 0o600 != 0o600 {
        return None;
    }

    Some(apply(mode, tweak, replace))
}

/// Resolve the file mode implied by `core.sharedRepository` for a newly created file.
pub(crate) async fn shared_repository_file_mode(mode: u32) -> Result<u32> {
    let output = git_cmd()?
        .arg("config")
        .arg("--get")
        .arg("core.sharedRepository")
        .check(false)
        .output()
        .await?;
    if output.status.success() {
        let value = str::from_utf8(&output.stdout)?;
        Ok(apply_shared_repository_file_mode(value, mode).unwrap_or(mode))
    } else {
        Ok(mode)
    }
}

/// Return the input paths whose Git `filter` attribute is `lfs`.
///
/// Returned paths preserve their input spelling: relative paths are relative to
/// `current_dir`, and absolute paths stay absolute.
pub(crate) async fn lfs_files(
    current_dir: &Path,
    paths: &[&Path],
) -> Result<FxHashSet<PathBuf>, Error> {
    if paths.is_empty() {
        return Ok(FxHashSet::default());
    }

    let mut child = git_cmd()?
        .current_dir(current_dir)
        .arg("check-attr")
        .arg("filter")
        .arg("-z")
        .arg("--stdin")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .check(true)
        .spawn()?;

    let mut stdout = child.stdout.take().expect("failed to open stdout");
    let mut stdin = child.stdin.take().expect("failed to open stdin");

    let writer = async move {
        for path in paths {
            stdin.write_all(path_to_git_bytes(path)?).await?;
            stdin.write_all(b"\0").await?;
        }
        stdin.shutdown().await?;
        Ok::<(), std::io::Error>(())
    };
    let reader = async move {
        let mut out = Vec::new();
        stdout.read_to_end(&mut out).await?;
        Ok::<_, std::io::Error>(out)
    };

    let (read_result, _write_result) = tokio::try_join!(biased; reader, writer)?;

    let status = child.wait().await?;
    if !status.success() {
        return Err(Error::Command(process::Error::Status {
            command: "git check-attr -z filter --stdin".to_string(),
            error: StatusError {
                status,
                output: None,
            },
        }));
    }

    let mut lfs_files = FxHashSet::default();
    let mut it = read_result.split(|&byte| byte == b'\0');
    while let (Some(file), Some(_attr), Some(value)) = (it.next(), it.next(), it.next()) {
        if value == b"lfs" {
            lfs_files.insert(path_from_git_bytes(file)?);
        }
    }

    Ok(lfs_files)
}

/// Check if a git revision exists
pub(crate) async fn rev_exists(rev: &str) -> Result<bool, Error> {
    let output = git_cmd()?
        .arg("cat-file")
        // Exit with zero status if <object> exists and is a valid object.
        .arg("-e")
        .arg(rev)
        .check(false)
        .output()
        .await?;
    Ok(output.status.success())
}

/// Check if `ancestor` is an ancestor of `commit`.
pub(crate) async fn is_ancestor(ancestor: &str, commit: &str) -> Result<bool, Error> {
    let mut cmd = git_cmd()?;
    let status = cmd
        .arg("merge-base")
        .arg("--is-ancestor")
        .arg(ancestor)
        .arg(commit)
        .check(false)
        .status()
        .await?;

    if status.success() {
        return Ok(true);
    }
    if status.code() == Some(1) {
        return Ok(false);
    }

    cmd.check_status(status)?;
    Ok(false)
}

/// Return commits that are ancestors of the given commit but not in the specified remote.
pub(crate) async fn ancestors_not_in_remote(
    local_sha: &str,
    remote_name: &str,
) -> Result<Vec<String>, Error> {
    let output = git_cmd()?
        .arg("rev-list")
        .arg(local_sha)
        .arg("--topo-order")
        .arg("--reverse")
        .arg("--not")
        .arg(format!("--remotes={remote_name}"))
        .check(true)
        .output()
        .await?;
    Ok(str::from_utf8(&output.stdout)?
        .trim_ascii()
        .lines()
        .map(ToString::to_string)
        .collect())
}

/// Return root commits (commits with no parents) for the given commit.
pub(crate) async fn root_commits(local_sha: &str) -> Result<FxHashSet<String>, Error> {
    let output = git_cmd()?
        .arg("rev-list")
        .arg("--max-parents=0")
        .arg(local_sha)
        .check(true)
        .output()
        .await?;
    Ok(str::from_utf8(&output.stdout)?
        .trim_ascii()
        .lines()
        .map(ToString::to_string)
        .collect())
}

/// Return the parent commit of the given commit.
pub(crate) async fn parent_commit(commit: &str) -> Result<Option<String>, Error> {
    let output = git_cmd()?
        .arg("rev-parse")
        .arg(format!("{commit}^"))
        .check(false)
        .output()
        .await?;
    if output.status.success() {
        Ok(Some(
            str::from_utf8(&output.stdout)?.trim_ascii().to_string(),
        ))
    } else {
        Ok(None)
    }
}

/// Return absolute submodule paths by joining their configured paths to `git_root`.
/// `git_root` must be the absolute repository root.
#[instrument(level = "trace")]
pub(crate) fn list_submodules(git_root: &Path) -> Result<Vec<PathBuf>, Error> {
    if !git_root.join(".gitmodules").exists() {
        return Ok(vec![]);
    }

    let git = GIT.as_ref().map_err(|&e| Error::GitNotFound(e))?;
    let mut cmd = Command::new(git);
    let output = apply_git_work_tree(&mut cmd)
        .current_dir(git_root)
        .arg("config")
        .arg("--null")
        .arg("--file")
        .arg(".gitmodules")
        .arg("--get-regexp")
        .arg(r"^submodule\..*\.path$")
        .output()?;

    let mut submodules = Vec::new();
    // With `--null`, Git separates each key from its value with `\n` and records with NUL.
    for entry in output.stdout.split(|&byte| byte == b'\0') {
        let Some(separator) = entry.iter().position(|&byte| byte == b'\n') else {
            continue;
        };
        let path = &entry[separator + 1..];
        if path.is_empty() {
            continue;
        }
        submodules.push(git_root.join(path_from_git_bytes(path)?));
    }
    Ok(submodules)
}

#[cfg(test)]
mod tests {
    use std::assert_matches;
    use std::path::{Path, PathBuf};
    use std::process::Command;

    #[cfg(unix)]
    use crate::fs::PathClean;

    use super::zsplit;
    use super::{
        Error, GIT, TerminalPrompt, apply_shared_repository_file_mode, full_clone, init_repo,
        list_submodules, should_update_submodules, update_submodules,
    };
    #[cfg(unix)]
    use super::{Repo, lfs_files};
    use assert_cmd::assert::OutputAssertExt;

    fn run_git(path: &Path, args: &[&str]) {
        let mut command = Command::new(GIT.as_ref().unwrap());
        command.current_dir(path).args(args);

        command.assert().success();
    }

    #[tokio::test]
    async fn worktree_status_with_staged_and_unstaged_changes() -> anyhow::Result<()> {
        let tmp = tempfile::tempdir()?;
        let root = tmp.path();
        run_git(root, &["init"]);
        for name in ["staged.txt", "modified.txt", "deleted.txt"] {
            fs_err::write(root.join(name), "staged\n")?;
        }
        run_git(root, &["add", "."]);

        // A new repository has no HEAD but can still have a clean worktree.
        let status = super::worktree_status(root).await?;
        assert!(!status.unmerged);
        assert_eq!(status.unstaged, Vec::<PathBuf>::new());

        fs_err::write(root.join("modified.txt"), "unstaged\n")?;
        fs_err::remove_file(root.join("deleted.txt"))?;
        fs_err::write(root.join("intent.txt"), "")?;
        fs_err::write(root.join("untracked.txt"), "untracked\n")?;
        run_git(root, &["add", "--intent-to-add", "intent.txt"]);

        let status = super::worktree_status(root).await?;
        assert!(!status.unmerged);
        assert_eq!(
            status.unstaged,
            ["deleted.txt", "intent.txt", "modified.txt"].map(PathBuf::from)
        );
        assert_eq!(status.intent_to_add, [PathBuf::from("intent.txt")]);
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn worktree_status_preserves_unquoted_path_bytes() -> anyhow::Result<()> {
        use std::os::unix::ffi::OsStrExt as _;

        let status =
            super::parse_worktree_status(b"M\0 leading\nname-\xff.txt \0D\0deleted.txt\0")?;
        assert!(!status.unmerged);
        let paths = status
            .unstaged
            .iter()
            .map(|path| path.as_os_str().as_bytes())
            .collect::<Vec<_>>();
        assert_eq!(
            paths,
            [b" leading\nname-\xff.txt ".as_slice(), b"deleted.txt"]
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn repository_paths_preserve_special_characters() {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt as _;

        let tmp = tempfile::tempdir().unwrap();
        let names: &[&[u8]] = &[
            b"repo\nwith newline\n",
            b"repo with spaces ",
            #[cfg(not(target_os = "macos"))]
            b"repo-\xff",
        ];
        for name in names {
            let repo = tmp.path().join(OsStr::from_bytes(name));
            let subdir = repo.join("subdir");
            fs_err::create_dir_all(&subdir).unwrap();
            run_git(&repo, &["init"]);

            let state = Repo::discover(&subdir).unwrap();
            assert_eq!(state.root.unwrap(), dunce::canonicalize(&repo).unwrap());
            assert_eq!(
                state.git_dir,
                dunce::canonicalize(repo.join(".git")).unwrap()
            );
            assert_eq!(state.common_dir.clean(), repo.join(".git"));
            assert_eq!(state.hooks_dir.clean(), repo.join(".git/hooks"));

            for hooks_dir in ["custom\nhooks ", " "] {
                run_git(&repo, &["config", "core.hooksPath", hooks_dir]);
                let state = Repo::discover(&subdir).unwrap();
                assert_eq!(state.hooks_dir.clean(), repo.join(hooks_dir));
            }

            let bare = repo.join("bare\n");
            run_git(&repo, &["init", "--bare", "bare\n"]);
            let state = Repo::discover(&bare).unwrap();
            assert!(state.root.is_err());
            assert_eq!(state.git_dir, dunce::canonicalize(&bare).unwrap());
            assert_eq!(state.common_dir.clean(), bare);
            assert_eq!(state.hooks_dir.clean(), bare.join("hooks"));
        }
    }

    #[tokio::test]
    async fn should_update_submodules_when_gitmodules_exists() {
        let tmp = tempfile::tempdir().unwrap();
        run_git(tmp.path(), &["init"]);
        fs_err::write(tmp.path().join(".gitmodules"), "").unwrap();

        assert!(should_update_submodules(tmp.path()).await.unwrap());
    }

    #[tokio::test]
    async fn full_clone_skips_submodule_update_when_repo_has_no_submodules() {
        let remote = tempfile::tempdir().unwrap();
        run_git(remote.path(), &["init"]);
        fs_err::write(remote.path().join("file.txt"), "content\n").unwrap();
        run_git(remote.path(), &["add", "."]);
        run_git(
            remote.path(),
            &[
                "-c",
                "user.name=prek",
                "-c",
                "user.email=prek@example.com",
                "commit",
                "-m",
                "initial commit",
            ],
        );
        let output = Command::new(GIT.as_ref().unwrap())
            .current_dir(remote.path())
            .arg("rev-parse")
            .arg("HEAD")
            .output()
            .unwrap();
        assert!(output.status.success());
        let rev = String::from_utf8_lossy(&output.stdout);

        let clone = tempfile::tempdir().unwrap();
        init_repo(remote.path().to_str().unwrap(), clone.path())
            .await
            .unwrap();

        full_clone(rev.trim(), clone.path(), TerminalPrompt::Disabled)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn update_submodules_runs_when_gitlinks_exist_without_gitmodules() {
        let tmp = tempfile::tempdir().unwrap();
        run_git(tmp.path(), &["init"]);
        run_git(
            tmp.path(),
            &[
                "update-index",
                "--add",
                "--cacheinfo",
                "160000,1111111111111111111111111111111111111111,sub",
            ],
        );

        assert!(should_update_submodules(tmp.path()).await.unwrap());

        let err = update_submodules(tmp.path(), TerminalPrompt::Disabled, true)
            .await
            .unwrap_err();

        assert_matches!(err, Error::Command(_));
        let message = err.to_string();
        assert!(message.contains("submodule update --init --recursive"));
        assert!(message.contains("--depth=1"));

        let err = update_submodules(tmp.path(), TerminalPrompt::Disabled, false)
            .await
            .unwrap_err();

        assert_matches!(err, Error::Command(_));
        let message = err.to_string();
        assert!(message.contains("submodule update --init --recursive"));
        assert!(!message.contains("--depth=1"));
    }

    #[cfg(unix)]
    #[test]
    fn zsplit_preserves_non_utf8_paths() {
        use std::os::unix::ffi::OsStrExt as _;

        let paths = zsplit(b"normal.py\0bad-\xff.py\0").unwrap();

        assert_eq!(paths.len(), 2);
        assert_eq!(paths[0].as_os_str().as_bytes(), b"normal.py");
        assert_eq!(paths[1].as_os_str().as_bytes(), b"bad-\xff.py");
    }

    #[test]
    fn zsplit_preserves_leading_and_trailing_spaces() {
        let paths = zsplit(b" leading.py\0trailing.py \0").unwrap();

        assert_eq!(
            paths,
            vec![PathBuf::from(" leading.py"), PathBuf::from("trailing.py ")]
        );
    }

    #[cfg(unix)]
    #[test]
    fn diff_files_preserve_unusual_paths() -> anyhow::Result<()> {
        use std::os::unix::ffi::OsStrExt as _;

        let files = super::parse_diff_files(
            b":000000 100644 000000 abc123 A\0added.rs\0\
              :100644 000000 abc123 000000 D\0 leading\t\n\xff.rs\0\
              :100644 100644 abc123 def456 M\0modified.rs\0\
              :120000 000000 def456 000000 D\0link with spaces.rs\0",
        )?;

        assert_eq!(files.len(), 4);
        assert_eq!(files[0].path, Path::new("added.rs"));
        assert!(files[0].deleted_mode.is_none());
        assert_eq!(files[1].path.as_os_str().as_bytes(), b" leading\t\n\xff.rs");
        assert!(matches!(
            files[1].deleted_mode,
            Some(super::FileMode::Regular)
        ));
        assert_eq!(files[2].path, Path::new("modified.rs"));
        assert!(files[2].deleted_mode.is_none());
        assert_eq!(files[3].path, Path::new("link with spaces.rs"));
        assert!(matches!(
            files[3].deleted_mode,
            Some(super::FileMode::Symlink)
        ));
        Ok(())
    }

    #[test]
    fn list_submodules_preserves_spaces_in_paths() {
        let tmp = tempfile::tempdir().unwrap();
        run_git(tmp.path(), &["init"]);
        fs_err::write(
            tmp.path().join(".gitmodules"),
            "[submodule \"space\"]\n\tpath = modules/with space\n",
        )
        .unwrap();

        assert_eq!(
            list_submodules(tmp.path()).unwrap(),
            vec![tmp.path().join("modules/with space")]
        );
    }

    #[cfg(unix)]
    #[test]
    fn list_submodules_preserves_non_utf8_paths() {
        use std::os::unix::ffi::OsStrExt as _;

        let tmp = tempfile::tempdir().unwrap();
        run_git(tmp.path(), &["init"]);
        fs_err::write(
            tmp.path().join(".gitmodules"),
            b"[submodule \"raw\"]\n\tpath = modules/bad-\xff\n",
        )
        .unwrap();

        let submodules = list_submodules(tmp.path()).unwrap();

        assert_eq!(
            submodules[0]
                .strip_prefix(tmp.path())
                .unwrap()
                .as_os_str()
                .as_bytes(),
            b"modules/bad-\xff"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn lfs_files_preserves_non_utf8_paths() {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt as _;

        let tmp = tempfile::tempdir().unwrap();
        run_git(tmp.path(), &["init"]);
        fs_err::write(tmp.path().join(".gitattributes"), "* filter=lfs\n").unwrap();
        let path = Path::new(OsStr::from_bytes(b"bad-\xff.bin"));

        let files = lfs_files(tmp.path(), &[path]).await.unwrap();

        assert!(files.contains(path));
    }

    #[test]
    fn shared_repository_group_mode_matches_git_behavior() {
        for value in ["group", "true", "yes", "on", "1"] {
            assert_eq!(apply_shared_repository_file_mode(value, 0o755), Some(0o775));
        }
    }

    #[test]
    fn shared_repository_everybody_mode_matches_git_behavior() {
        for value in ["all", "world", "everybody", "2"] {
            assert_eq!(apply_shared_repository_file_mode(value, 0o755), Some(0o775));
        }
    }

    #[test]
    fn shared_repository_octal_mode_matches_git_behavior() {
        assert_eq!(
            apply_shared_repository_file_mode("0640", 0o644),
            Some(0o640)
        );
        assert_eq!(
            apply_shared_repository_file_mode("0640", 0o755),
            Some(0o750)
        );
    }

    #[test]
    fn shared_repository_umask_or_invalid_values_do_not_override_mode() {
        for value in ["", "umask", "false", "no", "off", "0", "invalid", "0400"] {
            assert_eq!(apply_shared_repository_file_mode(value, 0o755), None);
        }
    }
}