girt 0.6.4

An incremental, idiomatic Rust implementation of Git
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
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
//! Fetching from and pushing to configured remotes.
//!
//! This module is the ordinary entry point for talking to another repository. It resolves a
//! named remote's URL through the repository configuration (`insteadOf`, `pushurl`, protocol
//! policy), selects the transport (local path, HTTP(S) or SSH), handles credentials the way Git
//! does, and drives the lower-level [`crate::fetch`] and [`crate::push`] workflows to completion.
//!
//! Process state that Git consults (environment variables such as `GIT_SSH_COMMAND`, proxies,
//! `HOME`) is passed explicitly as an [`Environment`]; use [`Environment::from_process`] for the
//! usual behavior.
//!
//! ```no_run
//! use girt::Repository;
//! use girt::transfer::{Environment, FetchOptions, NoCallbacks};
//!
//! let repo = Repository::open("project")?;
//! let options = FetchOptions::new(["+refs/heads/*:refs/remotes/origin/*"]).prune(true);
//! let outcome = repo.fetch(
//!     "origin",
//!     &options,
//!     &Environment::from_process(),
//!     &mut NoCallbacks,
//! )?;
//! println!("{} references updated", outcome.updated.len());
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

#![warn(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::unreachable,
    clippy::indexing_slicing,
    reason = "parses untrusted repository or network input (#103)"
)]

use std::collections::{BTreeMap, BTreeSet};
use std::ffi::{OsStr, OsString};
use std::num::NonZeroU32;
use std::ops::ControlFlow;
#[cfg(feature = "http")]
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;

use crate::fetch::{
    FetchLimits, FetchRequest, FetchUpdateKind, FetchUpdateLimits, FetchWorkflowError,
    KnownHistory, RemoteHead,
};
use crate::push::{PreparedPush, PushCommand, PushFailure, PushLimits, PushReport};
use crate::refs::{RefName, Reflog};
use crate::remote::{Destination, Direction, Protocol, ProtocolEnvironment, Refspecs, Remote};
use crate::transport::TransportControl;
use crate::{ObjectId, Repository};

/// A snapshot of the environment variables Git consults while transferring.
///
/// Transfers never read the process environment themselves. Child processes (SSH, credential
/// helpers) receive exactly these variables.
#[derive(Clone, Default)]
pub struct Environment {
    vars: BTreeMap<OsString, OsString>,
    current_dir: Option<PathBuf>,
}

impl std::fmt::Debug for Environment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Values can contain secrets such as tokens.
        f.debug_struct("Environment")
            .field("names", &self.vars.keys().collect::<Vec<_>>())
            .finish()
    }
}

impl Environment {
    /// Captures the current process environment and working directory.
    pub fn from_process() -> Self {
        let mut environment: Self = std::env::vars_os().collect();
        environment.current_dir = std::env::current_dir().ok();
        environment
    }

    /// Sets the directory that relative local remote paths are resolved against, as Git resolves
    /// them against its working directory.
    pub fn with_current_dir(mut self, directory: impl Into<PathBuf>) -> Self {
        self.current_dir = Some(directory.into());
        self
    }

    /// Returns a variable's value.
    pub fn get(&self, name: &str) -> Option<&OsStr> {
        self.vars.get(OsStr::new(name)).map(OsString::as_os_str)
    }

    /// Sets a variable, returning `self` for chaining.
    pub fn with(mut self, name: impl Into<OsString>, value: impl Into<OsString>) -> Self {
        self.vars.insert(name.into(), value.into());
        self
    }

    /// Removes a variable, returning `self` for chaining.
    pub fn without(mut self, name: impl AsRef<OsStr>) -> Self {
        self.vars.remove(name.as_ref());
        self
    }

    fn bytes(&self, name: &str) -> Option<Vec<u8>> {
        self.get(name)
            .map(|value| value.as_encoded_bytes().to_vec())
    }

    #[cfg(feature = "http")]
    fn string(&self, name: &str) -> Option<String> {
        self.get(name).and_then(OsStr::to_str).map(str::to_owned)
    }
}

impl<K: Into<OsString>, V: Into<OsString>> FromIterator<(K, V)> for Environment {
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        Self {
            vars: iter
                .into_iter()
                .map(|(name, value)| (name.into(), value.into()))
                .collect(),
            current_dir: None,
        }
    }
}

/// A value requested from the user while authenticating.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum CredentialPrompt {
    /// The username for the URL.
    Username,
    /// The password or token for the URL.
    Password,
}

/// Hooks for reporting progress and interacting with the user during a transfer.
///
/// All methods have no-op defaults. Callbacks run on the calling thread and should return
/// promptly.
pub trait TransferCallbacks {
    /// Receives a progress or informational message from the remote, as raw bytes. Messages may
    /// end in `\r` (to be overwritten) or `\n`.
    fn remote_message(&mut self, _message: &[u8]) {}

    /// Receives native local pack-validation work on the calling thread.
    ///
    /// Completion describes validation, not installation or reference publication. No pack means
    /// no snapshots. Counts may restart on a retry. Observers must return promptly; panics unwind
    /// before this validation phase publishes incoming storage. Network transport messages retain
    /// their existing byte callback; this observer currently covers native local transfers only.
    fn validation_progress(&mut self, _progress: crate::fetch::ValidationProgress) {}

    /// Receives diagnostic output of a local transport process, such as SSH's standard error
    /// (e.g. host key warnings or authentication failures), as raw bytes.
    fn transport_message(&mut self, _message: &[u8]) {}

    /// Asks the user for a credential after configured helpers didn't supply one. Returns
    /// `None` to cancel. `url` has no embedded password.
    fn credential(&mut self, _url: &str, _prompt: CredentialPrompt) -> Option<Vec<u8>> {
        None
    }
}

/// Callbacks that report nothing and never prompt.
#[derive(Clone, Copy, Debug, Default)]
pub struct NoCallbacks;

impl TransferCallbacks for NoCallbacks {}

/// What to fetch and how to update local references.
#[derive(Clone, Debug)]
pub struct FetchOptions {
    refspecs: Vec<Vec<u8>>,
    depth: Option<NonZeroU32>,
    prune: bool,
    tag_namespaces: Vec<RefName>,
    reflog: Option<(crate::Signature, Vec<u8>)>,
}

