girt 0.18.0

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
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
//! Native local transfers using original objects and independent Git reads.

use std::ops::ControlFlow;
use std::process::Command;
use std::sync::atomic::AtomicBool;

use girt::config::{ConfigFile, ConfigInputs, ConfigScope};
use girt::fetch::{FetchError, FetchLimits, discover_local, receive_local};
use girt::push::{
    ForcePolicy, PreparedPush, PushCommand, PushError, PushFailure, PushLimits, RejectionOrigin,
    send_local,
};
use girt::refs::{Backend, Expected, RefName, Target};
use girt::transport::TransportControl;
use girt::{
    Commit, CommitFields, Config, InitKind, ObjectFormat, PackLimits, Repository, Signature, Tree,
};
use rstest::rstest;

fn repository(
    root: &tempfile::TempDir,
    name: &str,
    format: ObjectFormat,
    backend: Backend,
) -> Repository {
    Repository::init_with_backend(format, root.path().join(name), InitKind::Bare, backend).unwrap()
}

fn commit(repository: &Repository) -> girt::ObjectId {
    let store = repository.loose_objects();
    let tree = Tree::new(repository.object_format(), vec![]).unwrap();
    store.write_tree(&tree).unwrap();
    let person = Signature {
        name: b"Local Test".to_vec(),
        email: b"local@example.invalid".to_vec(),
        seconds: 1_700_000_000,
        offset_minutes: 0,
    };
    let commit = Commit::new(CommitFields {
        tree: tree.id(),
        parents: vec![],
        author: person.clone(),
        committer: person,
        extra_headers: vec![],
        message: b"Local transfer\n".to_vec(),
    })
    .unwrap();
    let id = store.write_commit(&commit).unwrap();
    let name = RefName::new("refs/heads/main").unwrap();
    repository
        .references()
        .unwrap()
        .update_without_reflog(&name, Target::Direct(id), Expected::Absent)
        .unwrap();
    id
}

fn git_cat_file(repository: &Repository, id: girt::ObjectId) -> Vec<u8> {
    let output = Command::new("git")
        .arg("--git-dir")
        .arg(plain_local_path(repository.git_dir()))
        .args(["cat-file", "commit", &id.to_string()])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    output.stdout
}

fn plain_local_path(path: &std::path::Path) -> String {
    let value = path.to_string_lossy();
    #[cfg(windows)]
    {
        value.strip_prefix(r"\\?\").unwrap_or(&value).to_owned()
    }
    #[cfg(not(windows))]
    {
        value.into_owned()
    }
}

#[rstest]
#[case::sha1(ObjectFormat::Sha1)]
#[case::sha256(ObjectFormat::Sha256)]
fn native_push_creates_and_deletes_git_reflog_with_explicit_identity(#[case] format: ObjectFormat) {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", format, Backend::Files);
    let dest = repository(&root, "dest", format, Backend::Files);
    let id = commit(&source);
    use std::io::Write;
    std::fs::OpenOptions::new()
        .append(true)
        .open(dest.git_dir().join("config"))
        .unwrap()
        .write_all(b"\n[core]\n logAllRefUpdates = true\n")
        .unwrap();
    let command = PushCommand::new(RefName::new("refs/heads/main").unwrap(), None, id)
        .with_force(ForcePolicy::FastForwardOnly);
    let cancel = AtomicBool::new(false);
    let objects = source.objects_with(PackLimits::default()).unwrap();
    let prepared =
        PreparedPush::new(&objects, vec![command], &[], PushLimits::default(), &cancel).unwrap();
    assert!(matches!(
        send_local(
            dest.git_dir(),
            girt::push::LocalPushRequest::new(&prepared),
            girt::transport::TransportControl::new(&cancel),
            |_| {}
        ),
        Err(PushError::NotSent(PushFailure::Identity))
    ));
    let identity = Signature {
        name: b"Pusher".to_vec(),
        email: b"push@example.invalid".to_vec(),
        seconds: 1_700_000_000,
        offset_minutes: 0,
    };
    let report = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&prepared).with_identity(Some(&identity)),
        TransportControl::new(&cancel),
        |_| {},
    )
    .unwrap();
    assert!(report.all_succeeded());
    assert!(report.refs[0].effects.is_some());
    let log = dest
        .references()
        .unwrap()
        .reflog(&RefName::new("refs/heads/main").unwrap())
        .unwrap()
        .unwrap();
    assert_eq!(log.len(), 1);
    assert_eq!(log[0].committer, identity);
    assert_eq!(log[0].new, id);
    let git_log = Command::new("git")
        .arg("--git-dir")
        .arg(plain_local_path(dest.git_dir()))
        .args(["reflog", "show", "--format=%H", "refs/heads/main"])
        .output()
        .unwrap();
    assert!(git_log.status.success());
    assert!(git_log.stdout.starts_with(id.to_string().as_bytes()));
    let deletion = {
        let input = PushCommand::new(
            RefName::new("refs/heads/main").unwrap(),
            Some(id),
            girt::ObjectId::null(format),
        );
        input.with_force(ForcePolicy::FastForwardOnly)
    };
    let prepared = PreparedPush::new(
        &objects,
        vec![deletion],
        &[],
        PushLimits::default(),
        &cancel,
    )
    .unwrap();
    let report = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&prepared).with_identity(Some(&identity)),
        TransportControl::new(&cancel),
        |_| {},
    )
    .unwrap();
    assert!(report.all_succeeded());
    assert!(
        dest.references()
            .unwrap()
            .reflog(&RefName::new("refs/heads/main").unwrap())
            .unwrap()
            .is_none()
    );
    let git_log = Command::new("git")
        .arg("--git-dir")
        .arg(plain_local_path(dest.git_dir()))
        .args(["reflog", "exists", "refs/heads/main"])
        .status()
        .unwrap();
    assert!(!git_log.success());
}

