rattler_git 0.3.4

Git operations support for rattler based crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
/// Derived from `uv-git` implementation
/// Source: <https://github.com/astral-sh/uv/blob/4b8cc3e29e4c2a6417479135beaa9783b05195d3/crates/uv-git/src/git.rs>
/// This module represents all necessary git types and operations to interact with git repositories.
/// Example:
///   * `GitReference` that can represent a branch, tag, commit, or named ref.
///   * `GitRemote` that represents a remote repository and can be fetched somewhere on the local filesystem.
///   * `GitDatabase` and `GitRepository` that represents a local clone of a remote repository's database.
use std::{
    fmt::Display,
    path::{Path, PathBuf},
    process::Command,
    str::FromStr,
    sync::LazyLock,
};

use crate::LazyClient;
use reqwest::StatusCode;
use url::Url;

use crate::{
    GitError,
    sha::{GitOid, GitSha},
};

/// A file indicates that if present, `git reset` has been done and a repo
/// checkout is ready to go. See [`GitCheckout::reset`] for why we need this.
const CHECKOUT_READY_LOCK: &str = ".ok";
/// Content of [`CHECKOUT_READY_LOCK`] indicating that LFS was requested but
/// `git-lfs` was unavailable. Such a checkout is reusable while `git-lfs`
/// remains unavailable, but must be recreated once it becomes available.
const CHECKOUT_LFS_DEGRADED: &str = "lfs-degraded";
pub const GIT_DIR: &str = "GIT_DIR";
pub const GIT_TERMINAL_PROMPT: &str = "GIT_TERMINAL_PROMPT";
pub const GIT_LFS_SKIP_SMUDGE: &str = "GIT_LFS_SKIP_SMUDGE";

#[derive(Debug, thiserror::Error, Clone)]
pub enum GitBinaryError {
    #[error("Git executable not found. Ensure that Git is installed and available.")]
    GitNotFound,
    #[error(transparent)]
    Other(#[from] which::Error),
}

/// A global cache of the result of `which git`.
pub static GIT: LazyLock<Result<PathBuf, GitBinaryError>> = LazyLock::new(|| {
    which::which("git").map_err(|e| match e {
        which::Error::CannotFindBinaryPath => GitBinaryError::GitNotFound,
        e => GitBinaryError::Other(e),
    })
});

/// Cached `git lfs` invoker. Probes `git lfs version` once; on success
/// callers get a `GitLfs` whose [`GitLfs::cmd`] returns a fresh `Command`
/// pre-set to `git lfs ...` with the terminal prompt disabled. Mirrors uv's
/// `GIT_LFS` static.
pub static GIT_LFS: LazyLock<Result<GitLfs, GitBinaryError>> = LazyLock::new(GitLfs::probe);

/// Pre-configured `git lfs` command builder. Kept opaque so the git path is
/// resolved exactly once.
#[derive(Debug, Clone)]
pub struct GitLfs {
    git: PathBuf,
}

impl GitLfs {
    fn probe() -> Result<Self, GitBinaryError> {
        let git = GIT.as_ref().map_err(Clone::clone)?.clone();
        let ok = Command::new(&git)
            .args(["lfs", "version"])
            .env(GIT_TERMINAL_PROMPT, "0")
            .output()
            .is_ok_and(|o| o.status.success());
        if ok {
            Ok(Self { git })
        } else {
            Err(GitBinaryError::GitNotFound)
        }
    }

    /// Fresh `git lfs` command with `GIT_TERMINAL_PROMPT=0` already set.
    pub fn cmd(&self) -> Command {
        let mut c = Command::new(&self.git);
        c.arg("lfs").env(GIT_TERMINAL_PROMPT, "0");
        c
    }
}

/// Runs a prepared `git` command and returns its output, failing when git
/// exits with a non-zero status. Failed commands can write misleading output;
/// `git rev-parse`, for example, echoes unresolved refnames to stdout.
fn git_output(cmd: &mut Command) -> Result<std::process::Output, GitError> {
    let output = cmd.output()?;
    if !output.status.success() {
        let args = cmd
            .get_args()
            .map(|arg| arg.to_string_lossy())
            .collect::<Vec<_>>()
            .join(" ");
        return Err(GitError::Command(
            args,
            String::from_utf8_lossy(&output.stderr).trim().to_string(),
        ));
    }
    Ok(output)
}

/// Value for `GIT_LFS_SKIP_SMUDGE`: only an explicit `Some(true)` enables
/// smudging. The checkout's origin is the local database, which only contains
/// LFS objects when they were explicitly requested and fetched.
fn lfs_skip_smudge_env(lfs: Option<bool>) -> &'static str {
    if lfs == Some(true) { "0" } else { "1" }
}

/// Strategy when fetching refspecs for a [`GitReference`]
enum RefspecStrategy {
    // All refspecs should be fetched, if any fail then the fetch will fail
    All,
    // Stop after the first successful fetch, if none succeed then the fetch will fail
    First,
}

/// A reference to commit or commit-ish.
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    Hash,
    PartialOrd,
    Ord,
    serde::Serialize,
    serde::Deserialize,
    Default,
)]
#[serde(rename_all = "kebab-case")]
pub enum GitReference {
    /// A specific branch.
    Branch(String),
    /// A specific tag.
    Tag(String),
    /// A specific (short) commit.
    ShortCommit(String),
    /// From a reference that's ambiguously a branch or tag.
    BranchOrTag(String),
    /// From a reference that's ambiguously a short commit, a branch, or a tag.
    BranchOrTagOrCommit(String),
    /// From a named reference, like `refs/pull/493/head`.
    NamedRef(String),
    /// From a specific revision, using a full 40-character commit hash.
    FullCommit(String),
    /// The default branch of the repository, the reference named `HEAD`.
    #[default]
    DefaultBranch,
}

impl GitReference {
    /// Creates a [`GitReference`] from an arbitrary revision string, which could represent a
    /// branch, tag, commit, or named ref.
    pub fn from_rev(rev: String) -> Self {
        if rev.starts_with("refs/") {
            Self::NamedRef(rev)
        } else if GitReference::looks_like_commit_hash(&rev) {
            if rev.len() == 40 {
                Self::FullCommit(rev)
            } else {
                Self::BranchOrTagOrCommit(rev)
            }
        } else {
            Self::BranchOrTag(rev)
        }
    }