impl FetchOptions {
    /// Fetches with the given refspecs (positive, negative `^src`, or globs).
    pub fn new<I, S>(refspecs: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<[u8]>,
    {
        Self {
            refspecs: refspecs
                .into_iter()
                .map(|refspec| refspec.as_ref().to_vec())
                .collect(),
            depth: None,
            prune: false,
            tag_namespaces: Vec::new(),
            reflog: None,
        }
    }

    /// Limits history to `depth` commits from each fetched tip, creating or adjusting shallow
    /// boundaries.
    pub fn depth(mut self, depth: Option<NonZeroU32>) -> Self {
        self.depth = depth;
        self
    }

    /// Deletes destinations whose sources no longer exist on the remote, including destinations
    /// of exact refspecs whose source is missing.
    pub fn prune(mut self, prune: bool) -> Self {
        self.prune = prune;
        self
    }

    /// Permits destinations below `namespace` that hold tags (e.g. a per-remote tag namespace).
    ///
    /// Such destinations are force-updatable and pruned like remote-tracking references.
    pub fn tag_namespace(mut self, namespace: RefName) -> Self {
        self.tag_namespaces.push(namespace);
        self
    }

    /// Records reflog entries by `committer` with `message` for changed references. Without
    /// this, no reflog entries are written.
    pub fn reflog(mut self, committer: crate::Signature, message: impl Into<Vec<u8>>) -> Self {
        self.reflog = Some((committer, message.into()));
        self
    }
}

/// One local reference changed by a fetch.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FetchedRef {
    /// Local reference name.
    pub name: RefName,
    /// Previous value, if the reference existed.
    pub old: Option<ObjectId>,
    /// New value, or `None` if the reference was pruned.
    pub new: Option<ObjectId>,
}

/// The result of a successful fetch.
#[derive(Clone, Debug, Default)]
pub struct FetchOutcome {
    /// Local references that were created, updated or pruned.
    pub updated: Vec<FetchedRef>,
    /// Exact (non-glob) refspec sources that the remote doesn't have.
    pub missing_sources: Vec<Vec<u8>>,
}

/// Options for [`Repository::push`].
#[derive(Clone, Debug, Default)]
pub struct PushOptions {
    push_options: Vec<Vec<u8>>,
    identity: Option<crate::Signature>,
    compression: Option<crate::PackCompression>,
}

impl PushOptions {
    /// Selects compression for a configured push, replacing the default bounded delta policy.
    ///
    /// Both policies can reuse eligible stored compressed entries and internal deltas. Ordinary
    /// compression disables new internal/external delta search. Delta search respects its bounds;
    /// packs offering advertised receiver candidates additionally cap output depth at one.
    ///
    /// ```
    /// let _options =
    ///     girt::transfer::PushOptions::default().compression(girt::PackCompression::Ordinary);
    /// ```
    pub fn compression(mut self, compression: crate::PackCompression) -> Self {
        self.compression = Some(compression);
        self
    }

    /// Identity for reflog entries written in a local destination repository.
    pub fn identity(mut self, identity: crate::Signature) -> Self {
        self.identity = Some(identity);
        self
    }

    /// Sends server-specific `--push-option` values (e.g. Gerrit review settings).
    pub fn push_option(mut self, option: impl Into<Vec<u8>>) -> Self {
        self.push_options.push(option.into());
        self
    }
}

/// How the remote's HEAD is configured, as advertised.
pub type RemoteHeadState = RemoteHead;

/// A transfer failed.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum TransferError {
    /// No remote with this name, or it has no URL for the direction.
    #[error("no such remote: {0}")]
    NoSuchRemote(String),
    /// The remote configuration is invalid.
    #[error("invalid remote configuration: {0}")]
    Configuration(String),
    /// The URL uses a transport girt doesn't support (e.g. `git://` or a remote helper).
    #[error("unsupported transport for remote {0}")]
    UnsupportedTransport(String),
    /// Authentication failed or was cancelled.
    #[error("authentication failed for {0}")]
    Authentication(String),
    /// A fetch failed before any local change.
    #[error(transparent)]
    Fetch(Box<FetchWorkflowError>),
    /// A fetch installed objects but failed to update some references.
    #[error(transparent)]
    FetchFinish(Box<crate::fetch::FetchFinishError>),
    /// A push failed; see [`crate::push::PushError`] for whether it may have taken effect.
    #[error(transparent)]
    Push(Box<crate::push::PushError>),
    /// Reading local objects or references failed.
    #[error(transparent)]
    Local(Box<dyn std::error::Error + Send + Sync>),
}

impl TransferError {
    fn local(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
        Self::Local(error.into())
    }
}

/// A resolved connection target.
enum Endpoint {
    Local(PathBuf),
    #[cfg(feature = "http")]
    Http(Box<Http>),
    #[cfg(all(feature = "ssh", any(target_os = "macos", target_os = "linux")))]
    Ssh(Box<crate::transport::ssh::SshRemote>),
}

#[cfg(feature = "http")]
struct Http {
    settings_config: crate::Config,
    remote_name: Vec<u8>,
    destination: Destination,
    environment: crate::transport::http::HttpEnvironment,
    helpers: Vec<crate::remote::CredentialHelper>,
    /// URL for prompts, without userinfo.
    display_url: String,
}

#[cfg(feature = "http")]
impl Http {
    fn remote(
        &self,
        credentials: Option<crate::remote::CredentialSession>,
    ) -> Result<crate::transport::http::HttpRemote, TransferError> {
        let settings = crate::transport::http::HttpSettings::resolve_for_remote(
            &self.settings_config,
            &self.remote_name,
            &self.destination,
            &self.environment,
        )
        .map_err(|error| TransferError::Configuration(error.to_string()))?;
        let remote = crate::transport::http::HttpRemote::configured(settings)
            .map_err(|error| TransferError::Configuration(error.to_string()))?;
        match credentials {
            Some(session) => remote
                .with_credentials(session)
                .map_err(|error| TransferError::Configuration(error.to_string())),
            None => Ok(remote),
        }
    }

    fn credentials(
        &self,
        callbacks: &mut dyn TransferCallbacks,
    ) -> Result<crate::remote::CredentialSession, TransferError> {
        let url = url_parts(self.destination.bytes())
            .ok_or_else(|| TransferError::Configuration("invalid HTTP URL".into()))?;
        let context = crate::remote::CredentialContext {
            protocol: url.scheme.into_bytes(),
            host: url.authority.into_bytes(),
            path: Some(url.path.trim_matches('/').as_bytes().to_vec()),
            use_http_path: false,
        };
        let display_url = self.display_url.clone();
        let mut prompt = |prompt: crate::remote::Prompt| {
            let prompt = match prompt {
                crate::remote::Prompt::Username => CredentialPrompt::Username,
                crate::remote::Prompt::Password => CredentialPrompt::Password,
            };
            callbacks.credential(&display_url, prompt)
        };
        crate::remote::CredentialSession::fill(
            &self.settings_config,
            context,
            &self.helpers,
            Some(&mut prompt),
            &AtomicBool::new(false),
            None,
        )
        .map_err(|_| TransferError::Authentication(self.display_url.clone()))
    }
}