#[test]
fn native_current_branch_policies_distinguish_updates_and_deletes() {
    use std::io::Write;
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", ObjectFormat::Sha1, Backend::Files);
    let dest = Repository::init(
        ObjectFormat::Sha1,
        root.path().join("worktree"),
        InitKind::Worktree,
    )
    .unwrap();
    let id = commit(&source);
    let cancel = AtomicBool::new(false);
    let objects = source.objects_with(PackLimits::default()).unwrap();
    let update = PushCommand::new(RefName::new("refs/heads/main").unwrap(), None, id)
        .with_force(ForcePolicy::FastForwardOnly);
    let prepared =
        PreparedPush::new(&objects, vec![update], &[], PushLimits::default(), &cancel).unwrap();
    let refused = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&prepared),
        girt::transport::TransportControl::new(&cancel),
        |_| {},
    )
    .unwrap();
    assert!(matches!(
        refused.refs[0].status,
        Some(girt::push::Status::Rejected(_))
    ));
    std::fs::OpenOptions::new()
        .append(true)
        .open(dest.git_dir().join("config"))
        .unwrap()
        .write_all(b"\n[receive]\n denyCurrentBranch = ignore\n")
        .unwrap();
    let identity = Signature {
        name: b"Pusher".to_vec(),
        email: b"push@example.invalid".to_vec(),
        seconds: 1_700_000_000,
        offset_minutes: 0,
    };
    let accepted = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&prepared).with_identity(Some(&identity)),
        TransportControl::new(&cancel),
        |_| {},
    )
    .unwrap();
    assert!(accepted.all_succeeded());
    let deletion = {
        let input = PushCommand::new(
            RefName::new("refs/heads/main").unwrap(),
            Some(id),
            girt::ObjectId::null(ObjectFormat::Sha1),
        );
        input.with_force(ForcePolicy::FastForwardOnly)
    };
    let prepared = PreparedPush::new(
        &objects,
        vec![deletion],
        &[],
        PushLimits::default(),
        &cancel,
    )
    .unwrap();
    let refused = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&prepared),
        girt::transport::TransportControl::new(&cancel),
        |_| {},
    )
    .unwrap();
    assert!(matches!(
        refused.refs[0].status,
        Some(girt::push::Status::Rejected(_))
    ));
    std::fs::OpenOptions::new()
        .append(true)
        .open(dest.git_dir().join("config"))
        .unwrap()
        .write_all(b" denyDeleteCurrent = false\n")
        .unwrap();
    let accepted = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&prepared).with_identity(Some(&identity)),
        TransportControl::new(&cancel),
        |_| {},
    )
    .unwrap();
    assert!(accepted.all_succeeded());
    assert!(
        dest.references()
            .unwrap()
            .read(&RefName::new("refs/heads/main").unwrap())
            .unwrap()
            .is_none()
    );
}

#[rstest]
#[case::sha1(ObjectFormat::Sha1)]
#[case::sha256(ObjectFormat::Sha256)]
fn native_push_uses_explicit_inherited_receive_config(#[case] format: ObjectFormat) {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", format, Backend::Files);
    let dest = repository(&root, "dest", format, Backend::Files);
    let id = commit(&source);
    let name = RefName::new("refs/heads/topic").unwrap();
    let cancel = AtomicBool::new(false);
    let objects = source.objects_with(PackLimits::default()).unwrap();
    let create = PreparedPush::new(
        &objects,
        vec![PushCommand::new(name.clone(), None, id).with_force(ForcePolicy::FastForwardOnly)],
        &[],
        PushLimits::default(),
        &cancel,
    )
    .unwrap();
    assert!(
        send_local(
            dest.git_dir(),
            girt::push::LocalPushRequest::new(&create),
            girt::transport::TransportControl::new(&cancel),
            |_| {}
        )
        .unwrap()
        .all_succeeded()
    );

    let global_config = root.path().join("global-config");
    std::fs::write(&global_config, b"[receive]\n denyDeletes = true\n").unwrap();
    let config_inputs = ConfigInputs::default().with_files(vec![
        ConfigFile::new(global_config, ConfigScope::Global).with_optional(false),
    ]);
    let delete = PreparedPush::new(
        &objects,
        vec![
            PushCommand::new(name.clone(), Some(id), girt::ObjectId::null(format))
                .with_force(ForcePolicy::FastForwardOnly),
        ],
        &[],
        PushLimits::default(),
        &cancel,
    )
    .unwrap();
    let report = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&delete).with_config_inputs(&config_inputs),
        TransportControl::new(&cancel),
        |_| {},
    )
    .unwrap();
    assert!(matches!(
        report.refs[0].status,
        Some(girt::push::Status::Rejected(_))
    ));
    assert_eq!(
        report.refs[0].rejection_origin,
        Some(RejectionOrigin::Receiver)
    );
    assert_eq!(
        dest.references().unwrap().read(&name).unwrap(),
        Some(Target::Direct(id))
    );
    assert!(
        send_local(
            dest.git_dir(),
            girt::push::LocalPushRequest::new(&delete),
            girt::transport::TransportControl::new(&cancel),
            |_| {}
        )
        .unwrap()
        .all_succeeded()
    );
}

#[test]
fn native_hidden_ref_rejects_independently_of_visible_ref() {
    use std::io::Write;
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", ObjectFormat::Sha1, Backend::Files);
    let dest = repository(&root, "dest", ObjectFormat::Sha1, Backend::Files);
    let id = commit(&source);
    std::fs::OpenOptions::new()
        .append(true)
        .open(dest.git_dir().join("config"))
        .unwrap()
        .write_all(b"\n[receive]\n hideRefs = refs/heads/private\n hideRefs = !refs/heads/private/allowed\n")
        .unwrap();
    let commands = ["refs/heads/private/blocked", "refs/heads/private/allowed"].map(|name| {
        PushCommand::new(RefName::new(name).unwrap(), None, id)
            .with_force(ForcePolicy::FastForwardOnly)
    });
    let cancel = AtomicBool::new(false);
    let objects = source.objects_with(PackLimits::default()).unwrap();
    let prepared = PreparedPush::new(
        &objects,
        commands.to_vec(),
        &[],
        PushLimits::default(),
        &cancel,
    )
    .unwrap();
    let report = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&prepared),
        girt::transport::TransportControl::new(&cancel),
        |_| {},
    )
    .unwrap();
    assert!(matches!(
        report.refs[0].status,
        Some(girt::push::Status::Rejected(_))
    ));
    assert_eq!(
        report.refs[0].rejection_origin,
        Some(RejectionOrigin::Receiver)
    );
    assert_eq!(report.refs[1].status, Some(girt::push::Status::Ok));
    let refs = dest.references().unwrap();
    assert_eq!(refs.read(&commands[0].name).unwrap(), None);
    assert_eq!(
        refs.read(&commands[1].name).unwrap(),
        Some(Target::Direct(id))
    );
}