    /// Converts the [`GitReference`] to a `str`.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::Tag(rev)
            | Self::Branch(rev)
            | Self::ShortCommit(rev)
            | Self::BranchOrTag(rev)
            | Self::BranchOrTagOrCommit(rev)
            | Self::FullCommit(rev)
            | Self::NamedRef(rev) => Some(rev),
            Self::DefaultBranch => None,
        }
    }

    /// Converts the [`GitReference`] to a `str` that can be used as a revision.
    pub(crate) fn as_rev(&self) -> &str {
        match self {
            Self::Tag(rev)
            | Self::Branch(rev)
            | Self::ShortCommit(rev)
            | Self::BranchOrTag(rev)
            | Self::BranchOrTagOrCommit(rev)
            | Self::FullCommit(rev)
            | Self::NamedRef(rev) => rev,
            Self::DefaultBranch => "HEAD",
        }
    }

    /// Returns the precise [`GitSha`] of this reference, if it's a full commit.
    pub(crate) fn as_sha(&self) -> Option<GitSha> {
        if let Self::FullCommit(rev) = self {
            Some(GitSha::from_str(rev).expect("Full commit should be exactly 40 characters"))
        } else {
            None
        }
    }
    /// Resolves self to an object ID with objects the `repo` currently has.
    pub(crate) fn resolve(&self, repo: &GitRepository) -> Result<GitOid, GitError> {
        match self {
            // Resolve the commit pointed to by the tag.
            //
            // `^0` recursively peels away from the revision to the underlying commit object.
            // This also verifies that the tag indeed refers to a commit.
            Self::Tag(s) => repo.rev_parse(&format!("refs/remotes/origin/tags/{s}^0")),

            // Resolve the commit pointed to by the branch.
            Self::Branch(s) => repo.rev_parse(&format!("origin/{s}^0")),

            // Attempt to resolve the branch, then the tag.
            Self::BranchOrTag(s) => repo
                .rev_parse(&format!("origin/{s}^0"))
                .or_else(|_| repo.rev_parse(&format!("refs/remotes/origin/tags/{s}^0"))),

            // Attempt to resolve the commit, the tag then the branch.
            Self::BranchOrTagOrCommit(s) => repo
                .rev_parse(&format!("{s}^0"))
                .or_else(|_| repo.rev_parse(&format!("refs/remotes/origin/tags/{s}^0")))
                .or_else(|_| repo.rev_parse(&format!("origin/{s}^0"))),

            // We'll be using the HEAD commit.
            Self::DefaultBranch => repo.rev_parse("refs/remotes/origin/HEAD"),

            // Resolve a direct commit reference.
            Self::FullCommit(s) | Self::ShortCommit(s) | Self::NamedRef(s) => {
                repo.rev_parse(&format!("{s}^0"))
            }
        }
    }

    /// Whether a `rev` looks like a commit hash (ASCII hex digits).
    pub fn looks_like_commit_hash(rev: &str) -> bool {
        rev.len() >= 7 && rev.chars().all(|ch| ch.is_ascii_hexdigit())
    }

    /// Whether a `rev` looks like a commit hash (ASCII hex digits).
    pub fn looks_like_full_commit_hash(rev: &str) -> bool {
        rev.len() == 40 && rev.chars().all(|ch| ch.is_ascii_hexdigit())
    }

    pub fn is_default(&self) -> bool {
        matches!(self, Self::DefaultBranch)
    }
}

impl Display for GitReference {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str().unwrap_or("HEAD"))
    }
}

/// A remote repository. It gets cloned into a local [`GitDatabase`].
#[derive(PartialEq, Clone, Debug)]
pub(crate) struct GitRemote {
    /// URL to a remote repository.
    url: Url,
}

impl GitRemote {
    /// Creates an instance for a remote repository URL.
    pub(crate) fn new(url: &Url) -> Self {
        Self { url: url.clone() }
    }

    /// Fetches and checkouts to a reference or a revision from this remote
    /// into a local path.
    ///
    /// This ensures that it gets the up-to-date commit when a named reference
    /// is given (tag, branch, refs/*). Thus, network connection is involved.
    ///
    /// When `locked_rev` is provided, it takes precedence over `reference`.
    ///
    /// If we have a previous instance of [`GitDatabase`] then fetch into that
    /// if we can. If that can successfully load our revision then we've
    /// populated the database with the latest version of `reference`, so
    /// return that database and the rev we resolve to.
    pub(crate) fn checkout(
        &self,
        into: &Path,
        db: Option<GitDatabase>,
        reference: &GitReference,
        locked_rev: Option<GitOid>,
        client: &LazyClient,
        options: &CheckoutOptions,
    ) -> Result<(GitDatabase, GitOid), GitError> {
        let locked_ref = locked_rev.map(|oid| GitReference::FullCommit(oid.to_string()));
        let reference = locked_ref.as_ref().unwrap_or(reference);
        if let Some(mut db) = db {
            fetch(&mut db.repo, self.url.as_str(), reference, client)?;

            let resolved_commit_hash = match locked_rev {
                Some(rev) => db.contains(rev).then_some(rev),
                None => reference.resolve(&db.repo).ok(),
            };

            if let Some(rev) = resolved_commit_hash {
                let ready = (options.lfs == Some(true))
                    .then(|| {
                        maybe_fetch_lfs(&mut db.repo, self.url.as_str(), rev, &options.lfs_filter)
                    })
                    .flatten();
                return Ok((db.with_lfs_ready(ready), rev));
            }
        }

        // Otherwise start from scratch to handle corrupt git repositories.
        // After our fetch (which is interpreted as a clone now) we do the same
        // resolution to figure out what we cloned.
        if into.exists() {
            fs_err::remove_dir_all(into)?;
        }

        fs_err::create_dir_all(into)?;
        let mut repo = GitRepository::init(into)?;
        fetch(&mut repo, self.url.as_str(), reference, client)?;
        let rev = match locked_rev {
            Some(rev) => rev,
            None => reference.resolve(&repo).map_err(|err| {
                let mut repository = self.url.clone();
                let _ = repository.set_password(None);
                let _ = repository.set_username("");
                GitError::ReferenceNotFound {
                    reference: reference.as_rev().to_string(),
                    repository: repository.to_string(),
                    source: Box::new(err),
                }
            })?,
        };

        let ready = (options.lfs == Some(true))
            .then(|| maybe_fetch_lfs(&mut repo, self.url.as_str(), rev, &options.lfs_filter))
            .flatten();

        Ok((
            GitDatabase {
                repo,
                lfs_ready: None,
            }
            .with_lfs_ready(ready),
            rev,
        ))
    }