#[cfg(feature = "http")]
struct UrlParts {
    scheme: String,
    authority: String,
    path: String,
}

/// Splits `scheme://[user@]host[:port]/path` without percent decoding.
#[cfg(feature = "http")]
fn url_parts(bytes: &[u8]) -> Option<UrlParts> {
    let text = std::str::from_utf8(bytes).ok()?;
    let (scheme, rest) = text.split_once("://")?;
    let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
    let authority = authority
        .rsplit_once('@')
        .map_or(authority, |(_, host)| host);
    Some(UrlParts {
        scheme: scheme.to_ascii_lowercase(),
        authority: authority.to_owned(),
        path: path.to_owned(),
    })
}

#[cfg(feature = "http")]
fn redacted_url(bytes: &[u8]) -> String {
    let text = String::from_utf8_lossy(bytes);
    match url_parts(bytes) {
        Some(parts) => format!("{}://{}{}", parts.scheme, parts.authority, parts.path),
        None => text.into_owned(),
    }
}

/// Quotes `value` for a POSIX shell.
#[cfg(any(
    feature = "http",
    all(feature = "ssh", any(target_os = "macos", target_os = "linux"))
))]
fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

/// Finds `program` in the environment's `PATH`.
#[cfg(any(
    feature = "http",
    all(feature = "ssh", any(target_os = "macos", target_os = "linux"))
))]
fn find_program(environment: &Environment, program: &str) -> Option<PathBuf> {
    let path = environment.get("PATH")?;
    std::env::split_paths(path)
        .map(|dir| dir.join(program))
        .find(|candidate| candidate.is_file())
}

/// Maps configured `credential.helper` values to helpers, following Git's rules: `!cmd` is a
/// shell snippet, an absolute path is a shell command, and anything else names
/// `git-credential-<name>` (with any arguments). `store`, optionally with `--file`, runs natively.
#[cfg(feature = "http")]
fn credential_helpers(
    config: &crate::Config,
    environment: &Environment,
) -> Vec<crate::remote::CredentialHelper> {
    let exec_dirs: Vec<PathBuf> = environment
        .get("GIT_EXEC_PATH")
        .map(PathBuf::from)
        .into_iter()
        .chain(
            [
                "/opt/homebrew/opt/git/libexec/git-core",
                "/usr/local/opt/git/libexec/git-core",
                "/usr/lib/git-core",
                "/usr/libexec/git-core",
                "/Library/Developer/CommandLineTools/usr/libexec/git-core",
                "/Applications/Xcode.app/Contents/Developer/usr/libexec/git-core",
            ]
            .map(PathBuf::from),
        )
        .collect();
    config
        .entries()
        .iter()
        .filter(|entry| {
            entry.section.eq_ignore_ascii_case(b"credential")
                && entry.name.eq_ignore_ascii_case(b"helper")
        })
        .filter_map(|entry| entry.value.as_deref())
        .filter(|value| !value.is_empty())
        .filter_map(|value| {
            let text = std::str::from_utf8(value).ok()?;
            if let Some(store) = native_store(text, environment) {
                return Some(crate::remote::CredentialHelper {
                    configured_name: value.to_vec(),
                    backend: crate::remote::CredentialBackend::Store(store),
                });
            }
            let command = if let Some(snippet) = text.strip_prefix('!') {
                snippet.to_owned()
            } else if Path::new(text.split_whitespace().next()?).is_absolute() {
                text.to_owned()
            } else {
                let (name, arguments) = text.split_once(' ').unwrap_or((text, ""));
                let program = format!("git-credential-{name}");
                let path = find_program(environment, &program).or_else(|| {
                    exec_dirs
                        .iter()
                        .map(|dir| dir.join(&program))
                        .find(|candidate| candidate.is_file())
                })?;
                format!("{} {arguments}", shell_quote(&path.to_string_lossy()))
            };
            Some(crate::remote::CredentialHelper {
                configured_name: value.to_vec(),
                backend: crate::remote::CredentialBackend::Program(
                    crate::remote::CredentialProgram {
                        executable: PathBuf::from("/bin/sh"),
                        arguments: vec![
                            "-c".into(),
                            format!("{command} \"$@\"").into(),
                            command.into(),
                        ],
                        inherit_environment: false,
                        environment: environment
                            .vars
                            .iter()
                            .map(|(name, value)| (name.clone(), value.clone()))
                            .collect(),
                    },
                ),
            })
        })
        .collect()
}

/// Recognizes `store`, `store --file <path>` and `store --file=<path>`, which girt answers itself.
/// Other arguments, and paths containing shell syntax, keep using Git's program.
#[cfg(feature = "http")]
fn native_store(text: &str, environment: &Environment) -> Option<crate::remote::CredentialStore> {
    let mut words = text.split_whitespace();
    if words.next()? != "store" {
        return None;
    }
    let home = environment.get("HOME").map(PathBuf::from);
    let file = match (words.next(), words.next()) {
        (None, _) => None,
        (Some("--file"), Some(path)) => Some(path),
        (Some(option), None) => Some(option.strip_prefix("--file=")?),
        _ => return None,
    };
    if words.next().is_some() {
        return None;
    }
    let Some(file) = file else {
        let xdg = environment.get("XDG_CONFIG_HOME").map(PathBuf::from);
        return Some(crate::remote::CredentialStore::user_files(
            home.as_deref(),
            xdg.as_deref(),
        ));
    };
    // Anything the shell would interpret (quotes, expansions, redirections, separators) keeps
    // Git's program, so only plain path bytes are taken literally.
    let plain = |byte: u8| byte.is_ascii_alphanumeric() || b"/._-+,:@%=~".contains(&byte);
    if !file.bytes().all(plain) {
        return None;
    }
    let path = match file.strip_prefix("~/") {
        Some(rest) => home?.join(rest),
        None if file.starts_with('~') => return None,
        None => PathBuf::from(file),
    };
    let path = match &environment.current_dir {
        Some(directory) if path.is_relative() => directory.join(path),
        _ => path,
    };
    Some(crate::remote::CredentialStore::file(path))
}