#[rstest]
#[case::sha1_files(ObjectFormat::Sha1, Backend::Files)]
#[case::sha1_reftable(ObjectFormat::Sha1, Backend::Reftable)]
#[case::sha256_files(ObjectFormat::Sha256, Backend::Files)]
#[case::sha256_reftable(ObjectFormat::Sha256, Backend::Reftable)]
fn native_stale_expectation_is_distinct_from_receiver_rejection(
    #[case] format: ObjectFormat,
    #[case] backend: Backend,
) {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", format, backend);
    let dest = repository(&root, "dest", format, backend);
    let id = commit(&source);
    let stale = RefName::new("refs/heads/stale").unwrap();
    let accepted = RefName::new("refs/heads/accepted").unwrap();
    let commands = vec![
        PushCommand::new(stale.clone(), Some(id), id).with_force(ForcePolicy::FastForwardOnly),
        PushCommand::new(accepted.clone(), None, id).with_force(ForcePolicy::FastForwardOnly),
    ];
    let cancel = AtomicBool::new(false);
    let prepared = PreparedPush::new(
        &source.objects_with(PackLimits::default()).unwrap(),
        commands,
        &[],
        PushLimits::default(),
        &cancel,
    )
    .unwrap();
    let report = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&prepared),
        girt::transport::TransportControl::new(&cancel),
        |_| {},
    )
    .unwrap();
    assert!(matches!(
        report.refs[0].status,
        Some(girt::push::Status::Rejected(_))
    ));
    assert_eq!(
        report.refs[0].rejection_origin,
        Some(RejectionOrigin::ExpectedValue)
    );
    assert_eq!(report.refs[1].status, Some(girt::push::Status::Ok));
    assert_eq!(report.refs[1].rejection_origin, None);
    let refs = dest.references().unwrap();
    assert_eq!(refs.read(&stale).unwrap(), None);
    assert_eq!(refs.read(&accepted).unwrap(), Some(Target::Direct(id)));
}

#[test]
fn native_warn_mode_reports_accepted_current_branch_update() {
    use std::io::Write;
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", ObjectFormat::Sha1, Backend::Files);
    let dest = Repository::init(
        ObjectFormat::Sha1,
        root.path().join("worktree"),
        InitKind::Worktree,
    )
    .unwrap();
    let id = commit(&source);
    std::fs::OpenOptions::new()
        .append(true)
        .open(dest.git_dir().join("config"))
        .unwrap()
        .write_all(b"\n[receive]\n denyCurrentBranch = warn\n")
        .unwrap();
    let cancel = AtomicBool::new(false);
    let prepared = PreparedPush::new(
        &source.objects_with(PackLimits::default()).unwrap(),
        vec![
            PushCommand::new(RefName::new("refs/heads/main").unwrap(), None, id)
                .with_force(ForcePolicy::FastForwardOnly),
        ],
        &[],
        PushLimits::default(),
        &cancel,
    )
    .unwrap();
    let identity = Signature {
        name: b"Pusher".to_vec(),
        email: b"push@example.invalid".to_vec(),
        seconds: 1_700_000_000,
        offset_minutes: 0,
    };
    let report = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&prepared).with_identity(Some(&identity)),
        TransportControl::new(&cancel),
        |_| {},
    )
    .unwrap();
    assert!(report.all_succeeded());
    assert_eq!(report.warnings.len(), 1);
    assert_eq!(
        dest.references()
            .unwrap()
            .read(&RefName::new("refs/heads/main").unwrap())
            .unwrap(),
        Some(Target::Direct(id))
    );
}

#[rstest]
#[case::deletes("denyDeletes")]
#[case::non_fast_forward("denyNonFastForwards")]
fn invalid_receive_boolean_refuses_before_native_installation(#[case] key: &str) {
    use std::io::Write;
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", ObjectFormat::Sha1, Backend::Files);
    let dest = repository(&root, "dest", ObjectFormat::Sha1, Backend::Files);
    let id = commit(&source);
    std::fs::OpenOptions::new()
        .append(true)
        .open(dest.git_dir().join("config"))
        .unwrap()
        .write_all(format!("\n[receive]\n {key} = invalid\n").as_bytes())
        .unwrap();
    let cancel = AtomicBool::new(false);
    let prepared = PreparedPush::new(
        &source.objects_with(PackLimits::default()).unwrap(),
        vec![
            PushCommand::new(RefName::new("refs/heads/main").unwrap(), None, id)
                .with_force(ForcePolicy::FastForwardOnly),
        ],
        &[],
        PushLimits::default(),
        &cancel,
    )
    .unwrap();
    assert!(matches!(
        send_local(
            dest.git_dir(),
            girt::push::LocalPushRequest::new(&prepared),
            girt::transport::TransportControl::new(&cancel),
            |_| {}
        ),
        Err(PushError::NotSent(PushFailure::Unsupported(_)))
    ));
    assert!(
        dest.objects_with(PackLimits::default())
            .unwrap()
            .read_with(id, Default::default())
            .unwrap()
            .is_none()
    );
}

#[rstest]
#[case::sha1_files(ObjectFormat::Sha1, Backend::Files)]
#[case::sha1_reftable(ObjectFormat::Sha1, Backend::Reftable)]
#[case::sha256_files(ObjectFormat::Sha256, Backend::Files)]
#[case::sha256_reftable(ObjectFormat::Sha256, Backend::Reftable)]
fn native_fetch_and_push_preserve_git_objects_and_refs(
    #[case] format: ObjectFormat,
    #[case] backend: Backend,
) {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", format, backend);
    let fetched = repository(&root, "fetched", format, backend);
    let pushed = repository(&root, "pushed", format, backend);
    let id = commit(&source);
    let received = receive_local(
        source.git_dir(),
        |_| vec![id],
        girt::fetch::LocalFetchRequest::new(FetchLimits::default()),
        girt::transport::TransportControl::new(&AtomicBool::new(false)),
        girt::fetch::LocalFetchObserver::default(),
    )
    .unwrap();
    assert_eq!(received.wants(), &[id]);
    received
        .install(&fetched, PackLimits::default(), &AtomicBool::new(false))
        .unwrap();
    assert_eq!(git_cat_file(&fetched, id), git_cat_file(&source, id));
    let command = PushCommand::new(RefName::new("refs/heads/main").unwrap(), None, id)
        .with_force(ForcePolicy::FastForwardOnly);
    let objects = source.objects_with(PackLimits::default()).unwrap();
    let prepared = PreparedPush::new(
        &objects,
        vec![command],
        &[],
        PushLimits::default(),
        &AtomicBool::new(false),
    )
    .unwrap();
    let report = send_local(
        pushed.git_dir(),
        girt::push::LocalPushRequest::new(&prepared),
        girt::transport::TransportControl::new(&AtomicBool::new(false)),
        |_| {},
    )
    .unwrap();
    assert!(report.all_succeeded());
    assert_eq!(
        pushed
            .references()
            .unwrap()
            .resolve_with(&RefName::new("refs/heads/main").unwrap(), 8)
            .unwrap()
            .id,
        Some(id)
    );
    assert_eq!(git_cat_file(&pushed, id), git_cat_file(&source, id));
}