    /// Creates a [`GitDatabase`] of this remote at `db_path`.
    #[allow(clippy::unused_self)]
    pub(crate) fn db_at(&self, db_path: &Path) -> Result<GitDatabase, GitError> {
        let repo = GitRepository::open(db_path)?;
        Ok(GitDatabase {
            repo,
            lfs_ready: None,
        })
    }

    pub fn url(&self) -> &Url {
        &self.url
    }
}

/// Path filters passed to Git LFS. Values use the comma-separated gitignore
/// pattern syntax accepted by `git lfs fetch --include/--exclude`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct LfsFilter {
    /// Only materialize LFS objects whose paths match these patterns.
    pub include: Option<String>,
    /// Do not materialize LFS objects whose paths match these patterns.
    pub exclude: Option<String>,
}

impl LfsFilter {
    pub fn is_empty(&self) -> bool {
        self.include.is_none() && self.exclude.is_none()
    }

    fn configure_git(&self, command: &mut Command) {
        if let Some(include) = &self.include {
            command.arg("-c").arg(format!("lfs.fetchinclude={include}"));
        }
        if let Some(exclude) = &self.exclude {
            command.arg("-c").arg(format!("lfs.fetchexclude={exclude}"));
        }
    }

    fn configure_lfs_fetch(&self, command: &mut Command) {
        if let Some(include) = &self.include {
            command.arg(format!("--include={include}"));
        }
        if let Some(exclude) = &self.exclude {
            command.arg(format!("--exclude={exclude}"));
        }
    }
}

/// Options controlling checkout behavior (submodules, LFS, etc.).
#[derive(Debug, Clone)]
pub struct CheckoutOptions {
    /// Whether to recursively initialize and update submodules.
    pub update_submodules: bool,

    /// Git LFS handling, tri-state:
    /// * `Some(true)`: fetch LFS objects into the database (`git lfs fetch`)
    ///   and run the smudge filter during checkout so pointer files are
    ///   materialised into real content.
    /// * `Some(false)`: force-skip the smudge filter (`GIT_LFS_SKIP_SMUDGE=1`)
    ///   so checkouts always contain pointer files. Callers can handle LFS
    ///   themselves afterwards.
    /// * `None`: LFS is not requested and the smudge filter is skipped. This
    ///   differs from `Some(false)` only in preserving the caller's preference.
    pub lfs: Option<bool>,

    /// Optional path filters limiting which LFS objects are fetched and
    /// materialized. Filters have no effect unless `lfs == Some(true)`.
    pub lfs_filter: LfsFilter,
}

impl Default for CheckoutOptions {
    fn default() -> Self {
        Self {
            update_submodules: true,
            // Skipping the smudge filter is the safe default: the checkout's
            // origin points at the local database, which has no LFS objects
            // unless `lfs == Some(true)` fetched them.
            lfs: Some(false),
            lfs_filter: LfsFilter::default(),
        }
    }
}

/// A local clone of a remote repository's database. Multiple [`GitCheckout`]s
/// can be cloned from a single [`GitDatabase`].
pub(crate) struct GitDatabase {
    /// Underlying Git repository instance for this database.
    repo: GitRepository,
    /// `Some(true)` = fsck passed, `Some(false)` = fsck failed or git-lfs
    /// missing, `None` = LFS never requested.
    lfs_ready: Option<bool>,
}

impl GitDatabase {
    pub(crate) fn lfs_ready(&self) -> Option<bool> {
        self.lfs_ready
    }

    /// Builder: set [`Self::lfs_ready`] and return self. Mirrors uv's
    /// `with_lfs_ready` so callers can chain after a fetch or cache hit.
    #[must_use]
    pub(crate) fn with_lfs_ready(mut self, value: Option<bool>) -> Self {
        self.lfs_ready = value;
        self
    }

    /// True if the LFS objects reachable from `revision` are already present
    /// and valid in this database (i.e. `git lfs fsck --objects` passes).
    /// Used to decide whether a cached DB satisfies an LFS-aware request.
    pub(crate) fn contains_lfs_artifacts(&self, revision: GitOid, filter: &LfsFilter) -> bool {
        // A filtered fetch is cheap when its objects are already cached and is
        // the authoritative way to apply Git LFS's path matching semantics.
        // Do not claim a DB-only cache hit for filtered requests.
        filter.is_empty() && self.repo.lfs_fsck_objects(revision)
    }

    /// Checkouts to a revision at `destination` from this database.
    pub(crate) fn copy_to(
        &self,
        rev: GitOid,
        destination: &Path,
        source_url: &Url,
        options: &CheckoutOptions,
    ) -> Result<GitCheckout, GitError> {
        // If the existing checkout exists, and it is fresh, use it.
        // A non-fresh checkout can happen if the checkout operation was
        // interrupted. In that case, the checkout gets deleted and a new
        // clone is created.
        let checkout = match GitRepository::open(destination)
            .ok()
            .map(|repo| GitCheckout::new(rev, repo))
            .filter(|checkout| checkout.is_fresh(GIT_LFS.is_err()))
        {
            Some(co) => co,
            None => GitCheckout::clone_into(destination, self, rev, source_url, options)?,
        };
        Ok(checkout)
    }

    /// Get a short OID for a `revision`, usually 7 chars or more if ambiguous.
    pub(crate) fn to_short_id(&self, revision: GitOid) -> Result<String, GitError> {
        let output = git_output(
            Command::new(GIT.as_ref().map_err(Clone::clone)?)
                .arg("rev-parse")
                .arg("--short")
                .arg(revision.as_str())
                .current_dir(&self.repo.path),
        )?;

        let mut result = String::from_utf8(output.stdout)?;

        result.truncate(result.trim_end().len());
        tracing::debug!("result of short id is  {:?}", result);
        Ok(result)
    }

    /// Checks if `oid` resolves to a commit in this database.
    pub(crate) fn contains(&self, oid: GitOid) -> bool {
        self.repo.rev_parse(&format!("{oid}^0")).is_ok()
    }
}

/// A local Git repository.
pub(crate) struct GitRepository {
    /// Path to the underlying Git repository on the local filesystem.
    path: PathBuf,
}