#[cfg(feature = "http")]
fn http_environment(
    config: &crate::Config,
    destination: &Destination,
    environment: &Environment,
) -> Result<crate::transport::http::HttpEnvironment, TransferError> {
    let ca_path = match environment.get("GIT_SSL_CAINFO") {
        Some(path) => Some(PathBuf::from(path)),
        None => crate::transport::http::HttpSettings::configured_ca_info(config, destination)
            .map_err(|error| TransferError::Configuration(error.to_string()))?
            .map(|path| {
                let path = String::from_utf8_lossy(path).into_owned();
                match (path.strip_prefix("~/"), environment.get("HOME")) {
                    (Some(rest), Some(home)) => Path::new(home).join(rest),
                    _ => PathBuf::from(path),
                }
            }),
    };
    let ssl_ca_info = ca_path
        .map(|path| {
            std::fs::read(&path).map_err(|error| {
                TransferError::Configuration(format!("reading {}: {error}", path.display()))
            })
        })
        .transpose()?;
    let proxy_var = |names: &[&str]| names.iter().find_map(|name| environment.string(name));
    Ok(crate::transport::http::HttpEnvironment {
        ssl_ca_info,
        ssl_no_verify: environment
            .bytes("GIT_SSL_NO_VERIFY")
            .map(|value| crate::config::boolean(Some(&value)).unwrap_or(true)),
        proxy: proxy_var(&[
            "https_proxy",
            "HTTPS_PROXY",
            "http_proxy",
            "all_proxy",
            "ALL_PROXY",
        ]),
        no_proxy: proxy_var(&["no_proxy", "NO_PROXY"]),
        proxy_credentials: None,
        allow_insecure_tls: true,
    })
}

#[cfg(all(feature = "ssh", any(target_os = "macos", target_os = "linux")))]
fn ssh_endpoint(
    config: &crate::Config,
    destination: &Destination,
    environment: &Environment,
) -> Result<crate::transport::ssh::SshRemote, TransferError> {
    use crate::transport::ssh::{ApprovedSshCommand, OpenSshOptions, SshRemote};
    // Git runs a configured command through the shell with the SSH arguments appended.
    let configured = environment
        .bytes("GIT_SSH_COMMAND")
        .or_else(|| {
            config
                .string("core", None, "sshcommand")
                .map(<[u8]>::to_vec)
        })
        .map(|command| (command.clone(), command))
        .or_else(|| {
            environment.bytes("GIT_SSH").map(|program| {
                let quoted = shell_quote(&String::from_utf8_lossy(&program));
                (program, quoted.into_bytes())
            })
        });
    let approved_command = configured.map(|(configured, command)| {
        let command = String::from_utf8_lossy(&command).into_owned();
        ApprovedSshCommand {
            configured,
            executable: PathBuf::from("/bin/sh"),
            arguments: vec!["-c".into(), format!("{command} \"$@\""), command],
        }
    });
    let default_executable =
        find_program(environment, "ssh").unwrap_or_else(|| PathBuf::from("/usr/bin/ssh"));
    // GIT_SSH_VARIANT and ssh.variant only matter for non-OpenSSH clients.
    let environment = environment
        .clone()
        .without("GIT_PROTOCOL")
        .without("GIT_SSH_VARIANT");
    SshRemote::openssh(
        config,
        destination,
        OpenSshOptions {
            default_executable,
            approved_command,
            environment: environment.vars,
        },
    )
    .map_err(|error| TransferError::Configuration(error.to_string()))
}

impl Repository {
    fn endpoint(
        &self,
        remote_name: &str,
        direction: Direction,
        environment: &Environment,
    ) -> Result<(Endpoint, Destination), TransferError> {
        let config = self.config();
        let remote = Remote::find(config, remote_name.as_bytes())
            .map_err(|error| TransferError::Configuration(error.to_string()))?
            .ok_or_else(|| TransferError::NoSuchRemote(remote_name.to_owned()))?;
        let protocol_environment =
            ProtocolEnvironment::from_environment(|name| environment.bytes(name))
                .map_err(|error| TransferError::Configuration(error.to_string()))?;
        let destination = match direction {
            Direction::Fetch => remote.fetch_destination(config, &protocol_environment),
            Direction::Push => remote
                .push_destinations(config, &protocol_environment)
                .and_then(|destinations| {
                    destinations
                        .into_iter()
                        .next()
                        .ok_or(crate::remote::EndpointError::Missing)
                }),
        }
        .map_err(|error| match error {
            crate::remote::EndpointError::Missing => {
                TransferError::NoSuchRemote(remote_name.to_owned())
            }
            error => TransferError::Configuration(error.to_string()),
        })?;
        let endpoint = match destination.protocol() {
            Protocol::Local | Protocol::File => {
                let path = destination
                    .local_path()
                    .map_err(|error| TransferError::Configuration(error.to_string()))?;
                // Like Git, relative paths are relative to the working directory, falling back to
                // the working tree (or Git directory).
                let base = environment
                    .current_dir
                    .as_deref()
                    .or(self.worktree())
                    .unwrap_or(self.git_dir());
                Endpoint::Local(base.join(path))
            }
            #[cfg(feature = "http")]
            Protocol::Http | Protocol::Https => Endpoint::Http(Box::new(Http {
                environment: http_environment(config, &destination, environment)?,
                helpers: credential_helpers(config, environment),
                display_url: redacted_url(destination.bytes()),
                settings_config: config.clone(),
                remote_name: remote_name.as_bytes().to_vec(),
                destination: destination.clone(),
            })),
            #[cfg(all(feature = "ssh", any(target_os = "macos", target_os = "linux")))]
            Protocol::Ssh => {
                Endpoint::Ssh(Box::new(ssh_endpoint(config, &destination, environment)?))
            }
            _ => return Err(TransferError::UnsupportedTransport(remote_name.to_owned())),
        };
        Ok((endpoint, destination))
    }

    /// Asks the remote which branch its HEAD points to.
    ///
    /// # Errors
    ///
    /// Returns [`TransferError`] for configuration, transport and authentication failures.
    pub fn remote_head(
        &self,
        remote_name: &str,
        environment: &Environment,
        callbacks: &mut dyn TransferCallbacks,
    ) -> Result<RemoteHead, TransferError> {
        let (endpoint, _) = self.endpoint(remote_name, Direction::Fetch, environment)?;
        let cancel = AtomicBool::new(false);
        let control = TransportControl::new(&cancel);
        let limits = FetchLimits::trusted();
        let discovery = match endpoint {
            Endpoint::Local(path) => crate::fetch::discover_local(path, limits, control),
            #[cfg(feature = "http")]
            Endpoint::Http(http) => {
                let runtime = runtime()?;
                let result = runtime.block_on(crate::fetch::discover_http(
                    &http.remote(None)?,
                    limits,
                    control,
                ));
                if is_unauthorized_fetch(&result) {
                    let session = http.credentials(callbacks)?;
                    runtime.block_on(crate::fetch::discover_http(
                        &http.remote(Some(session))?,
                        limits,
                        control,
                    ))
                } else {
                    result
                }
            }
            #[cfg(all(feature = "ssh", any(target_os = "macos", target_os = "linux")))]
            Endpoint::Ssh(ssh) => {
                runtime()?.block_on(crate::fetch::discover_ssh(&ssh, limits, control))
            }
        };
        let _ = &callbacks;
        discovery
            .map(|discovery| discovery.head)
            .map_err(|error| TransferError::Fetch(Box::new(FetchWorkflowError::Transfer(error))))
    }