#[rstest]
#[case::sha1_files(ObjectFormat::Sha1, Backend::Files)]
#[case::sha1_reftable(ObjectFormat::Sha1, Backend::Reftable)]
#[case::sha256_files(ObjectFormat::Sha256, Backend::Files)]
#[case::sha256_reftable(ObjectFormat::Sha256, Backend::Reftable)]
fn native_push_deletes_one_ref_and_creates_another(
    #[case] format: ObjectFormat,
    #[case] backend: Backend,
) {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", format, backend);
    let dest = repository(&root, "dest", format, backend);
    let id = commit(&source);
    let objects = source.objects_with(PackLimits::default()).unwrap();
    let cancel = AtomicBool::new(false);
    let old = PushCommand::new(RefName::new("refs/for/main").unwrap(), None, id)
        .with_force(ForcePolicy::FastForwardOnly);
    let prepared =
        PreparedPush::new(&objects, vec![old], &[], PushLimits::default(), &cancel).unwrap();
    assert!(
        send_local(
            dest.git_dir(),
            girt::push::LocalPushRequest::new(&prepared),
            girt::transport::TransportControl::new(&cancel),
            |_| {}
        )
        .unwrap()
        .all_succeeded()
    );

    let commands = vec![
        PushCommand::new(
            RefName::new("refs/for/main").unwrap(),
            Some(id),
            girt::ObjectId::null(format),
        )
        .with_force(ForcePolicy::FastForwardOnly),
        PushCommand::new(RefName::new("refs/tags/main").unwrap(), None, id)
            .with_force(ForcePolicy::FastForwardOnly),
    ];
    let prepared =
        PreparedPush::new(&objects, commands, &[], PushLimits::default(), &cancel).unwrap();
    assert!(
        send_local(
            dest.git_dir(),
            girt::push::LocalPushRequest::new(&prepared),
            girt::transport::TransportControl::new(&cancel),
            |_| {}
        )
        .unwrap()
        .all_succeeded()
    );
    let refs = dest.references().unwrap();
    assert_eq!(
        refs.read(&RefName::new("refs/for/main").unwrap()).unwrap(),
        None
    );
    assert_eq!(
        refs.read(&RefName::new("refs/tags/main").unwrap()).unwrap(),
        Some(Target::Direct(id))
    );
}

#[test]
fn native_fetch_rejects_missing_source_object_without_installation() {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", ObjectFormat::Sha1, Backend::Files);
    let id = girt::ObjectId::for_blob(ObjectFormat::Sha1, b"missing");
    source
        .references()
        .unwrap()
        .update_without_reflog(
            &RefName::new("refs/heads/main").unwrap(),
            Target::Direct(id),
            Expected::Absent,
        )
        .unwrap();
    let result = receive_local(
        source.git_dir(),
        |_| vec![id],
        girt::fetch::LocalFetchRequest::new(FetchLimits::default()),
        girt::transport::TransportControl::new(&AtomicBool::new(false)),
        girt::fetch::LocalFetchObserver::default(),
    );
    assert!(matches!(result, Err(FetchError::Missing(missing)) if missing == id));
}

/// Publishes `main` at a commit whose root tree has `entries`, written without Git's mode checks.
fn commit_tree(repository: &Repository, entries: Vec<girt::TreeEntry>) -> girt::ObjectId {
    let store = repository.loose_objects();
    let tree = Tree::new(repository.object_format(), entries).unwrap();
    store.write_tree(&tree).unwrap();
    let person = Signature {
        name: b"Local Test".to_vec(),
        email: b"local@example.invalid".to_vec(),
        seconds: 1_700_000_000,
        offset_minutes: 0,
    };
    let id = store
        .write_commit(
            &Commit::new(CommitFields {
                tree: tree.id(),
                parents: vec![],
                author: person.clone(),
                committer: person,
                extra_headers: vec![],
                message: b"Repeated entries\n".to_vec(),
            })
            .unwrap(),
        )
        .unwrap();
    repository
        .references()
        .unwrap()
        .update_without_reflog(
            &RefName::new("refs/heads/main").unwrap(),
            Target::Direct(id),
            Expected::Any,
        )
        .unwrap();
    id
}

/// Trees name one object many times; the selection walk reads it once and checks every edge's
/// kind against the first, whether or not the object has been read yet.
#[test]
fn native_fetch_checks_every_kind_of_a_repeated_entry() {
    use girt::EntryMode;
    let entry = |mode, name: &str, id| girt::TreeEntry {
        mode,
        name: name.as_bytes().to_vec(),
        id,
    };
    let fetch = |source: &Repository, tip| {
        receive_local(
            source.git_dir(),
            |_| vec![tip],
            girt::fetch::LocalFetchRequest::new(FetchLimits::default()),
            girt::transport::TransportControl::new(&AtomicBool::new(false)),
            girt::fetch::LocalFetchObserver::default(),
        )
    };
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", ObjectFormat::Sha1, Backend::Files);
    let store = source.loose_objects();
    let blob = store.write_blob(b"shared\n").unwrap();
    let nested = Tree::new(ObjectFormat::Sha1, vec![entry(EntryMode::Blob, "x", blob)]).unwrap();
    store.write_tree(&nested).unwrap();
    let tip = commit_tree(
        &source,
        vec![
            entry(EntryMode::Blob, "a", blob),
            entry(EntryMode::Executable, "b", blob),
            entry(EntryMode::Tree, "c", nested.id()),
            entry(EntryMode::Tree, "d", nested.id()),
        ],
    );
    let received = fetch(&source, tip).unwrap();
    assert_eq!(received.wants(), [tip]);

    let tip = commit_tree(
        &source,
        vec![
            entry(EntryMode::Blob, "a", blob),
            entry(EntryMode::Tree, "b", blob),
        ],
    );
    assert!(matches!(fetch(&source, tip), Err(FetchError::Kind(id)) if id == blob));
}

#[rstest]
#[case::sha1(ObjectFormat::Sha1)]
#[case::sha256(ObjectFormat::Sha256)]
fn native_fetch_materializes_absent_canonical_empty_tree(#[case] format: ObjectFormat) {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", format, Backend::Files);
    let destination = repository(&root, "destination", format, Backend::Files);
    let id = commit(&source);
    let empty_tree = Tree::new(format, vec![]).unwrap().id();
    let hex = empty_tree.to_string();
    std::fs::remove_file(source.object_dir().join(&hex[..2]).join(&hex[2..])).unwrap();

    let cancel = AtomicBool::new(false);
    let received = receive_local(
        source.git_dir(),
        |_| vec![id],
        girt::fetch::LocalFetchRequest::new(FetchLimits::default()),
        girt::transport::TransportControl::new(&cancel),
        girt::fetch::LocalFetchObserver::default(),
    )
    .unwrap();
    received
        .install(&destination, PackLimits::default(), &cancel)
        .unwrap();
    let tree = destination
        .objects_with(PackLimits::default())
        .unwrap()
        .read_with(empty_tree, Default::default())
        .unwrap()
        .unwrap();
    assert_eq!(tree.kind(), girt::ObjectKind::Tree);
    assert!(tree.data().is_empty());
}