impl GitRepository {
    /// Opens an existing Git repository at `path`.
    ///
    /// Returns an error if the path is not a valid git repository (e.g., missing .git directory,
    /// corrupted repository, etc.)
    pub(crate) fn open(path: &Path) -> Result<GitRepository, GitError> {
        // Make sure there is a Git repository at the specified path.
        // Use --git-dir to verify this is a valid git repository.
        let output = Command::new(GIT.as_ref().map_err(Clone::clone)?)
            .args(["rev-parse", "--git-dir"])
            .current_dir(path)
            .output()?;

        if !output.status.success() {
            return Err(GitError::InvalidRepository(path.to_path_buf()));
        }

        Ok(GitRepository {
            path: path.to_path_buf(),
        })
    }

    /// Initializes a Git repository at `path`.
    fn init(path: &Path) -> Result<GitRepository, GitError> {
        // Initialize the repository.
        git_output(
            Command::new(GIT.as_ref().map_err(Clone::clone)?)
                .arg("init")
                .current_dir(path),
        )?;

        Ok(GitRepository {
            path: path.to_path_buf(),
        })
    }

    /// Parses the object ID of the given `refname`.
    fn rev_parse(&self, refname: &str) -> Result<GitOid, GitError> {
        let result = git_output(
            Command::new(GIT.as_ref().map_err(Clone::clone)?)
                .arg("rev-parse")
                .arg(refname)
                .current_dir(&self.path),
        )?;

        let mut result = String::from_utf8(result.stdout)?;

        result.truncate(result.trim_end().len());
        result.parse().map_err(GitError::OidParse)
    }

    /// `git lfs fsck --objects <revision>`. Returns `true` iff fsck passes;
    /// any failure (missing git-lfs, non-zero exit) is warned and returns
    /// `false`. Informational — see [`GitDatabase::lfs_ready`].
    fn lfs_fsck_objects(&self, revision: GitOid) -> bool {
        let Ok(lfs) = GIT_LFS.as_ref() else {
            return false;
        };
        let output = lfs
            .cmd()
            .arg("fsck")
            .arg("--objects")
            .arg(revision.as_str())
            .env_remove(GIT_DIR)
            .current_dir(&self.path)
            .output();
        match output {
            Ok(out) if out.status.success() => true,
            Ok(out) => {
                tracing::warn!(
                    "`git lfs fsck` reported problems for {revision} in {}: {}",
                    self.path.display(),
                    String::from_utf8_lossy(&out.stderr).trim()
                );
                false
            }
            Err(err) => {
                tracing::warn!(
                    "failed to run `git lfs fsck` for {revision} in {}: {err}",
                    self.path.display()
                );
                false
            }
        }
    }
}

/// A local checkout of a particular revision from a [`GitRepository`].
pub(crate) struct GitCheckout {
    /// The git revision this checkout is for.
    revision: GitOid,
    /// Underlying Git repository instance for this checkout.
    repo: GitRepository,
}

impl GitCheckout {
    /// Creates an instance of [`GitCheckout`]. This doesn't imply the checkout
    /// is done. Use [`GitCheckout::is_fresh`] to check.
    ///
    /// * The `repo` will be the checked out Git repository.
    fn new(revision: GitOid, repo: GitRepository) -> Self {
        Self { revision, repo }
    }

    /// Clone a repo for a `revision` into a local path from a `database`.
    /// This is a filesystem-to-filesystem clone.
    fn clone_into(
        into: &Path,
        database: &GitDatabase,
        revision: GitOid,
        source_url: &Url,
        options: &CheckoutOptions,
    ) -> Result<Self, GitError> {
        tracing::debug!("cloning into {:?} from {:?}", database.repo.path, into);
        let dirname = into.parent().expect("into path must have a parent");
        fs_err::create_dir_all(dirname)?;
        if into.exists() {
            fs_err::remove_dir_all(into)?;
        }

        // Perform a local clone of the repository, which will attempt to use
        // hardlinks to set up the repository. This should speed up the clone operation
        // quite a bit if it works.
        //
        // The smudge filter is controlled by `options.lfs`: when LFS was not
        // requested we skip it, because the database the clone originates
        // from has no LFS objects. When LFS was requested, the objects were
        // fetched into the database beforehand, so smudging can succeed.
        let mut clone_cmd = Command::new(GIT.as_ref().map_err(Clone::clone)?);
        if options.lfs == Some(true) {
            options.lfs_filter.configure_git(&mut clone_cmd);
        }
        clone_cmd
            .arg("clone")
            .arg("--local")
            // Make sure to pass the local file path and not a file://... url. If given a url,
            // Git treats the repository as a remote origin and gets confused because we don't
            // have a HEAD checked out.
            .arg(dunce::simplified(&database.repo.path).display().to_string())
            .arg(dunce::simplified(into).display().to_string());
        clone_cmd.env(GIT_LFS_SKIP_SMUDGE, lfs_skip_smudge_env(options.lfs));
        let output = git_output(&mut clone_cmd)?;

        tracing::debug!("output after cloning {:?}", output);

        let repo = GitRepository::open(into)?;
        let checkout = GitCheckout::new(revision, repo);
        checkout.reset(source_url, options)?;
        Ok(checkout)
    }

    /// Checks if the `HEAD` points to the expected revision and its ready
    /// marker is usable. An LFS-degraded checkout is only reusable while the
    /// current process still has no usable `git-lfs`.
    fn is_fresh(&self, accept_lfs_degraded: bool) -> bool {
        match self.repo.rev_parse("HEAD") {
            Ok(id) if id == self.revision => {
                // See comments in reset() for why we check this
                match fs_err::read_to_string(self.repo.path.join(CHECKOUT_READY_LOCK)) {
                    Ok(contents) => contents != CHECKOUT_LFS_DEGRADED || accept_lfs_degraded,
                    Err(_) => false,
                }
            }
            _ => false,
        }
    }