    /// Fetches from a configured remote and updates local references.
    ///
    /// Destinations must be remote-tracking references (`refs/remotes/`), tags, or a namespace
    /// allowed with [`FetchOptions::tag_namespace`]. Exact sources the remote doesn't have are
    /// reported in [`FetchOutcome::missing_sources`] rather than failing the fetch. No `FETCH_HEAD`
    /// is written and tags are not followed implicitly.
    ///
    /// # Errors
    ///
    /// Returns [`TransferError`]. After [`TransferError::FetchFinish`], new objects are installed
    /// but some references may not have been updated.
    pub fn fetch(
        &self,
        remote_name: &str,
        options: &FetchOptions,
        environment: &Environment,
        callbacks: &mut dyn TransferCallbacks,
    ) -> Result<FetchOutcome, TransferError> {
        let (endpoint, _) = self.endpoint(remote_name, Direction::Fetch, environment)?;
        let objects = self
            .objects(crate::PackLimits::trusted())
            .map_err(TransferError::local)?;
        let refs = self.references().map_err(TransferError::local)?;
        let tips: Vec<ObjectId> = refs
            .list()
            .map_err(TransferError::local)?
            .into_iter()
            .filter_map(|reference| match reference.target {
                crate::refs::Target::Direct(id) => Some(id),
                crate::refs::Target::Symbolic(_) => None,
            })
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect();
        let cancel = AtomicBool::new(false);
        let limits = FetchLimits::trusted();
        let known = if matches!(endpoint, Endpoint::Local(_)) {
            // Keep explicit reference roots as boundary evidence without a wire have-batch walk.
            KnownHistory::from_store_roots(objects, &tips, &cancel).map_err(|error| {
                TransferError::Fetch(Box::new(FetchWorkflowError::Transfer(error)))
            })?
        } else {
            KnownHistory::from_store(objects, &tips, limits, &cancel).map_err(|error| {
                TransferError::Fetch(Box::new(FetchWorkflowError::Transfer(error)))
            })?
        };
        let request = || self.fetch_request(options);
        let control = TransportControl::new(&cancel);
        #[cfg(feature = "http")]
        let mut on_message = |message: &[u8]| {
            callbacks.remote_message(message);
            ControlFlow::Continue(())
        };
        let ready = match endpoint {
            Endpoint::Local(path) => {
                let callbacks = std::cell::RefCell::new(callbacks);
                request()?.receive_local_with_validation_progress(
                    path,
                    &known,
                    limits,
                    control,
                    |message| {
                        callbacks.borrow_mut().remote_message(message);
                        ControlFlow::Continue(())
                    },
                    |event| callbacks.borrow_mut().validation_progress(event),
                )
            }
            #[cfg(feature = "http")]
            Endpoint::Http(http) => {
                let runtime = runtime()?;
                let known = std::sync::Arc::new(known);
                let receive = |remote: crate::transport::http::HttpRemote,
                               messages: &mut dyn FnMut(&[u8]) -> ControlFlow<()>|
                 -> Result<_, TransferError> {
                    let download = runtime.block_on(request()?.receive_http_with_progress(
                        &remote,
                        Some(known.clone()),
                        limits,
                        control,
                        |message| {
                            let _ = messages(message);
                        },
                    ));
                    Ok(download)
                };
                let mut download = receive(http.remote(None)?, &mut on_message)?;
                if matches!(
                    &download,
                    Err(FetchWorkflowError::Transfer(
                        crate::fetch::FetchError::Http(crate::transport::http::HttpError::Status(
                            401
                        ))
                    ))
                ) {
                    let session = http.credentials(callbacks)?;
                    download = receive(http.remote(Some(session))?, &mut |message| {
                        callbacks.remote_message(message);
                        ControlFlow::Continue(())
                    })?;
                }
                download
                    .and_then(|download| download.validate(&cancel, |_| ControlFlow::Continue(())))
            }
            #[cfg(all(feature = "ssh", any(target_os = "macos", target_os = "linux")))]
            Endpoint::Ssh(ssh) => {
                let callbacks = std::cell::RefCell::new(&mut *callbacks);
                let download = runtime()?.block_on(request()?.receive_ssh_with_progress(
                    &ssh,
                    Some(std::sync::Arc::new(known)),
                    limits,
                    control,
                    |message| callbacks.borrow_mut().transport_message(message),
                    |message| callbacks.borrow_mut().remote_message(message),
                ));
                download
                    .and_then(|download| download.validate(&cancel, |_| ControlFlow::Continue(())))
            }
        }
        .map_err(|error| TransferError::Fetch(Box::new(error)))?;
        let report = ready
            .finish(FetchUpdateLimits::trusted(), &cancel)
            .map_err(|error| TransferError::FetchFinish(Box::new(error)))?;
        Ok(FetchOutcome {
            updated: report
                .updates
                .iter()
                .filter(|update| {
                    !matches!(
                        update.kind,
                        FetchUpdateKind::SourceOnly | FetchUpdateKind::Unchanged
                    )
                })
                .filter_map(|update| {
                    Some(FetchedRef {
                        name: update.mapping.destination.clone()?,
                        old: update.previous,
                        new: update.mapping.source.as_ref().map(|source| source.id),
                    })
                })
                .collect(),
            missing_sources: report.missing,
        })
    }