#[test]
fn resolved_file_url_fetches_from_local_storage() {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source path", ObjectFormat::Sha1, Backend::Files);
    let id = commit(&source);
    let path = plain_local_path(source.git_dir())
        .replace('\\', "/")
        .replace(' ', "%20");
    let url = if cfg!(windows) {
        format!("file:///{path}")
    } else {
        format!("file://{path}")
    };
    let config = Config::parse(format!("[remote \"origin\"]\nurl = {url}\n").as_bytes()).unwrap();
    let remote = girt::remote::Remote::find(&config, b"origin")
        .unwrap()
        .unwrap();
    let destination = remote
        .fetch_destination(&config, &Default::default())
        .unwrap();
    let received = receive_local(
        destination.local_path().unwrap(),
        |_| vec![id],
        girt::fetch::LocalFetchRequest::new(FetchLimits::default()),
        girt::transport::TransportControl::new(&AtomicBool::new(false)),
        girt::fetch::LocalFetchObserver::default(),
    )
    .unwrap();
    assert_eq!(received.wants(), &[id]);
}

#[test]
fn native_fetch_rejects_corrupt_source_object() {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", ObjectFormat::Sha1, Backend::Files);
    let id = commit(&source);
    let hex = id.to_string();
    let path = source.object_dir().join(&hex[..2]).join(&hex[2..]);
    std::fs::write(path, b"corrupt loose object").unwrap();
    let result = receive_local(
        source.git_dir(),
        |_| vec![id],
        girt::fetch::LocalFetchRequest::new(FetchLimits::default()),
        girt::transport::TransportControl::new(&AtomicBool::new(false)),
        girt::fetch::LocalFetchObserver::default(),
    );
    assert!(matches!(result, Err(FetchError::LocalRead { id: failed, .. }) if failed == id));
}

#[test]
fn native_fetch_callback_interruption_returns_no_pack() {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", ObjectFormat::Sha256, Backend::Reftable);
    let id = commit(&source);
    let result = receive_local(
        source.git_dir(),
        |_| vec![id],
        girt::fetch::LocalFetchRequest::new(FetchLimits::default()),
        girt::transport::TransportControl::new(&AtomicBool::new(false)),
        girt::fetch::LocalFetchObserver::default().with_messages(&mut |_| ControlFlow::Break(())),
    );
    assert!(matches!(result, Err(FetchError::Cancelled)));
}