    /// This performs `git reset --hard` to the revision of this checkout, with
    /// additional interrupt protection by a dummy file [`CHECKOUT_READY_LOCK`].
    ///
    /// If we're interrupted while performing a `git reset` (e.g., we die
    /// because of a signal) Cargo needs to be sure to try to check out this
    /// repo again on the next go-round.
    ///
    /// To enable this we have a dummy file in our checkout, [`.ok`],
    /// which if present means that the repo has been successfully reset and is
    /// ready to go. Hence if we start to do a reset, we make sure this file
    /// *doesn't* exist, and then once we're done we create the file.
    ///
    /// [`.ok`]: CHECKOUT_READY_LOCK
    fn reset(&self, source_url: &Url, options: &CheckoutOptions) -> Result<(), GitError> {
        let ok_file = self.repo.path.join(CHECKOUT_READY_LOCK);
        let _ = fs_err::remove_file(&ok_file);

        tracing::debug!("reset {} to {}", self.repo.path.display(), self.revision);

        let skip_smudge = lfs_skip_smudge_env(options.lfs);

        // Perform the hard reset. Configure the filter explicitly when LFS is
        // enabled so materialization does not depend on a prior global
        // `git lfs install`.
        let mut reset_cmd = Command::new(GIT.as_ref().map_err(Clone::clone)?);
        if options.lfs == Some(true) && GIT_LFS.is_ok() {
            options.lfs_filter.configure_git(&mut reset_cmd);
            reset_cmd
                .arg("-c")
                .arg("filter.lfs.smudge=git-lfs smudge -- %f")
                .arg("-c")
                .arg("filter.lfs.process=git-lfs filter-process")
                .arg("-c")
                .arg("filter.lfs.required=true");
        }
        reset_cmd
            .arg("reset")
            .arg("--hard")
            .arg(self.revision.as_str())
            .current_dir(&self.repo.path)
            .env(GIT_LFS_SKIP_SMUDGE, skip_smudge);
        git_output(&mut reset_cmd)?;

        if options.update_submodules {
            // The checkout's origin points to the local bare cache database
            // (set by `git clone --local`). Submodules with relative URLs
            // would resolve against that local path and fail. Resolve them
            // against the real source URL first.
            resolve_submodule_urls(&self.repo.path, source_url)?;

            // Update submodules (`git submodule update --recursive`).
            // Submodules may contain LFS files too, so apply the same smudge
            // policy. Allow file:// protocol so local clones and file-based
            // submodule URLs work on modern Git (>= 2.38.1).
            let mut submodule_cmd = Command::new(GIT.as_ref().map_err(Clone::clone)?);
            if options.lfs == Some(true) {
                options.lfs_filter.configure_git(&mut submodule_cmd);
            }
            submodule_cmd
                .args(["-c", "protocol.file.allow=always"])
                .arg("submodule")
                .arg("update")
                .arg("--recursive")
                .arg("--init")
                .current_dir(&self.repo.path);
            submodule_cmd.env(GIT_LFS_SKIP_SMUDGE, skip_smudge);
            git_output(&mut submodule_cmd)?;
        }

        if options.lfs == Some(true) && GIT_LFS.is_err() {
            fs_err::write(ok_file, CHECKOUT_LFS_DEGRADED)?;
        } else {
            fs_err::File::create(ok_file)?;
        }
        Ok(())
    }
}

/// Attempts to fetch the given git `reference` for a Git repository.
///
/// This is the main entry for git clone/fetch. It does the following:
///
/// * Turns [`GitReference`] into refspecs accordingly.
/// * Dispatches `git fetch` using the git CLI.
///
/// The `remote_url` argument is the git remote URL where we want to fetch from.
pub(crate) fn fetch(
    repo: &mut GitRepository,
    remote_url: &str,
    reference: &GitReference,
    client: &LazyClient,
) -> Result<(), GitError> {
    let oid_to_fetch = match github_fast_path(repo, remote_url, reference, client) {
        Ok(FastPathRev::UpToDate) => return Ok(()),
        Ok(FastPathRev::NeedsFetch(rev)) => Some(rev),
        Ok(FastPathRev::Indeterminate) => None,
        Err(e) => {
            tracing::debug!("failed to check github fast path {:?}", e);
            None
        }
    };

    // Translate the reference desired here into an actual list of refspecs
    // which need to get fetched. Additionally record if we're fetching tags.
    let mut refspecs = Vec::new();
    let mut tags = false;
    let mut refspec_strategy = RefspecStrategy::All;
    // The `+` symbol on the refspec means to allow a forced (fast-forward)
    // update which is needed if there is ever a force push that requires a
    // fast-forward.
    match reference {
        // For branches and tags we can fetch simply one reference and copy it
        // locally, no need to fetch other branches/tags.
        GitReference::Branch(branch) => {
            refspecs.push(format!("+refs/heads/{branch}:refs/remotes/origin/{branch}"));
        }

        GitReference::Tag(tag) => {
            refspecs.push(format!("+refs/tags/{tag}:refs/remotes/origin/tags/{tag}"));
        }

        GitReference::BranchOrTag(branch_or_tag) => {
            refspecs.push(format!(
                "+refs/heads/{branch_or_tag}:refs/remotes/origin/{branch_or_tag}"
            ));
            refspecs.push(format!(
                "+refs/tags/{branch_or_tag}:refs/remotes/origin/tags/{branch_or_tag}"
            ));
            refspec_strategy = RefspecStrategy::First;
        }

        // For ambiguous references, we can fetch the exact commit (if known); otherwise,
        // we fetch all branches and tags.
        GitReference::ShortCommit(branch_or_tag_or_commit)
        | GitReference::BranchOrTagOrCommit(branch_or_tag_or_commit) => {
            // The `oid_to_fetch` is the exact commit we want to fetch. But it could be the exact
            // commit of a branch or tag. We should only fetch it directly if it's the exact commit
            // of a short commit hash.
            if let Some(oid_to_fetch) =
                oid_to_fetch.filter(|oid| is_short_hash_of(branch_or_tag_or_commit, *oid))
            {
                refspecs.push(format!("+{oid_to_fetch}:refs/commit/{oid_to_fetch}"));
            } else {
                // We don't know what the rev will point to. To handle this
                // situation we fetch all branches and tags, and then we pray
                // it's somewhere in there.
                refspecs.push(String::from("+refs/heads/*:refs/remotes/origin/*"));
                refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
                tags = true;
            }
        }

        GitReference::DefaultBranch => {
            refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
        }

        GitReference::NamedRef(rev) => {
            refspecs.push(format!("+{rev}:{rev}"));
        }

        GitReference::FullCommit(rev) => {
            if let Some(oid_to_fetch) = oid_to_fetch {
                refspecs.push(format!("+{oid_to_fetch}:refs/commit/{oid_to_fetch}"));
            } else {
                // There is a specific commit to fetch and we will do so in shallow-mode only
                // to not disturb the previous logic.
                // Note that with typical settings for shallowing, we will just fetch a single `rev`
                // as single commit.
                // The reason we write to `refs/remotes/origin/HEAD` is that it's of special significance
                // when during `GitReference::resolve()`, but otherwise it shouldn't matter.
                refspecs.push(format!("+{rev}:refs/remotes/origin/HEAD"));
            }
        }
    }

    tracing::debug!(
        "Performing a Git fetch for: {remote_url} with repo path {}",
        repo.path.display()
    );
    let result = match refspec_strategy {
        RefspecStrategy::All => fetch_with_cli(repo, remote_url, refspecs.as_slice(), tags),
        RefspecStrategy::First => {
            // Try each refspec
            let mut errors = refspecs
                .iter()
                .map_while(|refspec| {
                    let fetch_result =
                        fetch_with_cli(repo, remote_url, std::slice::from_ref(refspec), tags);

                    // Stop after the first success and log failures
                    match fetch_result {
                        Err(ref err) => {
                            tracing::debug!("failed to fetch refspec `{refspec}`: {err}");
                            Some(fetch_result)
                        }
                        Ok(()) => None,
                    }
                })
                .collect::<Vec<_>>();

            if errors.len() == refspecs.len() {
                if let Some(result) = errors.pop() {
                    // Use the last error for the message
                    result
                } else {
                    // Can only occur if there were no refspecs to fetch
                    Ok(())
                }
            } else {
                Ok(())
            }
        }
    };
    tracing::debug!("fetched with cli {:?}", result);
    result
}