    fn fetch_request(&self, options: &FetchOptions) -> Result<FetchRequest, TransferError> {
        let specs = Refspecs::parse(Direction::Fetch, options.refspecs.iter())
            .map_err(|error| TransferError::Configuration(error.to_string()))?;
        // Forced refspecs may replace any existing destination, as with `git fetch`.
        let authorized: BTreeSet<RefName> = self
            .references()
            .map_err(TransferError::local)?
            .list()
            .map_err(TransferError::local)?
            .into_iter()
            .map(|reference| reference.name)
            .collect();
        let reflog = match &options.reflog {
            None => Reflog::Preserve,
            Some((committer, message)) => Reflog::AppendIfChanged {
                committer: committer.clone(),
                message: message.clone(),
            },
        };
        let mut request = FetchRequest::prepare(self.clone(), specs, authorized, reflog)
            .map_err(|error| TransferError::Fetch(Box::new(error.into())))?;
        if options.prune {
            // Pruned references lose their reflogs, as in Git.
            request = request.with_prune();
            #[expect(clippy::expect_used, reason = "constant reference name is valid")]
            let namespaces = std::iter::once(RefName::new("refs/remotes").expect("valid name"))
                .chain(options.tag_namespaces.iter().cloned());
            for namespace in namespaces {
                request = request.with_reflog_for_update_kind(
                    namespace,
                    FetchUpdateKind::Prune,
                    Reflog::Delete,
                );
            }
        }
        for namespace in &options.tag_namespaces {
            request = request.with_tag_destination_namespace(namespace.clone());
        }
        if let Some(depth) = options.depth {
            request = request.with_depth(depth);
        }
        Ok(request)
    }

    /// Updates references on a configured remote's push URL.
    ///
    /// Each command is a compare-and-swap on the remote: it only applies if the remote reference
    /// currently has the command's expected value. Commands succeed or fail independently; check
    /// each [`crate::push::RefStatus`] in the report.
    ///
    /// Like `git push`, the pack omits history reachable from anything the remote advertises, so
    /// creating a branch sends only the commits the remote lacks. The pack is prepared after the
    /// advertisement is read, while the connection is open. If a local remote's references change
    /// during preparation, the push is prepared again once against the new references.
    ///
    /// # Errors
    ///
    /// Returns [`TransferError::Push`] when the push couldn't complete. Its
    /// [`crate::push::PushError::Uncertain`] variant means some updates may have been applied.
    pub fn push(
        &self,
        remote_name: &str,
        commands: Vec<PushCommand>,
        options: &PushOptions,
        environment: &Environment,
        callbacks: &mut dyn TransferCallbacks,
    ) -> Result<PushReport, TransferError> {
        self.push_observed(
            remote_name,
            commands,
            options,
            environment,
            callbacks,
            &|| {},
        )
    }

    /// Runs [`Self::push`], calling `before_prepare` before each preparation attempt.
    fn push_observed(
        &self,
        remote_name: &str,
        commands: Vec<PushCommand>,
        options: &PushOptions,
        environment: &Environment,
        callbacks: &mut dyn TransferCallbacks,
        before_prepare: &dyn Fn(),
    ) -> Result<PushReport, TransferError> {
        let (endpoint, _) = self.endpoint(remote_name, Direction::Push, environment)?;
        let objects = self
            .objects(crate::PackLimits::trusted())
            .map_err(TransferError::local)?;
        let format = objects.object_format();
        let mut limits = PushLimits::trusted();
        if let Some(compression) = options.compression {
            limits.compression = compression;
        }
        let cancel = AtomicBool::new(false);
        let control = TransportControl::new(&cancel);
        // Each transport reads the receiver's advertisement before preparing. Like `git
        // send-pack`, preparation excludes the history of every advertised object (`roots`), so
        // the pack holds only what the receiver lacks.
        let prepare = |roots: &[ObjectId]| -> Result<PreparedPush, PushFailure> {
            before_prepare();
            let prepared =
                PreparedPush::new_local(&objects, commands.clone(), roots, limits, &cancel)?;
            let prepared = if options.push_options.is_empty() {
                prepared
            } else {
                prepared.with_push_options(options.push_options.clone())?
            };
            Ok(prepared.with_progress())
        };
        #[cfg(any(
            feature = "http",
            all(feature = "ssh", any(target_os = "macos", target_os = "linux"))
        ))]
        let names: Vec<RefName> = commands.iter().map(|c| c.name.clone()).collect();
        let result = match endpoint {
            Endpoint::Local(path) => {
                let mut send = || {
                    crate::push::send_local_preparing_observed(
                        &path,
                        format,
                        control,
                        crate::push::LocalPushContext {
                            config_inputs: &crate::config::ConfigInputs::default(),
                            identity: options.identity.as_ref(),
                        },
                        |advertisement| prepare(&advertisement.receiver_roots()?),
                        |event| callbacks.validation_progress(event),
                    )
                };
                let mut result = send();
                // The destination's references changed while preparing: prepare once more against
                // the new ones. A second change is reported rather than retried.
                if is_knowledge_changed(&result) {
                    result = send();
                }
                // Receive hook output arrives with the report rather than live.
                if let Ok(report) = &result {
                    for message in &report.progress {
                        callbacks.remote_message(message);
                    }
                }
                result
            }
            #[cfg(feature = "http")]
            Endpoint::Http(http) => {
                let runtime = runtime()?;
                let send = |remote: &crate::transport::http::HttpRemote,
                            callbacks: &mut dyn TransferCallbacks| {
                    let advertised = std::cell::RefCell::new(BTreeMap::new());
                    let result = runtime.block_on(crate::push::send_http_preparing(
                        remote,
                        format,
                        limits,
                        control,
                        |advertisement| {
                            record_targets(advertisement, &names, &advertised);
                            prepare(&advertisement.receiver_roots())
                        },
                        |message| callbacks.remote_message(message),
                    ));
                    result.map(|mut report| {
                        mark_up_to_date(&mut report, &advertised.into_inner());
                        report
                    })
                };
                let remote = http.remote(None)?;
                let mut result = send(&remote, callbacks);
                if is_unauthorized_push(&result) {
                    let session = http.credentials(callbacks)?;
                    let remote = http.remote(Some(session))?;
                    result = send(&remote, callbacks);
                }
                result
            }
            #[cfg(all(feature = "ssh", any(target_os = "macos", target_os = "linux")))]
            Endpoint::Ssh(ssh) => {
                let runtime = runtime()?;
                let advertised = std::cell::RefCell::new(BTreeMap::new());
                let callbacks = std::cell::RefCell::new(callbacks);
                let result = runtime.block_on(crate::push::send_ssh_preparing(
                    &ssh,
                    format,
                    limits,
                    control,
                    |advertisement| {
                        record_targets(advertisement, &names, &advertised);
                        prepare(&advertisement.receiver_roots())
                    },
                    |message| callbacks.borrow_mut().transport_message(message),
                    |message| callbacks.borrow_mut().remote_message(message),
                ));
                result.map(|mut report| {
                    mark_up_to_date(&mut report, &advertised.into_inner());
                    report
                })
            }
        };
        let report = result.map_err(|error| TransferError::Push(Box::new(error)))?;
        self.update_tracking_refs(remote_name, &report, options.identity.as_ref());
        Ok(report)
    }

    /// Updates local remote-tracking references for successfully pushed references, as `git
    /// push` does, using the remote's fetch refspecs. Failures are ignored: the next fetch
    /// corrects them.
    fn update_tracking_refs(
        &self,
        remote_name: &str,
        report: &PushReport,
        identity: Option<&crate::Signature>,
    ) {
        let Ok(Some(remote)) =
            crate::remote::ConfiguredRemote::find(self.config(), remote_name.as_bytes())
        else {
            return;
        };
        let Ok(refs) = self.references() else {
            return;
        };
        let succeeded = report.unpack == Some(crate::push::Status::Ok);
        for status in &report.refs {
            if !succeeded || status.status != Some(crate::push::Status::Ok) {
                continue;
            }
            let Some(name) = tracking_ref(remote.fetch_refspecs(), status.command.name.as_bytes())
            else {
                continue;
            };
            let deleted = status.command.deletes();
            let edit = crate::refs::RefEdit {
                name,
                dereference: false,
                target: (!deleted).then_some(crate::refs::Target::Direct(status.command.new)),
                expected: crate::refs::Expected::Any,
                reflog: match (deleted, identity) {
                    (true, _) => Reflog::Delete,
                    (false, Some(identity)) => Reflog::AppendIfChanged {
                        committer: identity.clone(),
                        message: b"update by push".to_vec(),
                    },
                    (false, None) => Reflog::Preserve,
                },
            };
            // Applied independently so one conflicting name doesn't block the others.
            let _ = refs.transaction(std::slice::from_ref(&edit));
        }
    }
}