/// Git treats the canonical empty tree as present everywhere, so a push whose history reaches it
/// must succeed or reject per reference when neither repository stores it.
#[rstest]
#[case::sha1(ObjectFormat::Sha1)]
#[case::sha256(ObjectFormat::Sha256)]
fn native_push_accepts_history_reaching_unstored_empty_tree(#[case] format: ObjectFormat) {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", format, Backend::Files);
    let dest = repository(&root, "dest", format, Backend::Files);
    let empty_tree = Tree::new(format, vec![]).unwrap().id();
    let person = Signature {
        name: b"Local Test".to_vec(),
        email: b"local@example.invalid".to_vec(),
        seconds: 1_700_000_000,
        offset_minutes: 0,
    };
    let write = |repository: &Repository, parents, message: &[u8]| {
        let commit = Commit::new(CommitFields {
            tree: empty_tree,
            parents,
            author: person.clone(),
            committer: person.clone(),
            extra_headers: vec![],
            message: message.to_vec(),
        })
        .unwrap();
        repository.loose_objects().write_commit(&commit).unwrap()
    };
    // Both repositories store the commits but not the tree, as when another tool writes them.
    let main = RefName::new("refs/heads/main").unwrap();
    let mut parent = None;
    let mut child = None;
    for repository in [&source, &dest] {
        let first = write(repository, vec![], b"Parent\n");
        let second = write(repository, vec![first], b"Child\n");
        repository
            .references()
            .unwrap()
            .update_without_reflog(&main, Target::Direct(second), Expected::Absent)
            .unwrap();
        (parent, child) = (Some(first), Some(second));
    }
    let (parent, child) = (parent.unwrap(), child.unwrap());

    // `parent` is stored by the destination but isn't a reference tip, so the pack is empty and
    // validation walks `parent` down to the unstored empty tree.
    let copy = RefName::new("refs/heads/copy").unwrap();
    let commands = vec![
        PushCommand::new(main.clone(), None, parent).with_force(ForcePolicy::FastForwardOnly),
        PushCommand::new(copy.clone(), None, parent).with_force(ForcePolicy::FastForwardOnly),
    ];
    let cancel = AtomicBool::new(false);
    let prepared = PreparedPush::new(
        &source.objects_with(PackLimits::default()).unwrap(),
        commands,
        &[child],
        PushLimits::default(),
        &cancel,
    )
    .unwrap();
    let report = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&prepared),
        girt::transport::TransportControl::new(&cancel),
        |_| {},
    )
    .unwrap();
    assert_eq!(
        report.refs[0].rejection_origin,
        Some(RejectionOrigin::ExpectedValue)
    );
    assert_eq!(report.refs[1].status, Some(girt::push::Status::Ok));
    let refs = dest.references().unwrap();
    assert_eq!(refs.read(&main).unwrap(), Some(Target::Direct(child)));
    assert_eq!(refs.read(&copy).unwrap(), Some(Target::Direct(parent)));
    // The accepted update depends on the tree, so the destination now stores it.
    let hex = empty_tree.to_string();
    assert!(dest.object_dir().join(&hex[..2]).join(&hex[2..]).exists());
    let output = Command::new("git")
        .arg("--git-dir")
        .arg(plain_local_path(dest.git_dir()))
        .args(["fsck", "--connectivity-only"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
#[test]
fn receive_hooks_on_unsupported_platform_refuse_before_mutation() {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", ObjectFormat::Sha1, Backend::Files);
    let destination = repository(&root, "destination", ObjectFormat::Sha1, Backend::Files);
    let id = commit(&source);
    let path = destination.git_dir().join("hooks/pre-receive");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, b"hook must not execute").unwrap();
    let prepared = PreparedPush::new(
        &source.objects_with(PackLimits::default()).unwrap(),
        vec![
            PushCommand::new(RefName::new(b"refs/heads/main").unwrap(), None, id)
                .with_force(ForcePolicy::FastForwardOnly),
        ],
        &[],
        PushLimits::default(),
        &AtomicBool::new(false),
    )
    .unwrap();
    let error = send_local(
        destination.git_dir(),
        girt::push::LocalPushRequest::new(&prepared),
        girt::transport::TransportControl::new(&AtomicBool::new(false)),
        |_| {},
    )
    .unwrap_err();
    assert!(matches!(
        error,
        PushError::NotSent(PushFailure::Unsupported(
            "receive hook execution on this platform"
        ))
    ));
    assert!(
        destination
            .objects_with(PackLimits::default())
            .unwrap()
            .read_with(id, Default::default())
            .unwrap()
            .is_none()
    );
    assert!(
        destination
            .references()
            .unwrap()
            .read(&RefName::new(b"refs/heads/main").unwrap())
            .unwrap()
            .is_none()
    );
}

#[cfg(unix)]
fn git_unstored_empty_tree_commit(
    repository: &Repository,
    tree: girt::ObjectId,
    parent: Option<girt::ObjectId>,
) -> girt::ObjectId {
    let mut command = Command::new("git");
    for (key, _) in std::env::vars_os() {
        if key.to_string_lossy().starts_with("GIT_") {
            command.env_remove(key);
        }
    }
    command
        .arg("--git-dir")
        .arg(repository.git_dir())
        .args([
            "-c",
            "commit.gpgsign=false",
            "commit-tree",
            &tree.to_string(),
        ])
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env(
            "GIT_CONFIG_GLOBAL",
            repository.git_dir().join("absent-config"),
        )
        .env("GIT_AUTHOR_NAME", "Local Test")
        .env("GIT_AUTHOR_EMAIL", "local@example.invalid")
        .env("GIT_COMMITTER_NAME", "Local Test")
        .env("GIT_COMMITTER_EMAIL", "local@example.invalid")
        .env("GIT_AUTHOR_DATE", "@1700000000 +0000")
        .env("GIT_COMMITTER_DATE", "@1700000000 +0000")
        .stdin(std::process::Stdio::null());
    if let Some(parent) = parent {
        command.args(["-p", &parent.to_string()]);
    }
    let output = command.output().unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    std::str::from_utf8(&output.stdout)
        .unwrap()
        .trim()
        .parse()
        .unwrap()
}

#[cfg(unix)]
#[rstest]
#[case::sha1(ObjectFormat::Sha1)]
#[case::sha256(ObjectFormat::Sha256)]
fn pre_receive_rejection_does_not_materialize_unstored_empty_tree(#[case] format: ObjectFormat) {
    use std::os::unix::fs::PermissionsExt;
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", format, Backend::Files);
    let dest = repository(&root, "destination", format, Backend::Files);
    let tree = Tree::new(format, vec![]).unwrap().id();
    let parent = git_unstored_empty_tree_commit(&source, tree, None);
    let child = git_unstored_empty_tree_commit(&source, tree, Some(parent));
    let parent_commit = Commit::parse(format, &git_cat_file(&source, parent)).unwrap();
    let child_commit = Commit::parse(format, &git_cat_file(&source, child)).unwrap();
    assert_eq!(
        dest.loose_objects().write_commit(&parent_commit).unwrap(),
        parent
    );
    assert_eq!(
        dest.loose_objects().write_commit(&child_commit).unwrap(),
        child
    );
    dest.references()
        .unwrap()
        .update_without_reflog(
            &RefName::new(b"refs/heads/main").unwrap(),
            Target::Direct(child),
            Expected::Absent,
        )
        .unwrap();
    let hex = tree.to_string();
    let relative_tree = format!("{}/{}", &hex[..2], &hex[2..]);
    assert!(!dest.object_dir().join(&relative_tree).exists());
    let path = dest.git_dir().join("hooks/pre-receive");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, format!("#!/bin/sh\ntest -f \"$GIT_OBJECT_DIRECTORY/{relative_tree}\" || exit 9\ngit cat-file -e {tree} || exit 9\nprintf visible >hook-observed\ncat >/dev/null\nexit 1\n")).unwrap();
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
    let prepared = PreparedPush::new(
        &source.objects_with(PackLimits::default()).unwrap(),
        vec![
            PushCommand::new(RefName::new(b"refs/heads/copy").unwrap(), None, parent)
                .with_force(ForcePolicy::FastForwardOnly),
        ],
        &[child],
        PushLimits::default(),
        &AtomicBool::new(false),
    )
    .unwrap();
    let report = send_local(
        dest.git_dir(),
        girt::push::LocalPushRequest::new(&prepared),
        girt::transport::TransportControl::new(&AtomicBool::new(false)),
        |_| {},
    )
    .unwrap();
    assert_eq!(
        report.refs[0].status,
        Some(girt::push::Status::Rejected(
            b"pre-receive hook declined".to_vec()
        ))
    );
    assert_eq!(
        std::fs::read(dest.git_dir().join("hook-observed")).unwrap(),
        b"visible"
    );
    assert!(!dest.object_dir().join(relative_tree).exists());
    assert!(
        dest.references()
            .unwrap()
            .read(&RefName::new(b"refs/heads/copy").unwrap())
            .unwrap()
            .is_none()
    );
    assert_eq!(
        dest.references()
            .unwrap()
            .read(&RefName::new(b"refs/heads/main").unwrap())
            .unwrap(),
        Some(Target::Direct(child))
    );
}

/// Runs Git in `directory` without global or system configuration, returning trimmed stdout.
fn git_in(directory: &std::path::Path, args: &[&str]) -> String {
    let output = Command::new("git")
        .current_dir(directory)
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_CONFIG_GLOBAL", directory.join("absent-config"))
        .args([
            "-c",
            "user.name=Local Test",
            "-c",
            "user.email=local@example.invalid",
        ])
        .args(args)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "git {args:?}: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8(output.stdout).unwrap().trim().to_owned()
}

/// Builds a Git-written source with one packed commit; returns its path, tip and `.idx` size.
fn packed_git_source(root: &tempfile::TempDir) -> (std::path::PathBuf, girt::ObjectId, usize) {
    let path = root.path().join("source");
    std::fs::create_dir(&path).unwrap();
    git_in(&path, &["init", "-q", "--template=", "-b", "main"]);
    std::fs::write(path.join("file"), b"packed source\n").unwrap();
    git_in(&path, &["add", "file"]);
    git_in(&path, &["commit", "-q", "-m", "packed"]);
    git_in(&path, &["repack", "-adq"]);
    let tip = git_in(&path, &["rev-parse", "HEAD"]).parse().unwrap();
    let pack_dir = path.join(".git/objects/pack");
    let index = std::fs::read_dir(&pack_dir)
        .unwrap()
        .map(|entry| entry.unwrap().path())
        .find(|path| path.extension().is_some_and(|ext| ext == "idx"))
        .unwrap();
    let index_len = std::fs::metadata(index).unwrap().len().try_into().unwrap();
    (path, tip, index_len)
}