/// Best-effort `fetch_lfs`: warns and continues on missing git-lfs or fetch
/// failure. Returns the value to record in [`GitDatabase::lfs_ready`].
fn maybe_fetch_lfs(
    repo: &mut GitRepository,
    url: &str,
    revision: GitOid,
    filter: &LfsFilter,
) -> Option<bool> {
    let lfs = if let Ok(lfs) = GIT_LFS.as_ref() {
        lfs
    } else {
        tracing::warn!(
            "`git-lfs` is not installed; skipping LFS fetch for {url}. \
             Install git-lfs to download LFS-tracked files."
        );
        return Some(false);
    };
    match fetch_lfs(lfs, repo, url, revision, filter) {
        Ok(fsck_ok) => Some(fsck_ok),
        Err(err) => {
            tracing::warn!("failed to fetch LFS objects for {url} at {revision}: {err}");
            Some(false)
        }
    }
}

/// `git lfs fetch <url> <revision>` then `git lfs fsck --objects <revision>`.
/// Scoping to the resolved rev (not just HEAD) means LFS objects on feature
/// branches and tags are fetched too. Returns the fsck result; the bool of
/// `Ok` is `true` if fsck passes. `GIT_LFS_SKIP_SMUDGE` is removed from the
/// env so an inherited value can't suppress smudge mid-fetch.
fn fetch_lfs(
    lfs: &GitLfs,
    repo: &mut GitRepository,
    url: &str,
    revision: GitOid,
    filter: &LfsFilter,
) -> Result<bool, GitError> {
    let remote = lfs_remote_url(url);
    tracing::debug!("fetching LFS objects for {remote} at {revision}");

    let mut command = lfs.cmd();
    command.arg("fetch");
    filter.configure_lfs_fetch(&mut command);
    let output = command
        .arg(&*remote)
        .arg(revision.as_str())
        .env_remove(GIT_DIR)
        .env_remove(GIT_LFS_SKIP_SMUDGE)
        .current_dir(&repo.path)
        .output()?;
    if !output.status.success() {
        let stderr = String::from_utf8(output.stderr)?;
        return Err(GitError::LfsFetch(remote.into_owned(), stderr));
    }
    tracing::debug!("git lfs fetch output: {:?}", output);

    // `git lfs fsck` supports exclusions but not includes. A successful
    // filtered fetch is therefore the best available validation for a subset;
    // unfiltered requests retain the full object-integrity check.
    Ok(!filter.is_empty() || repo.lfs_fsck_objects(revision))
}

/// The remote to pass to `git lfs fetch`. git-lfs' standalone file transfer
/// agent only accepts a literal `file://` URL (or the name of a configured
/// remote) — plain local paths fail with "missing protocol" and Windows
/// drive-letter paths (`D:/repo`, parsed with a single-letter URL scheme)
/// fail with "no valid file:// URLs found". Convert such local paths to
/// canonical `file://` URLs; everything else passes through unchanged.
fn lfs_remote_url(url: &str) -> std::borrow::Cow<'_, str> {
    if let Ok(parsed) = Url::parse(url)
        && parsed.scheme().len() == 1
        && parsed.scheme().chars().all(|c| c.is_ascii_alphabetic())
        && let Ok(file_url) = Url::from_file_path(Path::new(url))
    {
        return std::borrow::Cow::Owned(file_url.to_string());
    }
    std::borrow::Cow::Borrowed(url)
}

/// Attempts to use `git` CLI installed on the system to fetch a repository.
fn fetch_with_cli(
    repo: &mut GitRepository,
    url: &str,
    refspecs: &[String],
    tags: bool,
) -> Result<(), GitError> {
    let mut cmd = Command::new(GIT.as_ref().map_err(Clone::clone)?);
    cmd.arg("fetch");
    if tags {
        cmd.arg("--tags");
    }
    cmd.arg("--force") // handle force pushes
        .arg("--update-head-ok") // see discussion in #2078
        .arg(url)
        .args(refspecs)
        //     // If cargo is run by git (for example, the `exec` command in `git
        //     // rebase`), the GIT_DIR is set by git and will point to the wrong
        //     // location (this takes precedence over the cwd). Make sure this is
        //     // unset so git will look at cwd for the repo.
        .env_remove(GIT_DIR)
        // Disable interactive credential prompts so an unreachable or
        // non-existent remote fails fast instead of hanging waiting for
        // input on the controlling TTY.
        .env(GIT_TERMINAL_PROMPT, "0")
        .current_dir(&repo.path);

    // // We capture the output to avoid streaming it to the user's console during clones.
    // // The required `on...line` callbacks currently do nothing.
    // // The output appears to be included in error messages by default.
    let output = cmd.output()?;
    if !output.status.success() {
        let stderr = String::from_utf8(output.stderr)?;
        return Err(GitError::Fetch(url.to_string(), stderr));
    }
    tracing::debug!("git fetch output: {:?}", output);
    Ok(())
}