/// Maps a remote reference name through fetch refspecs to its remote-tracking reference.
fn tracking_ref(refspecs: &[crate::remote::ConfiguredRefspec], name: &[u8]) -> Option<RefName> {
    use crate::remote::ConfiguredRefspecKind;
    let matches = |pattern: &[u8]| -> Option<Vec<u8>> {
        match crate::bytes::split_once(pattern, b'*') {
            None => (pattern == name).then(Vec::new),
            Some((prefix, suffix)) => name
                .strip_prefix(prefix)?
                .strip_suffix(suffix)
                .map(<[u8]>::to_vec),
        }
    };
    let excluded = refspecs.iter().any(|spec| {
        spec.kind() == ConfiguredRefspecKind::Exclusion && spec.source().and_then(matches).is_some()
    });
    if excluded {
        return None;
    }
    refspecs
        .iter()
        .filter(|spec| spec.kind() == ConfiguredRefspecKind::Mapping)
        .find_map(|spec| {
            let captured = matches(spec.source()?)?;
            let destination = spec.destination()?;
            let destination = match crate::bytes::split_once(destination, b'*') {
                None => destination.to_vec(),
                Some((prefix, suffix)) => [prefix, &captured, suffix].concat(),
            };
            RefName::new(destination).ok()
        })
}

/// Records the advertised values of the pushed references.
#[cfg(any(
    feature = "http",
    all(feature = "ssh", any(target_os = "macos", target_os = "linux"))
))]
fn record_targets(
    advertisement: &crate::push::PushAdvertisement,
    names: &[RefName],
    advertised: &std::cell::RefCell<BTreeMap<RefName, Option<ObjectId>>>,
) {
    let mut advertised = advertised.borrow_mut();
    for name in names {
        advertised.insert(name.clone(), advertisement.target(name));
    }
}

/// Like Git, treats a rejected reference whose remote value already equals the requested value as
/// up to date.
#[cfg(any(
    feature = "http",
    all(feature = "ssh", any(target_os = "macos", target_os = "linux"))
))]
fn mark_up_to_date(report: &mut PushReport, advertised: &BTreeMap<RefName, Option<ObjectId>>) {
    for status in &mut report.refs {
        let Some(current) = advertised.get(&status.command.name) else {
            continue;
        };
        // Deletions are never up to date; see `git push --force-with-lease`.
        let up_to_date = !status.command.deletes() && *current == Some(status.command.new);
        if up_to_date && status.status != Some(crate::push::Status::Ok) {
            status.status = Some(crate::push::Status::Ok);
            status.rejection_origin = None;
        }
    }
}

fn is_knowledge_changed<T>(result: &Result<T, crate::push::PushError>) -> bool {
    matches!(
        result,
        Err(crate::push::PushError::NotSent(
            crate::push::PushFailure::KnowledgeChanged(_)
        ))
    )
}

#[cfg(feature = "http")]
fn is_unauthorized_push<T>(result: &Result<T, crate::push::PushError>) -> bool {
    matches!(
        result,
        Err(crate::push::PushError::NotSent(
            crate::push::PushFailure::Http(crate::transport::http::HttpError::Status(401))
        ))
    )
}

#[cfg(feature = "http")]
fn is_unauthorized_fetch<T>(result: &Result<T, crate::fetch::FetchError>) -> bool {
    matches!(
        result,
        Err(crate::fetch::FetchError::Http(
            crate::transport::http::HttpError::Status(401)
        ))
    )
}