/// The source store opens under `FetchLimits::source_packs`, not a fixed default: a source whose
/// index exceeds the bound is refused as a source failure, and one within it is fetched intact.
#[rstest]
#[case::index_over_limit(1, false)]
#[case::index_at_limit(0, true)]
fn native_fetch_opens_source_within_source_pack_limits(
    #[case] below_index: usize,
    #[case] fetched: bool,
) {
    let root = tempfile::tempdir().unwrap();
    let (source, tip, index_len) = packed_git_source(&root);
    let limits = FetchLimits::default()
        .with_source_packs(PackLimits::default().with_max_index_bytes(index_len - below_index));
    let received = receive_local(
        &source,
        |_| vec![tip],
        girt::fetch::LocalFetchRequest::new(limits),
        TransportControl::new(&AtomicBool::new(false)),
        girt::fetch::LocalFetchObserver::default(),
    );
    let discovered = discover_local(
        &source,
        limits,
        TransportControl::new(&AtomicBool::new(false)),
    );
    assert_eq!(
        received.as_ref().err().map(ToString::to_string),
        (!fetched).then(|| "opening source object store".to_owned())
    );
    assert_eq!(
        matches!(received, Err(FetchError::SourceObjects(_))),
        !fetched
    );
    assert_eq!(
        matches!(discovered, Err(FetchError::SourceObjects(_))),
        !fetched
    );
    assert_eq!(discovered.is_ok(), fetched);
    let destination = repository(&root, "destination", ObjectFormat::Sha1, Backend::Files);
    let installed = received.map(|received| {
        received
            .install(&destination, PackLimits::default(), &AtomicBool::new(false))
            .unwrap();
        git_in(
            destination.git_dir(),
            &["cat-file", "-p", &format!("{tip}^{{tree}}:file")],
        )
    });
    assert_eq!(installed.ok(), fetched.then(|| "packed source".to_owned()));
}

/// Native local push opens the destination store under `PushLimits::destination_packs`, not a
/// fixed default: a Git-packed destination whose index exceeds the bound refuses the push before
/// any reference changes, and the default bound accepts it with Git-readable results.
#[rstest]
#[case::index_over_limit(Some(1), None)]
#[case::default_limits(None, Some(()))]
fn native_push_opens_destination_within_destination_pack_limits(
    #[case] below_index: Option<usize>,
    #[case] pushed: Option<()>,
) {
    let root = tempfile::tempdir().unwrap();
    let (destination, _, index_len) = packed_git_source(&root);
    let source = repository(&root, "pusher", ObjectFormat::Sha1, Backend::Files);
    let id = commit(&source);
    let packs = below_index.map_or_else(PackLimits::default, |below| {
        PackLimits::default().with_max_index_bytes(index_len - below)
    });
    let command = PushCommand::new(RefName::new("refs/heads/pushed").unwrap(), None, id);
    let identity = Signature {
        name: b"Local Test".to_vec(),
        email: b"local@example.invalid".to_vec(),
        seconds: 1_700_000_000,
        offset_minutes: 0,
    };
    let cancel = AtomicBool::new(false);
    let objects = source.objects_with(PackLimits::default()).unwrap();
    let prepared = PreparedPush::new(
        &objects,
        vec![command],
        &[],
        PushLimits::default().with_destination_packs(packs),
        &cancel,
    )
    .unwrap();
    let result = send_local(
        &destination,
        girt::push::LocalPushRequest::new(&prepared).with_identity(Some(&identity)),
        TransportControl::new(&cancel),
        |_| {},
    );
    assert_eq!(
        result.as_ref().map(|report| report.all_succeeded()).ok(),
        pushed.map(|()| true)
    );
    let limit_cause = match &result {
        Err(PushError::NotSent(PushFailure::Install(error))) => match error.as_ref() {
            FetchError::Destination(cause) => Some(cause.to_string()),
            _ => None,
        },
        _ => None,
    };
    assert_eq!(
        limit_cause,
        pushed
            .is_none()
            .then(|| "object storage limit exceeded: pack index bytes".to_owned())
    );
    let observed = git_in(
        &destination,
        &[
            "for-each-ref",
            "--format=%(objectname)",
            "refs/heads/pushed",
        ],
    );
    assert_eq!(
        (!observed.is_empty()).then(|| observed.parse::<girt::ObjectId>().unwrap()),
        pushed.map(|()| id)
    );
    git_in(&destination, &["fsck", "--strict"]);
}

#[rstest]
#[case(ObjectFormat::Sha1)]
#[case(ObjectFormat::Sha256)]
fn configured_clone_no_checkout_is_portable_and_checkout_preserves_platform_scope(
    #[case] format: ObjectFormat,
) {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", format, Backend::Files);
    let id = commit(&source);
    let url = source.git_dir().to_str().unwrap();
    let environment = girt::workflow::Environment::default();
    let inputs = ConfigInputs::default();
    let options = girt::workflow::CloneOptions::default().with_checkout(false);
    let outcome = girt::workflow::clone_with(
        url,
        root.path().join("no-checkout"),
        &options,
        &inputs,
        &environment,
        &mut girt::workflow::NoCallbacks,
    )
    .unwrap();
    let cloned = outcome.clone.repository.unwrap();
    assert_eq!(cloned.head().unwrap().id, Some(id));
    assert!(!cloned.git_dir().join("index").exists());
    // The persisted absolute URL remains usable with a later fetch from another current directory.
    let configured = girt::remote::Remote::find(cloned.config(), b"origin")
        .unwrap()
        .unwrap();
    girt::workflow::fetch(
        &cloned,
        "origin",
        &girt::workflow::FetchOptions::new(
            configured
                .fetch_refspecs()
                .specs()
                .iter()
                .map(|spec| spec.as_bytes()),
        ),
        &environment,
        &mut girt::workflow::NoCallbacks,
    )
    .unwrap();
    let checked_out = girt::workflow::clone_with(
        url,
        root.path().join("checkout"),
        &Default::default(),
        &inputs,
        &environment,
        &mut girt::workflow::NoCallbacks,
    );
    if cfg!(any(target_os = "linux", target_os = "macos")) {
        assert!(checked_out.unwrap().checkout.unwrap().index_published);
    } else {
        let girt::workflow::CloneError::UnsupportedCheckout = checked_out.unwrap_err() else {
            panic!("expected unsupported checkout");
        };
        assert!(!root.path().join("checkout").exists());
    }
}