/// The result of GitHub fast path check. See [`github_fast_path`] for more.
enum FastPathRev {
    /// The local rev (determined by `reference.resolve(repo)`) is already up to
    /// date with what this rev resolves to on GitHub's server.
    UpToDate,
    /// The following SHA must be fetched in order for the local rev to become
    /// up-to-date.
    NeedsFetch(GitOid),
    /// Don't know whether local rev is up-to-date. We'll fetch _all_ branches
    /// and tags from the server and see what happens.
    Indeterminate,
}

/// Attempts GitHub's special fast path for testing if we've already got an
/// up-to-date copy of the repository.
///
/// Updating the index is done pretty regularly so we want it to be as fast as
/// possible. For registries hosted on GitHub (like the crates.io index) there's
/// a fast path available to use[^1] to tell us that there's no updates to be
/// made.
///
/// Note that this function should never cause an actual failure because it's
/// just a fast path. As a result, a caller should ignore `Err` returned from
/// this function and move forward on the normal path.
///
/// [^1]: <https://developer.github.com/v3/repos/commits/#get-the-sha-1-of-a-commit-reference>
fn github_fast_path(
    repo: &mut GitRepository,
    url: &str,
    reference: &GitReference,
    client: &LazyClient,
) -> Result<FastPathRev, GitError> {
    let url = Url::parse(url)?;
    if !is_github(&url) {
        return Ok(FastPathRev::Indeterminate);
    }

    let local_object = reference.resolve(repo).ok();
    let github_branch_name = match reference {
        GitReference::Branch(branch) => branch,
        GitReference::Tag(tag) => tag,
        GitReference::BranchOrTag(branch_or_tag) => branch_or_tag,
        GitReference::DefaultBranch => "HEAD",
        GitReference::NamedRef(rev) => rev,
        GitReference::FullCommit(rev)
        | GitReference::ShortCommit(rev)
        | GitReference::BranchOrTagOrCommit(rev) => {
            // `revparse_single` (used by `resolve`) is the only way to turn
            // short hash -> long hash, but it also parses other things,
            // like branch and tag names, which might coincidentally be
            // valid hex.
            //
            // We only return early if `rev` is a prefix of the object found
            // by `revparse_single`. Don't bother talking to GitHub in that
            // case, since commit hashes are permanent. If a commit with the
            // requested hash is already present in the local clone, its
            // contents must be the same as what is on the server for that
            // hash.
            //
            // If `rev` is not found locally by `revparse_single`, we'll
            // need GitHub to resolve it and get a hash. If `rev` is found
            // but is not a short hash of the found object, it's probably a
            // branch and we also need to get a hash from GitHub, in case
            // the branch has moved.
            if let Some(ref local_object) = local_object
                && is_short_hash_of(rev, *local_object)
            {
                return Ok(FastPathRev::UpToDate);
            }
            rev
        }
    };

    // This expects GitHub urls in the form `github.com/user/repo` and nothing
    // else
    let mut pieces = url.path_segments().ok_or_else(|| {
        GitError::GitUrlFormat(
            url.as_str().to_string(),
            "no path segments on url".to_string(),
        )
    })?;
    let username = pieces.next().ok_or_else(|| {
        GitError::GitUrlFormat(
            url.as_str().to_string(),
            "couldn't find username or organisation name".to_string(),
        )
    })?;
    let repository = pieces.next().ok_or_else(|| {
        GitError::GitUrlFormat(
            url.as_str().to_string(),
            "couldn't find repository name".to_string(),
        )
    })?;
    if pieces.next().is_some() {
        return Err(GitError::GitUrlFormat(
            url.as_str().to_string(),
            "too many segments in the url".to_string(),
        ));
    }

    // Trim off the `.git` from the repository, if present, since that's
    // optional for GitHub and won't work when we try to use the API as well.
    let repository = repository.strip_suffix(".git").unwrap_or(repository);

    let url = format!(
        "https://api.github.com/repos/{username}/{repository}/commits/{github_branch_name}"
    );

    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;

    runtime.block_on(async move {
        tracing::debug!("Attempting GitHub fast path for: {url}");
        let mut request = client
            .client()
            .get(&url)
            .header("Accept", "application/vnd.github.3.sha");
        if let Some(local_object) = local_object {
            request = request.header("If-None-Match", local_object.to_string());
        }
        let mut request = request.build()?;
        if !request.headers().contains_key("User-Agent") {
            request
                .headers_mut()
                .insert("User-Agent", "rattler".parse().unwrap());
        }

        let response = client.client().execute(request).await?;
        let response_code = response.status();
        if response_code == StatusCode::NOT_MODIFIED {
            Ok(FastPathRev::UpToDate)
        } else if response_code == StatusCode::OK {
            let oid_to_fetch = response.text().await?.parse()?;
            Ok(FastPathRev::NeedsFetch(oid_to_fetch))
        } else {
            // The fast path is only an optimization; any non-success status
            // (404 for a missing repo, 422 when the rev cannot be resolved,
            // 403 when rate-limited, 5xx, etc.) just falls back to a normal
            // git fetch.
            tracing::debug!("GitHub fast path returned {response_code}, falling back to git fetch");
            Ok(FastPathRev::Indeterminate)
        }
    })
}

/// Whether a `url` is one from GitHub.
fn is_github(url: &Url) -> bool {
    url.host_str() == Some("github.com")
}

/// Whether `rev` is a shorter hash of `oid`.
fn is_short_hash_of(rev: &str, oid: GitOid) -> bool {
    let long_hash = oid.to_string();
    match long_hash.get(..rev.len()) {
        Some(truncated_long_hash) => truncated_long_hash.eq_ignore_ascii_case(rev),
        None => false,
    }
}

/// Resolve a relative submodule URL against a base URL.
///
/// This mirrors Cargo's `absolute_submodule_url`: if the base URL is
/// parseable (http, https, file, ssh, etc.) we use `Url::join` which
/// handles `../` normalization. The base URL gets a trailing `/`
/// appended to its path so that `join` resolves relative to the
/// directory rather than replacing the last path segment.
pub fn resolve_relative_url(base: &Url, relative: &str) -> Result<String, GitError> {
    let mut base = base.clone();

    // Ensure the base path ends with `/` so `join` treats it as a directory.
    if !base.path().ends_with('/') {
        base.set_path(&format!("{}/", base.path()));
    }

    let resolved = base.join(relative)?;
    Ok(resolved.to_string())
}