#[cfg(any(
    feature = "http",
    all(feature = "ssh", any(target_os = "macos", target_os = "linux"))
))]
fn runtime() -> Result<tokio::runtime::Runtime, TransferError> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(TransferError::local)
}

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

    use super::*;
    use crate::push::{ForcePolicy, PushError};

    fn git(directory: &Path, args: &[&str], date: usize) -> String {
        let date = format!("@{} +0000", 1_700_000_000 + date * 60);
        let output = Command::new("git")
            .current_dir(directory)
            .env_clear()
            .env("PATH", std::env::var_os("PATH").unwrap())
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_AUTHOR_NAME", "Push Author")
            .env("GIT_AUTHOR_EMAIL", "push@example.com")
            .env("GIT_COMMITTER_NAME", "Push Author")
            .env("GIT_COMMITTER_EMAIL", "push@example.com")
            .env("GIT_AUTHOR_DATE", &date)
            .env("GIT_COMMITTER_DATE", &date)
            .args(args)
            .output()
            .expect("Git required for push fixtures");
        assert!(
            output.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8(output.stdout).unwrap().trim().to_owned()
    }

    /// A worktree whose `main` has 30 commits, each adding a file, pushed to a bare `origin`, and
    /// a `topic` branch one commit ahead of `main` that the destination lacks.
    fn fixture() -> (tempfile::TempDir, PathBuf, PathBuf, ObjectId) {
        let root = tempfile::tempdir().unwrap();
        let work = root.path().join("work");
        let dest = root.path().join("dest.git");
        std::fs::create_dir(&work).unwrap();
        std::fs::create_dir(&dest).unwrap();
        git(&work, &["init", "-q", "--initial-branch=main", "."], 0);
        git(&dest, &["init", "-q", "--bare", "."], 0);
        git(&dest, &["config", "receive.unpackLimit", "1"], 0);
        for n in 0..=30 {
            if n == 30 {
                git(&work, &["push", "-q", &dest.to_string_lossy(), "main"], n);
                git(&work, &["switch", "-q", "-c", "topic"], n);
            }
            std::fs::write(work.join(format!("file-{n}")), format!("{n}\n")).unwrap();
            git(&work, &["add", "."], n);
            git(&work, &["commit", "-q", "-m", &n.to_string()], n);
        }
        git(
            &work,
            &["remote", "add", "origin", &dest.to_string_lossy()],
            0,
        );
        let topic = git(&work, &["rev-parse", "topic"], 0).parse().unwrap();
        (root, work, dest, topic)
    }

    fn push(
        work: &Path,
        topic: ObjectId,
        before_prepare: &dyn Fn(),
    ) -> Result<PushReport, TransferError> {
        Repository::open(work).unwrap().push_observed(
            "origin",
            vec![PushCommand {
                name: RefName::new("refs/heads/topic").unwrap(),
                expected: None,
                new: topic,
                force: ForcePolicy::FastForwardOnly,
            }],
            &PushOptions::default(),
            &Environment::default(),
            &mut NoCallbacks,
            before_prepare,
        )
    }

    /// Pack identities independently listed by Git, including verified thin-pack repair bases.
    fn pack_ids(dest: &Path) -> std::collections::BTreeMap<PathBuf, Vec<String>> {
        std::fs::read_dir(dest.join("objects/pack"))
            .unwrap()
            .map(|entry| entry.unwrap().path())
            .filter(|path| path.extension().is_some_and(|e| e == "idx"))
            .map(|index| {
                let output = Command::new("git")
                    .arg("show-index")
                    .stdin(std::fs::File::open(&index).unwrap())
                    .output()
                    .unwrap();
                assert!(output.status.success());
                let ids = String::from_utf8(output.stdout)
                    .unwrap()
                    .lines()
                    .map(|line| line.split_whitespace().nth(1).unwrap().to_owned())
                    .collect();
                (index, ids)
            })
            .collect()
    }

    fn packed(dest: &Path) -> usize {
        pack_ids(dest).values().map(Vec::len).sum()
    }

    #[test]
    fn push_retry_after_knowledge_change_reuses_advertisement() {
        let (_root, work, dest, topic) = fixture();
        let before = pack_ids(&dest);
        let base_tree = git(&work, &["rev-parse", "main~1^{tree}"], 0);
        let attempts = Cell::new(0);
        // The destination's only ref moves back one commit while the first pack is prepared, so
        // the root that pack relies on is no longer advertised.
        let report = push(&work, topic, &|| {
            attempts.set(attempts.get() + 1);
            if attempts.get() == 1 {
                git(&dest, &["update-ref", "refs/heads/main", "main~1"], 0);
            }
        })
        .unwrap();
        assert!(report.all_succeeded(), "{report:?}");
        assert_eq!(attempts.get(), 2);
        // The retry sends exactly Git's six selected objects. Native thin-pack repair additionally
        // appends the verified old tree base, rather than retransmitting receiver history.
        let after = pack_ids(&dest);
        let mut incoming: Vec<_> = after
            .iter()
            .filter(|(path, _)| !before.contains_key(*path))
            .flat_map(|(_, ids)| ids.iter().cloned())
            .collect();
        let oracle = git(
            &work,
            &["rev-list", "--objects", "topic", "--not", "main~1"],
            0,
        );
        let mut expected: Vec<_> = oracle
            .lines()
            .map(|line| line.split_whitespace().next().unwrap().to_owned())
            .collect();
        assert_eq!(expected.len(), 6);
        expected.push(base_tree);
        incoming.sort();
        expected.sort();
        assert_eq!(incoming, expected);
        assert_eq!(git(&dest, &["rev-parse", "topic"], 0), topic.to_string());
        git(&dest, &["fsck", "--strict", "--no-dangling"], 0);
    }

    #[test]
    fn push_reports_a_second_knowledge_change_without_sending() {
        let (_root, work, dest, topic) = fixture();
        let before = packed(&dest);
        let attempts = Cell::new(0);
        let result = push(&work, topic, &|| {
            attempts.set(attempts.get() + 1);
            git(&dest, &["update-ref", "refs/heads/main", "main~1"], 0);
        });
        assert!(
            matches!(
                result,
                Err(TransferError::Push(ref error))
                    if matches!(**error, PushError::NotSent(PushFailure::KnowledgeChanged(_)))
            ),
            "{result:?}"
        );
        assert_eq!(attempts.get(), 2);
        assert_eq!(packed(&dest), before);
        assert!(git(&dest, &["for-each-ref", "refs/heads/topic"], 0).is_empty());
    }

    #[cfg(feature = "http")]
    #[test]
    fn native_store_accepts_plain_paths_and_leaves_shell_syntax_to_git() {
        let environment = Environment::default()
            .with("HOME", "/home/user")
            .with_current_dir("/work");
        let files = |text| native_store(text, &environment).map(|store| store.files().to_vec());
        assert_eq!(
            files("store --file=~/creds"),
            Some(vec![PathBuf::from("/home/user/creds")])
        );
        assert_eq!(
            files("store --file creds"),
            Some(vec![PathBuf::from("/work/creds")])
        );
        assert_eq!(files("store").map(|files| files.len()), Some(2));
        for text in [
            "store --file=creds>out",
            "store --file creds|tee",
            "store --file=a;b",
            "store --file=$HOME/creds",
            "store --file='creds'",
            "store --file=(creds)",
            "store --file=a&",
            "store --file=<in",
            "store --other",
            "store --file a b",
            "store>out",
        ] {
            assert!(files(text).is_none(), "{text}");
        }
    }

    #[test]
    fn tracking_ref_rejects_overlapping_pattern_halves() {
        use crate::remote::{ConfiguredRefspec, Direction};
        let refspecs =
            [
                ConfiguredRefspec::parse(Direction::Fetch, b"refs/heads/*/x:refs/remotes/o/*")
                    .unwrap(),
            ];
        assert_eq!(tracking_ref(&refspecs, b"refs/heads/x"), None);
        assert_eq!(
            tracking_ref(&refspecs, b"refs/heads/a/x")
                .unwrap()
                .as_bytes(),
            b"refs/remotes/o/a"
        );
    }
}