/// Names of the reflogs under `git_dir`, relative to its `logs` directory.
fn reflog_names(git_dir: &std::path::Path) -> std::collections::BTreeSet<String> {
    fn walk(
        root: &std::path::Path,
        directory: &std::path::Path,
        names: &mut std::collections::BTreeSet<String>,
    ) {
        let Ok(entries) = std::fs::read_dir(directory) else {
            return;
        };
        for entry in entries {
            let path = entry.unwrap().path();
            if path.is_dir() {
                walk(root, &path, names);
            } else {
                let name = path.strip_prefix(root).unwrap().to_string_lossy();
                names.insert(name.replace('\\', "/"));
            }
        }
    }
    let mut names = std::collections::BTreeSet::new();
    let root = git_dir.join("logs");
    walk(&root, &root, &mut names);
    names
}

#[rstest]
#[case::default(None, false)]
#[case::always(Some("always"), false)]
#[case::disabled(Some("false"), false)]
#[case::existing_tag_log(None, true)]
fn workflow_fetch_reflogs_follow_core_log_all_ref_updates_like_git(
    #[case] setting: Option<&str>,
    #[case] existing_tag_log: bool,
) {
    let root = tempfile::tempdir().unwrap();
    let source = repository(&root, "source", ObjectFormat::Sha1, Backend::Files);
    commit(&source);
    git_in(source.git_dir(), &["tag", "v1", "main"]);
    let url = plain_local_path(source.git_dir());
    let refspecs = [
        "+refs/heads/*:refs/remotes/origin/*",
        "+refs/tags/*:refs/tags/*",
        "+refs/tags/*:refs/remote-tags/origin/*",
    ];
    let prepare = |name: &str| {
        let path = root.path().join(name);
        git_in(root.path(), &["init", "-q", name]);
        git_in(&path, &["remote", "add", "origin", &url]);
        if let Some(setting) = setting {
            git_in(&path, &["config", "core.logAllRefUpdates", setting]);
        }
        if existing_tag_log {
            let log = path.join(".git/logs/refs/tags/v1");
            std::fs::create_dir_all(log.parent().unwrap()).unwrap();
            std::fs::write(log, b"").unwrap();
        }
        path
    };

    let with_git = prepare("git");
    let mut fetch = vec!["fetch", "-q", "--no-auto-maintenance", "origin"];
    fetch.extend(refspecs);
    git_in(&with_git, &fetch);

    let with_girt = Repository::open(prepare("girt")).unwrap();
    let person = Signature {
        name: b"Local Test".to_vec(),
        email: b"local@example.invalid".to_vec(),
        seconds: 1_700_000_000,
        offset_minutes: 0,
    };
    girt::workflow::fetch(
        &with_girt,
        "origin",
        &girt::workflow::FetchOptions::new(refspecs)
            .with_tag_namespace(RefName::new("refs/remote-tags/origin").unwrap())
            .with_reflog(person, "fetch origin"),
        &girt::workflow::Environment::default(),
        &mut girt::workflow::NoCallbacks,
    )
    .unwrap();

    let expected = reflog_names(&with_git.join(".git"));
    assert!(expected.contains("refs/remotes/origin/main") == (setting != Some("false")));
    assert_eq!(reflog_names(with_girt.git_dir()), expected);
}

fn git(dir: &std::path::Path, args: &[&str]) -> String {
    let output = Command::new("git")
        .arg("-C")
        .arg(plain_local_path(dir))
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .args(["-c", "user.name=T", "-c", "user.email=t@example.invalid"])
        .args(args)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8(output.stdout).unwrap()
}

fn object_ids(dir: &std::path::Path) -> std::collections::BTreeSet<String> {
    git(
        dir,
        &[
            "cat-file",
            "--batch-all-objects",
            "--batch-check=%(objectname)",
        ],
    )
    .lines()
    .map(str::to_owned)
    .collect()
}

/// A clone from a source with a bitmap selects through it. The destination receives the same
/// objects as from a walk, including when it already holds one of them and the walk must run.
#[rstest]
#[case::sha1_bitmap(ObjectFormat::Sha1, true, false)]
#[case::sha1_walk(ObjectFormat::Sha1, false, false)]
#[case::sha1_bitmap_stored(ObjectFormat::Sha1, true, true)]
#[case::sha256_bitmap(ObjectFormat::Sha256, true, false)]
fn native_fetch_with_source_bitmap_receives_every_reachable_object(
    #[case] format: ObjectFormat,
    #[case] bitmap: bool,
    #[case] stored: bool,
) {
    let root = tempfile::tempdir().unwrap();
    let work = root.path().join("work");
    let format_name = match format {
        ObjectFormat::Sha1 => "sha1",
        _ => "sha256",
    };
    std::fs::create_dir(&work).unwrap();
    git(
        &work,
        &["init", "-q", "-b", "main", "--object-format", format_name],
    );
    for round in 0..4 {
        std::fs::create_dir_all(work.join("dir")).unwrap();
        std::fs::write(work.join("shared"), b"shared\n").unwrap();
        std::fs::write(work.join("dir/file"), format!("round {round}\n")).unwrap();
        git(&work, &["add", "-A"]);
        git(&work, &["commit", "-q", "-m", &format!("round {round}")]);
        if round == 1 {
            git(&work, &["tag", "-a", "-m", "tag", "v1"]);
            git(&work, &["branch", "old"]);
        }
    }
    git(&work, &["repack", "-adq", "--write-bitmap-index"]);
    let source = work.join(".git");
    let packs = source.join("objects/pack");
    let has_bitmap = std::fs::read_dir(&packs)
        .unwrap()
        .any(|entry| entry.unwrap().path().extension() == Some("bitmap".as_ref()));
    assert!(has_bitmap);
    if !bitmap {
        for entry in std::fs::read_dir(&packs).unwrap() {
            let path = entry.unwrap().path();
            if path.extension() == Some("bitmap".as_ref()) {
                std::fs::remove_file(path).unwrap();
            }
        }
    }
    let destination = repository(&root, "destination", format, Backend::Files);
    if stored {
        destination.loose_objects().write_blob(b"shared\n").unwrap();
    }
    let known = girt::fetch::KnownHistory::from_store(
        destination.objects().unwrap(),
        &[],
        FetchLimits::default(),
        &AtomicBool::new(false),
    )
    .unwrap();
    let received = receive_local(
        &source,
        |advertisement| {
            advertisement
                .refs
                .iter()
                .map(|reference| reference.id)
                .collect()
        },
        girt::fetch::LocalFetchRequest::new(FetchLimits::default()).with_known(&known),
        girt::transport::TransportControl::new(&AtomicBool::new(false)),
        girt::fetch::LocalFetchObserver::default(),
    )
    .unwrap();
    received
        .install(&destination, PackLimits::default(), &AtomicBool::new(false))
        .unwrap();
    assert_eq!(object_ids(destination.git_dir()), object_ids(&source));
}