/// Resolve relative submodule URLs against the source URL.
///
/// Reads `.gitmodules`, finds entries with relative URLs (`./` or `../`),
/// resolves them against `source_url`, and writes the absolute URL into
/// the repo-level git config so that `git submodule update` uses it.
fn resolve_submodule_urls(repo_path: &Path, source_url: &Url) -> Result<(), GitError> {
    let gitmodules_path = repo_path.join(".gitmodules");
    if !gitmodules_path.exists() {
        return Ok(());
    }

    // List all submodule URLs from .gitmodules
    let output = Command::new(GIT.as_ref().map_err(Clone::clone)?)
        .current_dir(repo_path)
        .args([
            "config",
            "--file",
            ".gitmodules",
            "--get-regexp",
            r"submodule\..*\.url",
        ])
        .output()?;

    if !output.status.success() {
        // No submodule entries — nothing to resolve
        return Ok(());
    }

    let stdout = String::from_utf8(output.stdout)?;
    for line in stdout.lines() {
        // Each line is: submodule.<name>.url <url>
        let Some((key, submodule_url)) = line.split_once(' ') else {
            continue;
        };

        if !submodule_url.starts_with("./") && !submodule_url.starts_with("../") {
            continue;
        }

        let resolved = resolve_relative_url(source_url, submodule_url)?;

        // Write the resolved URL into the repo config (not .gitmodules).
        // `git submodule update --init` reads from the repo config,
        // falling back to .gitmodules only for `submodule init`.
        let output = Command::new(GIT.as_ref().map_err(Clone::clone)?)
            .current_dir(repo_path)
            .args(["config", key, &resolved])
            .output()?;

        if !output.status.success() {
            let stderr = String::from_utf8(output.stderr)?;
            return Err(GitError::SubmoduleUrl(key.to_string(), stderr));
        }
    }

    Ok(())
}

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

    #[test]
    fn test_lfs_remote_url() {
        // A Windows drive-letter path parses as a URL with a single-letter
        // scheme; git-lfs' standalone file agent needs it as a `file://`
        // URL. (`Url::from_file_path` only accepts absolute paths, so this
        // conversion naturally only happens on Windows hosts.)
        if cfg!(windows) {
            assert_eq!(
                lfs_remote_url("D:/a/work/lfs_repo"),
                "file:///D:/a/work/lfs_repo"
            );
        } else {
            assert_eq!(lfs_remote_url("D:/a/work/lfs_repo"), "D:/a/work/lfs_repo");
        }

        // file:// URLs and remote URLs pass through unchanged.
        assert_eq!(
            lfs_remote_url("file:///repos/sample"),
            "file:///repos/sample"
        );
        assert_eq!(
            lfs_remote_url("https://github.com/owner/repo.git"),
            "https://github.com/owner/repo.git"
        );
        assert_eq!(
            lfs_remote_url("ssh://git@github.com/owner/repo.git"),
            "ssh://git@github.com/owner/repo.git"
        );
    }

    #[test]
    fn test_resolve_relative_url() {
        let base = Url::parse("https://github.com/owner/repo.git").unwrap();

        assert_eq!(
            resolve_relative_url(&base, "../sibling.git").unwrap(),
            "https://github.com/owner/sibling.git"
        );

        assert_eq!(
            resolve_relative_url(&base, "./child.git").unwrap(),
            "https://github.com/owner/repo.git/child.git"
        );

        let file_base = Url::parse("file:///tmp/repos/main.git").unwrap();
        assert_eq!(
            resolve_relative_url(&file_base, "../sub.git").unwrap(),
            "file:///tmp/repos/sub.git"
        );
    }

    #[test]
    fn test_resolve_submodule_urls_no_gitmodules() {
        let tmp = tempfile::tempdir().unwrap();
        // No .gitmodules file — should succeed as a no-op
        let url = Url::parse("https://github.com/owner/repo.git").unwrap();
        resolve_submodule_urls(tmp.path(), &url).unwrap();
    }

    /// Integration test: create a git repo with a `.gitmodules` containing
    /// relative URLs, then verify that `resolve_submodule_urls` rewrites
    /// them to absolute URLs in the repo config.
    #[test]
    fn test_resolve_submodule_urls_rewrites_relative() {
        let tmp = tempfile::tempdir().unwrap();
        let repo_path = tmp.path().join("repo");

        // Initialize a git repo
        Command::new("git")
            .args(["init"])
            .arg(&repo_path)
            .output()
            .unwrap();

        // Write a .gitmodules file with relative URLs
        let gitmodules = r#"
[submodule "sub-relative"]
	path = sub-relative
	url = ../sibling.git
[submodule "sub-absolute"]
	path = sub-absolute
	url = https://github.com/other/absolute.git
[submodule "sub-child"]
	path = sub-child
	url = ./child.git
"#;
        std::fs::write(repo_path.join(".gitmodules"), gitmodules.trim_ascii_start()).unwrap();

        let source_url = Url::from_file_path(&repo_path).unwrap();
        resolve_submodule_urls(&repo_path, &source_url).unwrap();

        // Verify relative URLs were resolved
        let output = Command::new("git")
            .current_dir(&repo_path)
            .args(["config", "submodule.sub-relative.url"])
            .output()
            .unwrap();
        let expected_sibling = Url::from_file_path(tmp.path().join("sibling.git")).unwrap();
        assert_eq!(
            String::from_utf8(output.stdout).unwrap().trim(),
            expected_sibling.as_str()
        );

        let output = Command::new("git")
            .current_dir(&repo_path)
            .args(["config", "submodule.sub-child.url"])
            .output()
            .unwrap();
        let expected_child = Url::from_file_path(repo_path.join("child.git")).unwrap();
        assert_eq!(
            String::from_utf8(output.stdout).unwrap().trim(),
            expected_child.as_str()
        );

        // Verify absolute URL was NOT written to repo config
        let output = Command::new("git")
            .current_dir(&repo_path)
            .args(["config", "submodule.sub-absolute.url"])
            .output()
            .unwrap();
        // Should fail (exit code 1) because absolute URLs are not rewritten
        assert!(!output.status.success());
    }
}