grit-lib 0.5.25

Core library for the grit Git implementation
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
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
//! Snapshot checkouts: start work on a repository without cloning its history.
//!
//! A server that offers snapshot checkouts (`grit serve` does) answers under
//! its own endpoint, `/.grit/checkouts/<repository>`, separate from the Git
//! smart-HTTP paths, so a client can tell a server that has them from one that
//! doesn't. A checkout is one **snapshot commit**: the target branch's tree,
//! cut down to the paths asked for (as Git's cone-mode sparse checkout has
//! them: everything under each path, plus the files directly in every
//! directory above one), in a commit with fixed metadata whose message names
//! the real commit it stands for. Because the metadata is fixed, every
//! checkout of the same paths at the same commit gets the same snapshot.
//!
//! The server hands the snapshot out as a bundle, which the client downloads
//! with [`crate::resumable::download_resumable`] (so an interrupted checkout
//! resumes) and turns into a new repository whose history is that one commit,
//! with the snapshot at [`upstream_ref`] (`refs/remotes/origin/<branch>`) and a
//! new work branch on top of it checked out. Its `origin` fetches only the
//! checkout's snapshots ([`snapshot_fetch_refspec`], no tags) and pushes to the
//! check-in area ([`out_push_refspec`]), so plain `git` and `grit` fetches and
//! pushes in a checkout never bring the full history or touch the server's
//! real branches.
//!
//! - Wire types: [`CheckoutServerInfo`], [`CheckoutRequest`], [`CheckoutInfo`].
//! - Server side: [`normalize_paths`], [`filtered_tree`], [`snapshot_object`],
//!   [`make_snapshot`], [`fetch_promised_blobs`], [`project_branch`].
//! - Client side: [`CheckoutUrl`], [`CheckoutClient`], [`materialize`],
//!   [`CheckoutMarker`], [`push_for_checkin`], [`fetch_snapshot`], [`refresh`],
//!   [`fetch_branch`], [`refresh_branch`].
//!
//! Work comes back with a **check-in**: the client gives commits made with
//! plain Git a change id ([`give_change_ids`]), pushes its branches' raw tips
//! to [`out_ref`] ([`push_for_checkin`]) and asks the server to [`graft`] them
//! onto the real history ([`graft_checkin_branch`]) and set the server's
//! branches ([`set_checked_in_branch`], deciding with [`decide_checkin`],
//! which also accepts a rebase that keeps every commit by change id:
//! [`keeps_every_commit`]). The
//! server can [`integrate`] a branch into the target with a merge commit, and
//! keeps **slices** — named sets of paths — in [`SLICES_PATH`] on the target
//! branch ([`edit_slices`]). Those are the only ways the target changes: the
//! server refuses plain pushes to it with a [`TargetGuard`]. A **refresh** asks the server for a snapshot of the newest target on
//! top of the checkout's last one ([`CheckoutClient::update`]), fetches it from
//! [`target_ref`] ([`fetch_snapshot`]) and brings the current branch onto it
//! ([`refresh`]). The client's transfers always go to the URL its marker
//! records, whatever `origin` has become. Once a checked-in branch has been
//! integrated into the branch the checkout snapshots, the checkout records
//! that it landed ([`land_integration`], [`record_landed`]), so refreshes
//! never replay its commits onto snapshots that already have them, and
//! [`Landing::move_off`] puts the user on a fresh work branch.
//!
//! Checkouts share a branch through **projection**, the reverse of a graft:
//! the server shows a checkout one of its branches cut down to the
//! checkout's paths on its snapshots ([`project`], [`project_branch`], asked
//! for with [`CheckoutClient::branch`]) at [`in_ref`], the client fetches it
//! ([`fetch_branch`]) and brings its branch of that name onto it
//! ([`refresh_branch`]). Grafts and projections record the pairs they make in
//! the repository's [`GraftLog`], so work built on a projected commit grafts
//! onto the real commit it stands for.
//!
//! The server keeps each checkout's record, the work-branch names it has
//! given out, and the graft log in a [`CheckoutStore`].

mod branch_refresh;
mod checkin;
mod graft;
mod graft_log;
mod guard;
mod ids;
mod landing;
mod project;
mod refresh;
mod refs;
mod store;
mod target;
#[cfg(test)]
mod testing;
mod transfer;
mod tree;

pub use branch_refresh::{refresh_branch, BranchRefresh, BranchRefreshResult};
pub use checkin::{
    decide_checkin, graft_checkin_branch, set_checked_in_branch, BranchSet, CheckinDecision,
    CheckinRefusal, CheckinRule,
};
pub use graft::{graft, GraftError, Grafted};
pub use graft_log::GraftLog;
pub use guard::TargetGuard;
pub use ids::{change_keys, give_change_ids, keeps_every_commit};
pub use landing::{land_integration, move_off_landed_branch, record_landed, Landing, MovedOff};
pub use project::{project, project_branch, ProjectError, ProjectedCommit, Projection};
pub use refresh::{
    ensure_refreshable, refresh, BranchOnOldSnapshot, FollowedBranch, RefreshOutcome, RefreshedHead,
};
pub use store::{valid_checkout_id, CheckoutRecord, CheckoutStore, ReservedName, StoredCheckout};
pub use target::{
    edit_slices, integrate, missing_paths, parse_slices, read_slices, render_slices,
    same_branch_name, target_branch, valid_slice_name, Integration, SliceEdit, SlicesEdited,
    TargetChange, TargetRefusal, SLICES_PATH,
};
pub use transfer::{fetch_branch, fetch_snapshot, push_for_checkin, FetchedSnapshot};

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::fetch::Progress;
use crate::objects::{
    parse_commit, parse_tree, serialize_tree, tree_entry_cmp, ObjectId, ObjectKind, TreeEntry,
};
use crate::odb::Odb;
use crate::progress::Cancel;
use crate::repo::{InitOptions, Repository};
use crate::transport::http::{HttpClient, HttpMethod, HttpRequest};

/// Path under the server root where snapshot checkouts are served:
/// `/.grit/checkouts/<repository>`.
pub const CHECKOUT_API: &str = ".grit/checkouts";

/// Name and email of every snapshot commit's author and committer.
pub const SNAPSHOT_IDENT: &str = "grit-checkout <snapshot@grit-checkout>";

/// Trailer naming the real commit a snapshot stands for.
pub const SNAPSHOT_BASE_TRAILER: &str = "Grit-Checkout-Base";

/// File in the repository's common git directory (shared by all its worktrees)
/// that marks it as a snapshot checkout.
pub const MARKER_FILE: &str = "grit-checkout.json";

const TREE_MODE: u32 = 0o040000;
const GITLINK_MODE: u32 = 0o160000;

/// `GET /.grit/checkouts/<repo>`: what the server would check out.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckoutServerInfo {
    /// The repository's name.
    pub name: String,
    /// The target branch checkouts start from.
    pub branch: String,
    /// Where the target branch is.
    pub head: String,
}

/// `POST /.grit/checkouts/<repo>`: make a checkout.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckoutRequest {
    /// Paths to check out; empty is the whole tree.
    #[serde(default)]
    pub paths: Vec<String>,
    /// What the client calls the checkout (its directory name), for the server's log.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client: Option<String>,
    /// The work branch name the client would like.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub work: Option<String>,
}

/// One snapshot commit of a checkout and the real commit it stands for.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SnapshotRoot {
    /// The snapshot commit.
    pub commit: String,
    /// The real commit of the target branch it stands for.
    pub base: String,
}

/// A checkout as the server knows it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckoutInfo {
    /// The checkout's id on the server.
    pub id: String,
    /// The repository's name, the default directory to check out into.
    pub name: String,
    /// The target branch.
    pub branch: String,
    /// The checkout's paths (normalized); empty is the whole tree.
    pub paths: Vec<String>,
    /// The real commit the newest snapshot stands for.
    pub base: String,
    /// The newest snapshot commit.
    pub root: String,
    /// That commit's exact bytes, so the client can check it rebuilt the same object.
    pub root_object: String,
    /// The snapshot's tree.
    pub tree: String,
    /// Every snapshot commit of the checkout, oldest first.
    pub roots: Vec<SnapshotRoot>,
    /// Files in the snapshot.
    pub files: u64,
    /// Bytes of those files.
    pub bytes: u64,
    /// Size of the bundle the snapshot downloads as.
    pub bundle_bytes: u64,
    /// The work branch the client should create: the one it asked for, numbered
    /// when the server already has a branch by that name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub work: Option<String>,
}

/// `GET /.grit/checkouts/<repo>/<id>`: a checkout as the server has it, and
/// where its target branch is now.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckoutState {
    /// The checkout's record.
    #[serde(flatten)]
    pub info: CheckoutInfo,
    /// Where the target branch is now, which is past [`CheckoutInfo::base`]
    /// when it moved since the last snapshot; `None` when the server no
    /// longer has the branch.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tip: Option<String>,
}

/// `POST /.grit/checkouts/<repo>/<id>/work`: reserve a fresh work branch for
/// checkout `id`, as making a checkout does ([`CheckoutRequest::work`]).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkBranchRequest {
    /// The name the client would like.
    pub work: String,
}

/// The answer to a [`WorkBranchRequest`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkBranchResponse {
    /// The name the server reserved: the one asked for, numbered past the
    /// server's branches and the names it gave out before. It is never given
    /// out again.
    pub work: String,
}

/// `POST /.grit/checkouts/<repo>/<id>/branch`: show the server's branch
/// `name` to checkout `id` ([`project_branch`]).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BranchRequest {
    /// The branch, without `refs/heads/`.
    pub name: String,
}

/// The answer to a [`BranchRequest`]: the server's branch as the checkout
/// sees it, at [`in_ref`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BranchInfo {
    /// The branch, as the server spells it, which can differ in case from the
    /// name asked for where the server ignores case.
    pub name: String,
    /// Where the server's branch is, on its real history.
    pub tip: String,
    /// Its projection for the checkout, at [`in_ref`].
    pub projected: String,
    /// The branch's commits the target lacks, all projected.
    pub commits: usize,
    /// How many of them were made afresh.
    #[serde(default)]
    pub made: usize,
    /// How many were shown as commits that were there already: checkout
    /// commits on the same snapshots that the server's are grafts of (the
    /// checkout's own among them), and earlier projections.
    #[serde(default)]
    pub reused: usize,
}

/// The ref a checkout's newest snapshot is kept at on the server.
#[must_use]
pub fn target_ref(id: &str) -> String {
    format!("refs/checkouts/{id}/target")
}

/// Whether `name` is a valid branch name (`refs/heads/<name>` is a valid ref).
#[must_use]
pub fn valid_branch_name(name: &str) -> bool {
    crate::check_ref_format::check_refname_format(
        &format!("refs/heads/{name}"),
        &crate::check_ref_format::RefNameOptions::default(),
    )
    .is_ok()
}

/// Where a checkout pushes its branch `name` for the server to graft.
#[must_use]
pub fn out_ref(id: &str, name: &str) -> String {
    format!("refs/checkouts/{id}/out/heads/{name}")
}

/// Where the server puts its branch `name` as checkout `id` sees it (its
/// projection, [`project_branch`]) for the checkout to fetch.
#[must_use]
pub fn in_ref(id: &str, name: &str) -> String {
    format!("refs/checkouts/{id}/in/heads/{name}")
}

/// The local ref a checkout keeps its newest snapshot of `branch` at:
/// `refs/remotes/origin/<branch>`.
#[must_use]
pub fn upstream_ref(branch: &str) -> String {
    format!("refs/remotes/origin/{branch}")
}

/// The refspec that fetches checkout `id`'s newest snapshot (at [`target_ref`]
/// on the server) into [`upstream_ref`]`(branch)`:
/// `+refs/checkouts/<id>/target:refs/remotes/origin/<branch>`.
///
/// A checkout's `origin` fetches with it, so a plain `git fetch` or
/// `grit fetch` there brings only snapshots, never the full history.
#[must_use]
pub fn snapshot_fetch_refspec(id: &str, branch: &str) -> String {
    format!("+{}:{}", target_ref(id), upstream_ref(branch))
}

/// The refspec a checkout's `origin` pushes with:
/// `+refs/heads/*:refs/checkouts/<id>/out/heads/*`.
///
/// A plain `git push` or `grit push` in a checkout then lands where check-ins
/// graft from ([`out_ref`]), never on the server's real branches.
#[must_use]
pub fn out_push_refspec(id: &str) -> String {
    format!("+refs/heads/*:{}", out_ref(id, "*"))
}

/// One branch of a check-in: its name and the tip the client pushed to
/// [`out_ref`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckinBranch {
    /// Branch name (without `refs/heads/`).
    pub name: String,
    /// The tip pushed to [`out_ref`].
    pub raw: String,
}

/// `POST /.grit/checkouts/<repo>/<id>/checkin`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckinRequest {
    /// The branches to check in.
    pub branches: Vec<CheckinBranch>,
    /// Set a branch even where it would drop commits the server has.
    #[serde(default)]
    pub force: bool,
}

/// What a check-in did to one branch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CheckinStatus {
    /// The server had no such branch; it does now.
    Created,
    /// The server's branch moved to the graft.
    Updated,
    /// The server's branch already had the branch's commits: it was at the
    /// graft, or ahead of it.
    Unchanged,
    /// The branch was not set.
    Refused,
}

/// The result for one branch of a check-in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckinResult {
    /// The branch.
    pub name: String,
    /// What happened.
    pub status: CheckinStatus,
    /// The commit on the server's history the branch's tip became.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grafted: Option<String>,
    /// Where the server's branch was before.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous: Option<String>,
    /// Commits replayed.
    #[serde(default)]
    pub commits: usize,
    /// For [`CheckinStatus::Updated`], the rule that allowed the update.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rule: Option<CheckinRule>,
    /// Why it was refused, in words.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// Why it was refused, for programs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<CheckinRefusal>,
}

/// The answer to a check-in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckinResponse {
    /// One result per branch, in request order.
    pub results: Vec<CheckinResult>,
}

/// Who did something.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ident {
    /// Name.
    pub name: String,
    /// Email address.
    pub email: String,
}

impl Ident {
    /// Who the user's own commits are by, for a server-made commit made for
    /// them (an integration's merge, a slice change): the author identity a
    /// commit gets, from `GIT_AUTHOR_NAME` and `GIT_AUTHOR_EMAIL`, then
    /// `author.*`, then `user.*` (see
    /// [`crate::config::ident_resolve::resolve_name_with`]).
    ///
    /// # Parameters
    ///
    /// - `env`: the environment to read `GIT_AUTHOR_*` and fallbacks from.
    /// - `config`: the repository's configuration.
    ///
    /// # Errors
    ///
    /// [`crate::config::ident_resolve::IdentityError`] when no name or email
    /// is configured; a server then uses the signed-in user.
    pub fn author<E: crate::ident_resolve::IdentityEnv>(
        env: &E,
        config: &crate::config::ConfigSet,
    ) -> std::result::Result<Self, crate::ident_resolve::IdentityError> {
        use crate::ident_resolve::{resolve_email_with, resolve_name_with, IdentRole};
        Ok(Self {
            name: resolve_name_with(env, config, IdentRole::Author)?,
            email: resolve_email_with(env, config, IdentRole::Author)?,
        })
    }

    /// The signature of a commit by this identity at `time`, cleaned of
    /// anything that would break the commit's header
    /// ([`crate::ident::Signature::cleaned`]), since a server takes
    /// identities from its requests. A name that cleans away to nothing is
    /// replaced by the email.
    ///
    /// # Errors
    ///
    /// [`crate::ident::SignatureError`] for a `time` before the epoch or with
    /// a sub-minute offset.
    pub fn signature(
        &self,
        time: time::OffsetDateTime,
    ) -> std::result::Result<crate::ident::Signature, crate::ident::SignatureError> {
        let signature = crate::ident::Signature::cleaned(&self.name, &self.email, time)?;
        if signature.name.is_empty() {
            return Ok(crate::ident::Signature {
                name: signature.email.clone(),
                ..signature
            });
        }
        Ok(signature)
    }
}

/// `POST /.grit/checkouts/<repo>/integrate`: merge a branch into the target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntegrateRequest {
    /// The branch on the server.
    pub name: String,
    /// Who the merge commit is by (the signed-in user when absent).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub author: Option<Ident>,
}

/// What an integration did.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IntegrateStatus {
    /// A merge commit moved the target.
    Merged,
    /// The target already had every commit of the branch.
    AlreadyIntegrated,
}

/// The answer to an integration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntegrateResponse {
    /// What happened.
    pub status: IntegrateStatus,
    /// The branch.
    pub name: String,
    /// The target branch.
    pub target: String,
    /// Where the target was.
    pub previous: String,
    /// Where it is now.
    pub head: String,
    /// The branch's commits the merge brought in.
    pub commits: usize,
}

/// A named set of paths to check out together.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Slice {
    /// The slice's name.
    pub name: String,
    /// What it is for.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Its paths.
    pub paths: Vec<String>,
}

/// `GET /.grit/checkouts/<repo>/slices`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlicesResponse {
    /// The target branch.
    pub target: String,
    /// Where it is.
    pub head: String,
    /// The slices on it.
    pub slices: Vec<Slice>,
}

/// `PUT /.grit/checkouts/<repo>/slices/<name>`: make or change a slice.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SliceRequest {
    /// The slice's paths.
    pub paths: Vec<String>,
    /// What it is for.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Make a new slice, refusing a name that exists; otherwise change one
    /// that does.
    #[serde(default)]
    pub create: bool,
    /// Who the commit is by (the signed-in user when absent).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub author: Option<Ident>,
}

/// `DELETE /.grit/checkouts/<repo>/slices/<name>`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SliceDeleteRequest {
    /// Who the commit is by (the signed-in user when absent).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub author: Option<Ident>,
}

/// What a change to the slices did.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SliceChange {
    /// The slice as it is now; none once deleted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slice: Option<Slice>,
    /// The target branch.
    pub target: String,
    /// Where it was.
    pub previous: String,
    /// Where it is: a commit changing the slices file, or `previous` when
    /// nothing changed.
    pub head: String,
}

/// An error body the checkout endpoints answer with.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckoutErrorBody {
    /// What went wrong.
    pub error: String,
}

/// Why a snapshot checkout failed.
#[derive(Debug, thiserror::Error)]
pub enum CheckoutError {
    /// The server has no snapshot-checkout endpoint for this repository.
    #[error("{url} offers no grit checkout (no {endpoint} endpoint); it may be a plain Git server, or the repository may not exist")]
    NotOffered {
        /// The URL the user gave.
        url: String,
        /// The endpoint that was missing.
        endpoint: String,
    },
    /// The server refused a request.
    #[error("{url}: {message} (HTTP {status})")]
    Server {
        /// The request URL.
        url: String,
        /// The response status.
        status: u16,
        /// The server's explanation.
        message: String,
    },
    /// The URL cannot name a repository.
    #[error("{0} is not an http(s) URL of a repository")]
    InvalidUrl(String),
    /// A path is not a plain path inside the repository.
    #[error("{path}: {reason}")]
    InvalidPath {
        /// The path as given.
        path: String,
        /// What is wrong with it.
        reason: &'static str,
    },
    /// A path is not in the tree being checked out.
    #[error("{path} is not in the repository at {base}")]
    MissingPath {
        /// The path.
        path: String,
        /// The commit it was looked up in.
        base: String,
    },
    /// The downloaded snapshot is not the one the server described.
    #[error("the downloaded snapshot is {got}, but the server described {expected}")]
    Mismatch {
        /// The snapshot commit the server described.
        expected: String,
        /// What the download held.
        got: String,
    },
    /// The destination already has files.
    #[error("{0} already exists and is not empty")]
    DestinationNotEmpty(PathBuf),
    /// A name is not a valid branch name.
    #[error("{0} is not a valid branch name")]
    InvalidBranchName(String),
    /// A checkout's stored record could not be read.
    #[error("the record of checkout {id} at {path} is damaged: {detail}")]
    DamagedRecord {
        /// The checkout's id.
        id: String,
        /// The record's file.
        path: PathBuf,
        /// What was wrong with it.
        detail: String,
    },
    /// A ref kept moving while the server tried to set it.
    #[error("{refname} kept moving while it was being set")]
    RefKeptMoving {
        /// The ref.
        refname: String,
    },
    /// Every work-branch name the server reserved is a branch in the
    /// checkout already.
    #[error("the work branches the server reserved are taken here (the last was {name})")]
    WorkBranchTaken {
        /// The last name the server reserved.
        name: String,
    },
    /// The snapshot fetched is not the one the server described: the
    /// checkout was refreshed again (from another worktree, say) meanwhile.
    #[error("the server's snapshot moved again while fetching: expected {expected}, got {got}")]
    SnapshotMoved {
        /// The snapshot the server described.
        expected: String,
        /// What the fetch brought into the checkout's upstream ref.
        got: String,
    },
    /// The projection of a server branch fetched is not the one the server
    /// described: the branch was shown to the checkout again meanwhile.
    #[error("the server's {name} moved again while fetching: expected {expected}, got {got}")]
    BranchMoved {
        /// The branch.
        name: String,
        /// The projection the server described.
        expected: String,
        /// What the fetch brought.
        got: String,
    },
    /// A local branch shares no commit with the server's branch of its name,
    /// as the checkout sees it, and builds on none of its snapshots.
    #[error("{name} has nothing in common with the server's {name}")]
    UnrelatedBranch {
        /// The branch.
        name: String,
    },
    /// A branch that `HEAD` was switched to for its rebase couldn't be
    /// rebased, and `HEAD` couldn't be switched back: it is still on the
    /// branch.
    #[error("{failed}; HEAD is still on {branch}, which it was switched to for the rebase")]
    StillSwitched {
        /// The branch `HEAD` is on now.
        branch: String,
        /// Why the rebase failed.
        failed: Box<CheckoutError>,
    },
    /// The checkout is in the middle of an operation (a stopped rebase, a
    /// merge) that has to be finished or aborted first.
    #[error("a {} is in progress", .0.description())]
    OperationInProgress(crate::state::InProgressOperation),
    /// A fetch from or push to the server failed.
    #[error(transparent)]
    Remote(Box<crate::remote::RemoteError>),
    /// Bringing the current branch onto the new snapshot failed.
    #[error(transparent)]
    Pull(Box<crate::porcelain::pull::PullError>),
    /// The server's answer could not be parsed.
    #[error("unexpected answer from {url}: {detail}")]
    Protocol {
        /// The request URL.
        url: String,
        /// What was wrong.
        detail: String,
    },
    /// The download failed.
    #[error(transparent)]
    Download(Box<crate::resumable::ResumableError>),
    /// The snapshot needs blobs the repository keeps on a promisor remote (a
    /// large-object promisor), and lazy fetch is off, so they cannot be brought in.
    /// As for upload-pack, lazy fetch is turned on with `uploadpack.lazyFetch` or
    /// `GIT_NO_LAZY_FETCH=0` on the server (see [`fetch_promised_blobs`]).
    #[error("the snapshot needs {count} blob(s) kept on a promisor remote, starting with {oid}, and this server does not fetch from its promisor remotes (uploadpack.lazyFetch is off)")]
    PromisedBlobs {
        /// The first missing blob.
        oid: ObjectId,
        /// How many blobs the snapshot lacks.
        count: usize,
    },
    /// The snapshot's blobs kept on a promisor remote were fetched, but the fetch
    /// failed or did not bring them all.
    #[error("the snapshot needs {count} blob(s) kept on a promisor remote, starting with {oid}, and fetching them failed: {source}")]
    PromisedBlobsNotFetched {
        /// The first blob still missing.
        oid: ObjectId,
        /// How many blobs were missing before the fetch.
        count: usize,
        /// Why the fetch failed.
        #[source]
        source: Box<crate::error::Error>,
    },
    /// A repository operation failed.
    #[error(transparent)]
    Library(Box<crate::error::Error>),
    /// A file operation failed.
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

impl From<crate::error::Error> for CheckoutError {
    fn from(e: crate::error::Error) -> Self {
        Self::Library(Box::new(e))
    }
}

impl From<crate::resumable::ResumableError> for CheckoutError {
    fn from(e: crate::resumable::ResumableError) -> Self {
        Self::Download(Box::new(e))
    }
}

impl From<crate::remote::RemoteError> for CheckoutError {
    fn from(e: crate::remote::RemoteError) -> Self {
        Self::Remote(Box::new(e))
    }
}

impl From<crate::porcelain::pull::PullError> for CheckoutError {
    fn from(e: crate::porcelain::pull::PullError) -> Self {
        Self::Pull(Box::new(e))
    }
}

/// Result alias for snapshot checkouts.
pub type Result<T> = std::result::Result<T, CheckoutError>;

/// Clean up requested paths: relative, without `.`, `..` or empty components,
/// without trailing slashes, sorted, deduplicated, and with paths inside
/// another one dropped.
///
/// # Errors
///
/// [`CheckoutError::InvalidPath`] for an absolute path or one with `.`, `..`
/// or empty components.
pub fn normalize_paths(paths: &[String]) -> Result<Vec<String>> {
    let mut out: Vec<String> = Vec::new();
    for p in paths {
        let trimmed = p.trim().trim_matches('/');
        if trimmed.is_empty() {
            continue;
        }
        if p.trim().starts_with('/') {
            return Err(CheckoutError::InvalidPath {
                path: p.clone(),
                reason: "paths are relative to the repository root",
            });
        }
        if trimmed
            .split('/')
            .any(|s| s.is_empty() || s == "." || s == "..")
        {
            return Err(CheckoutError::InvalidPath {
                path: p.clone(),
                reason: "not a plain path inside the repository",
            });
        }
        out.push(trimmed.to_owned());
    }
    out.sort();
    out.dedup();
    let all = out.clone();
    out.retain(|p| {
        !all.iter().any(|q| {
            q != p && p.starts_with(q.as_str()) && p.as_bytes().get(q.len()) == Some(&b'/')
        })
    });
    Ok(out)
}

/// The entry at `path` (slash-separated) under `tree`, as `(mode, oid)`.
fn lookup(odb: &Odb, tree: ObjectId, path: &[u8]) -> crate::error::Result<Option<(u32, ObjectId)>> {
    let mut current = (TREE_MODE, tree);
    for component in path.split(|b| *b == b'/') {
        if current.0 != TREE_MODE {
            return Ok(None);
        }
        let entries = parse_tree(&odb.read(&current.1)?.data)?;
        match entries.into_iter().find(|e| e.name == component) {
            Some(e) => current = (e.mode, e.oid),
            None => return Ok(None),
        }
    }
    Ok(Some(current))
}

/// A tree being assembled from entries at full paths.
#[derive(Default)]
struct Dir {
    entries: BTreeMap<Vec<u8>, Node>,
}

enum Node {
    Entry(u32, ObjectId),
    Dir(Dir),
}

impl Dir {
    fn insert(&mut self, path: &[u8], mode: u32, oid: ObjectId) {
        match path.iter().position(|b| *b == b'/') {
            None => {
                self.entries.insert(path.to_vec(), Node::Entry(mode, oid));
            }
            Some(i) => {
                let node = self
                    .entries
                    .entry(path[..i].to_vec())
                    .or_insert_with(|| Node::Dir(Dir::default()));
                if let Node::Dir(dir) = node {
                    dir.insert(&path[i + 1..], mode, oid);
                }
            }
        }
    }

    fn write(self, odb: &Odb) -> crate::error::Result<ObjectId> {
        let mut entries = Vec::with_capacity(self.entries.len());
        for (name, node) in self.entries {
            let (mode, oid) = match node {
                Node::Entry(mode, oid) => (mode, oid),
                Node::Dir(dir) => (TREE_MODE, dir.write(odb)?),
            };
            entries.push(TreeEntry { mode, name, oid });
        }
        entries.sort_by(|a, b| {
            tree_entry_cmp(&a.name, a.mode == TREE_MODE, &b.name, b.mode == TREE_MODE)
        });
        odb.write(ObjectKind::Tree, &serialize_tree(&entries))
    }
}

/// `tree` cut down to `paths`: each path's entry where it is, and the files
/// directly in every directory above one, the top level included, as Git's
/// cone-mode sparse checkout has them. Selected directories' trees are reused
/// as they are, so only the root and the directories above nested paths are
/// written. No paths is the whole tree.
///
/// # Errors
///
/// [`CheckoutError::MissingPath`] when `tree` has no entry at one of `paths`,
/// and object read or write failures.
pub fn filtered_tree(odb: &Odb, tree: ObjectId, paths: &[String]) -> Result<ObjectId> {
    cut_tree(odb, tree, paths, true)
}

/// [`filtered_tree`], skipping paths `tree` doesn't have instead of failing.
pub(crate) fn view_tree(odb: &Odb, tree: ObjectId, paths: &[String]) -> Result<ObjectId> {
    cut_tree(odb, tree, paths, false)
}

/// Whether `path` (a file's slash-separated path) is in the view `paths`
/// give, as [`filtered_tree`] cuts it: under one of them, or directly in a
/// directory above one (the top level included). No paths is the whole tree.
pub(crate) fn in_view(path: &[u8], paths: &[String]) -> bool {
    if paths.is_empty() {
        return true;
    }
    let parent = path
        .iter()
        .rposition(|b| *b == b'/')
        .map_or(&b""[..], |i| &path[..i]);
    let under = |dir: &[u8], p: &[u8]| p.starts_with(dir) && p.get(dir.len()) == Some(&b'/');
    parent.is_empty()
        || paths
            .iter()
            .map(String::as_bytes)
            .any(|p| path == p || under(p, path) || under(parent, p))
}

fn cut_tree(odb: &Odb, tree: ObjectId, paths: &[String], strict: bool) -> Result<ObjectId> {
    if paths.is_empty() {
        return Ok(tree);
    }
    let mut dirs: Vec<&[u8]> = vec![b""];
    for p in paths {
        let p = p.as_bytes();
        dirs.extend(
            p.iter()
                .enumerate()
                .filter(|(_, b)| **b == b'/')
                .map(|(i, _)| &p[..i]),
        );
    }
    dirs.sort();
    dirs.dedup();
    let mut root = Dir::default();
    for dir in dirs {
        let oid = if dir.is_empty() {
            tree
        } else {
            match lookup(odb, tree, dir)? {
                Some((TREE_MODE, oid)) => oid,
                _ => continue,
            }
        };
        for entry in parse_tree(&odb.read(&oid)?.data)? {
            if entry.mode == TREE_MODE {
                continue;
            }
            let path = if dir.is_empty() {
                entry.name.clone()
            } else {
                [dir, b"/", &entry.name].concat()
            };
            root.insert(&path, entry.mode, entry.oid);
        }
    }
    for p in paths {
        match lookup(odb, tree, p.as_bytes())? {
            Some((mode, oid)) => root.insert(p.as_bytes(), mode, oid),
            None if strict => {
                return Err(CheckoutError::MissingPath {
                    path: p.clone(),
                    base: tree.to_hex(),
                })
            }
            None => {}
        }
    }
    Ok(root.write(odb)?)
}

/// The bytes of the snapshot commit standing for `base` with tree `tree` on
/// `parent`.
///
/// The author and committer are [`SNAPSHOT_IDENT`] at `base_time` (UTC), and
/// the message names `base`, repeats its message, and ends with a
/// [`SNAPSHOT_BASE_TRAILER`] trailer. Nothing else goes in, so the same inputs
/// always give the same commit.
#[must_use]
pub fn snapshot_object(
    tree: ObjectId,
    parent: Option<ObjectId>,
    base: ObjectId,
    base_time: i64,
    base_message: &str,
) -> Vec<u8> {
    let base = base.to_hex();
    let who = format!("{SNAPSHOT_IDENT} {base_time} +0000");
    let mut s = format!("tree {}\n", tree.to_hex());
    if let Some(p) = parent {
        s.push_str(&format!("parent {}\n", p.to_hex()));
    }
    let subject = base_message.lines().next().unwrap_or_default().trim();
    let quoted: String = base_message
        .trim_end()
        .lines()
        .map(|l| format!("    {l}").trim_end().to_owned() + "\n")
        .collect();
    s.push_str(&format!(
        "author {who}\ncommitter {who}\n\nSnapshot of {}: {subject}\n\nStands for {base}:\n\n{quoted}\n{SNAPSHOT_BASE_TRAILER}: {base}\n",
        &base[..base.len().min(12)]
    ));
    s.into_bytes()
}

/// A snapshot commit written into a repository.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Snapshot {
    /// The snapshot commit.
    pub commit: ObjectId,
    /// Its tree.
    pub tree: ObjectId,
    /// The real commit it stands for.
    pub base: ObjectId,
    /// The commit's exact bytes.
    pub object: Vec<u8>,
    /// Files in the tree (submodules not counted).
    pub files: u64,
    /// Bytes of those files.
    pub bytes: u64,
}

/// Write the snapshot of `base` filtered to `paths` (see [`filtered_tree`])
/// on `parent` into `repo`, with the number and size of its files.
///
/// A snapshot holds every file it names, so in a repository whose large blobs
/// live on a promisor remote, the ones the snapshot needs are fetched first
/// ([`fetch_promised_blobs`]).
///
/// # Errors
///
/// [`CheckoutError::MissingPath`] for a path `base` lacks,
/// [`CheckoutError::PromisedBlobs`] and [`CheckoutError::PromisedBlobsNotFetched`]
/// for blobs on a promisor remote that cannot be fetched, and object read or
/// write failures.
pub fn make_snapshot(
    repo: &Repository,
    base: ObjectId,
    paths: &[String],
    parent: Option<ObjectId>,
) -> Result<Snapshot> {
    let odb = repo.odb();
    let commit = odb.read_commit(&base)?;
    let tree = filtered_tree(odb, commit.tree, paths).map_err(|e| match e {
        CheckoutError::MissingPath { path, .. } => CheckoutError::MissingPath {
            path,
            base: base.to_hex(),
        },
        other => other,
    })?;
    let time = crate::ident::parse_signature_times(&commit.committer)
        .map(|t| t.unix_seconds)
        .unwrap_or(0);
    let object = snapshot_object(tree, parent, base, time, &commit.message);
    fetch_promised_tree_blobs(repo, tree)?;
    let id = odb.write(ObjectKind::Commit, &object)?;
    let (files, bytes) = tree_stats(odb, tree)?;
    Ok(Snapshot {
        commit: id,
        tree,
        base,
        object,
        files,
        bytes,
    })
}

/// Make sure `repo` stores every blob of the snapshot commit `snapshot`, fetching
/// the ones it keeps on a promisor remote.
///
/// A server whose large blobs were offloaded to a large-object promisor lacks
/// them locally, but a snapshot (and its bundle) must hold every file. This
/// follows upload-pack's rule for a client that accepted no promisor remote: the
/// blobs are fetched from the repository's promisor remotes when lazy fetch is on,
/// which the host decides by installing a
/// [`PromisorFetcher`](crate::promisor_fetch::PromisorFetcher) on the repository
/// (as [`crate::serve::ServeOptions::attach_promisor_fetcher`] does for
/// upload-pack), and the request fails otherwise. Every missing blob is fetched in
/// one request. A repository without promisor remotes is not checked.
///
/// # Parameters
///
/// - `repo`: the served repository.
/// - `snapshot`: a snapshot commit (or any commit) whose tree must be complete.
///
/// # Returns
///
/// How many blobs were fetched (`0` when nothing was missing).
///
/// # Errors
///
/// [`CheckoutError::PromisedBlobs`] when blobs are missing and the repository has
/// no promisor fetcher, [`CheckoutError::PromisedBlobsNotFetched`] when the fetch
/// failed or left some missing, [`CheckoutError::Library`] with
/// [`crate::error::Error::ObjectNotFound`] for a missing blob nothing promises,
/// and object read failures.
pub fn fetch_promised_blobs(repo: &Repository, snapshot: ObjectId) -> Result<usize> {
    let tree = parse_commit(&repo.odb().read(&snapshot)?.data)?.tree;
    fetch_promised_tree_blobs(repo, tree)
}

/// [`fetch_promised_blobs`] for the snapshot tree `tree`.
fn fetch_promised_tree_blobs(repo: &Repository, tree: ObjectId) -> Result<usize> {
    let config = repo.config()?;
    if !crate::promisor::repo_treats_promisor_packs(repo.git_dir(), config.as_ref()) {
        return Ok(0);
    }
    let odb = repo.odb();
    // Each missing blob with the tree that names it, for the promise check.
    let mut blobs: Vec<(ObjectId, ObjectId)> = Vec::new();
    let mut seen = crate::objects::OidHashSet::default();
    let mut stack = vec![tree];
    while let Some(oid) = stack.pop() {
        for entry in parse_tree(&odb.read(&oid)?.data)? {
            match entry.mode {
                TREE_MODE => stack.push(entry.oid),
                GITLINK_MODE => {}
                _ if seen.insert(entry.oid) => blobs.push((entry.oid, oid)),
                _ => {}
            }
        }
    }
    let missing: crate::objects::OidHashSet = odb
        .missing_stored_oids(blobs.iter().map(|(blob, _)| *blob))?
        .into_iter()
        .collect();
    let Some(&(first, referrer)) = blobs.iter().find(|(blob, _)| missing.contains(blob)) else {
        return Ok(0);
    };
    let promised = crate::serve::promised_objects::PromisorObjects::new(repo)?;
    if !promised.is_promised(&first, Some(&referrer))? {
        return Err(crate::error::Error::ObjectNotFound(first.to_hex()).into());
    }
    let count = missing.len();
    if repo.caches().promisor_fetcher().is_none() {
        return Err(CheckoutError::PromisedBlobs { oid: first, count });
    }
    let wanted: Vec<ObjectId> = blobs
        .iter()
        .map(|(blob, _)| *blob)
        .filter(|blob| missing.contains(blob))
        .collect();
    let not_fetched =
        |oid: ObjectId, source: crate::error::Error| CheckoutError::PromisedBlobsNotFetched {
            oid,
            count,
            source: Box::new(source),
        };
    repo.prefetch_promised(&wanted)
        .map_err(|e| not_fetched(first, e))?;
    odb.reprepare_local_packs();
    odb.invalidate_packs();
    if let Some(&still) = odb.missing_stored_oids(wanted.iter().copied())?.first() {
        return Err(not_fetched(
            still,
            crate::error::Error::PromisedObjectMissing(still),
        ));
    }
    Ok(count)
}

/// Files under `tree` and their total size, without reading file contents.
fn tree_stats(odb: &Odb, tree: ObjectId) -> crate::error::Result<(u64, u64)> {
    let (mut files, mut bytes) = (0u64, 0u64);
    let mut stack = vec![tree];
    while let Some(oid) = stack.pop() {
        for entry in parse_tree(&odb.read(&oid)?.data)? {
            match entry.mode {
                TREE_MODE => stack.push(entry.oid),
                GITLINK_MODE => {}
                _ => {
                    files += 1;
                    bytes += odb.read_info(&entry.oid)?.size;
                }
            }
        }
    }
    Ok((files, bytes))
}

/// A repository URL split into what snapshot checkouts need.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckoutUrl {
    /// The repository URL, for Git (`origin`).
    pub repo_url: String,
    /// The repository's name (last path segment, without `.git`).
    pub name: String,
    /// The checkout endpoint, `<server>/.grit/checkouts/<path>`.
    pub api: String,
}

impl CheckoutUrl {
    /// Split `url` (`http(s)://host[:port]/<path to repository>[.git]`).
    ///
    /// # Errors
    ///
    /// [`CheckoutError::InvalidUrl`] when `url` is not http(s) or names no
    /// repository.
    pub fn parse(url: &str) -> Result<Self> {
        let invalid = || CheckoutError::InvalidUrl(url.to_owned());
        let parsed = url::Url::parse(url).map_err(|_| invalid())?;
        if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
            return Err(invalid());
        }
        let path = parsed.path().trim_matches('/');
        let path = path.strip_suffix(".git").unwrap_or(path);
        if path.is_empty() {
            return Err(invalid());
        }
        let name = path.rsplit('/').next().unwrap_or(path).to_owned();
        let mut server = parsed.clone();
        server.set_path("");
        server.set_query(None);
        server.set_fragment(None);
        let server = server.as_str().trim_end_matches('/').to_owned();
        Ok(Self {
            repo_url: format!("{server}/{path}.git"),
            name,
            api: format!("{server}/{CHECKOUT_API}/{path}"),
        })
    }
}

/// Talks to a server's snapshot-checkout endpoint.
pub struct CheckoutClient<'a> {
    http: &'a dyn HttpClient,
    url: CheckoutUrl,
    given: String,
}

impl<'a> CheckoutClient<'a> {
    /// A client for the repository at `url`.
    ///
    /// # Errors
    ///
    /// [`CheckoutError::InvalidUrl`] as for [`CheckoutUrl::parse`].
    pub fn new(http: &'a dyn HttpClient, url: &str) -> Result<Self> {
        Ok(Self {
            http,
            url: CheckoutUrl::parse(url)?,
            given: url.to_owned(),
        })
    }

    /// The parsed URL.
    #[must_use]
    pub fn url(&self) -> &CheckoutUrl {
        &self.url
    }

    fn json<T: serde::de::DeserializeOwned>(
        &self,
        method: HttpMethod,
        url: &str,
        body: Option<&[u8]>,
    ) -> Result<T> {
        let mut request = HttpRequest::new(method, url).header("Accept", "application/json");
        if let Some(body) = body {
            request = request
                .header("Content-Type", "application/json")
                .body(body);
        }
        let response = self.http.send(&request)?;
        let status = response.status;
        let bytes = response.into_bytes()?;
        if status == 404 && url == self.url.api {
            return Err(CheckoutError::NotOffered {
                url: self.given.clone(),
                endpoint: self.url.api.clone(),
            });
        }
        if !(200..300).contains(&status) {
            let message = serde_json::from_slice::<CheckoutErrorBody>(&bytes)
                .map(|b| b.error)
                .unwrap_or_else(|_| String::from_utf8_lossy(&bytes).trim().to_owned());
            return Err(CheckoutError::Server {
                url: url.to_owned(),
                status,
                message,
            });
        }
        serde_json::from_slice(&bytes).map_err(|e| CheckoutError::Protocol {
            url: url.to_owned(),
            detail: e.to_string(),
        })
    }

    /// What the server would check out.
    ///
    /// # Errors
    ///
    /// [`CheckoutError::NotOffered`] when the server has no checkout endpoint
    /// for the repository, and request failures.
    pub fn server_info(&self) -> Result<CheckoutServerInfo> {
        self.json(HttpMethod::Get, &self.url.api, None)
    }

    /// Make a checkout on the server.
    ///
    /// # Errors
    ///
    /// [`CheckoutError::NotOffered`], and the server's refusal (a path it
    /// doesn't have, an empty repository).
    pub fn create(&self, request: &CheckoutRequest) -> Result<CheckoutInfo> {
        let body = serde_json::to_vec(request).map_err(|e| CheckoutError::Protocol {
            url: self.url.api.clone(),
            detail: e.to_string(),
        })?;
        self.json(HttpMethod::Post, &self.url.api, Some(&body))
    }

    /// The URL of checkout `id`'s bundle.
    #[must_use]
    pub fn bundle_url(&self, id: &str) -> String {
        format!("{}/{id}/bundle", self.url.api)
    }

    /// Checkout `id` as the server has it, and where its target branch is now
    /// ([`CheckoutState::tip`]). Changes nothing on the server, so a dry run can
    /// tell whether a refresh would move.
    ///
    /// # Errors
    ///
    /// Request failures, and the server's refusal (no such checkout).
    pub fn show(&self, id: &str) -> Result<CheckoutState> {
        self.json(HttpMethod::Get, &format!("{}/{id}", self.url.api), None)
    }

    fn post_json<T: Serialize, R: serde::de::DeserializeOwned>(
        &self,
        method: HttpMethod,
        url: &str,
        body: &T,
    ) -> Result<R> {
        let body = serde_json::to_vec(body).map_err(|e| CheckoutError::Protocol {
            url: url.to_owned(),
            detail: e.to_string(),
        })?;
        self.json(method, url, Some(&body))
    }

    /// Ask the server to graft branches the client pushed to [`out_ref`].
    ///
    /// # Errors
    ///
    /// Request failures and the server's refusal of the whole request.
    pub fn checkin(&self, id: &str, request: &CheckinRequest) -> Result<CheckinResponse> {
        self.post_json(
            HttpMethod::Post,
            &format!("{}/{id}/checkin", self.url.api),
            request,
        )
    }

    /// Ask the server for a snapshot of the newest target branch on top of
    /// checkout `id`'s last one (kept at [`target_ref`]).
    ///
    /// # Errors
    ///
    /// Request failures.
    pub fn update(&self, id: &str) -> Result<CheckoutInfo> {
        self.post_json(
            HttpMethod::Post,
            &format!("{}/{id}/update", self.url.api),
            &(),
        )
    }

    /// Reserve a fresh work branch for checkout `id`: `wanted`, numbered past
    /// the server's branches and the names it gave out before.
    ///
    /// # Returns
    ///
    /// The name reserved, which the server never gives out again.
    ///
    /// # Errors
    ///
    /// Request failures, and the server's refusal (no such checkout, a name
    /// that is not a valid branch name).
    pub fn reserve_work_branch(&self, id: &str, wanted: &str) -> Result<String> {
        let reserved: WorkBranchResponse = self.post_json(
            HttpMethod::Post,
            &format!("{}/{id}/work", self.url.api),
            &WorkBranchRequest {
                work: wanted.to_owned(),
            },
        )?;
        Ok(reserved.work)
    }

    /// Ask the server to show its branch `name` to checkout `id`: its
    /// projection, put at [`in_ref`] to fetch ([`fetch_branch`]).
    ///
    /// # Errors
    ///
    /// Request failures, and the server's refusal (no such branch, the
    /// branch the checkout follows, a branch already on the target or older
    /// than the checkout's first snapshot).
    pub fn branch(&self, id: &str, name: &str) -> Result<BranchInfo> {
        self.post_json(
            HttpMethod::Post,
            &format!("{}/{id}/branch", self.url.api),
            &BranchRequest {
                name: name.to_owned(),
            },
        )
    }

    /// Merge a branch into the target on the server.
    ///
    /// # Errors
    ///
    /// Request failures, and the server's refusal (a conflict, no such branch).
    pub fn integrate(&self, request: &IntegrateRequest) -> Result<IntegrateResponse> {
        self.post_json(
            HttpMethod::Post,
            &format!("{}/integrate", self.url.api),
            request,
        )
    }

    /// The slices on the target branch.
    ///
    /// # Errors
    ///
    /// [`CheckoutError::NotOffered`] and request failures.
    pub fn slices(&self) -> Result<SlicesResponse> {
        self.server_info()?;
        self.json(HttpMethod::Get, &format!("{}/slices", self.url.api), None)
    }

    /// Make or change slice `name`.
    ///
    /// # Errors
    ///
    /// Request failures and the server's refusal (a name that exists or
    /// doesn't, a path the target lacks).
    pub fn put_slice(&self, name: &str, request: &SliceRequest) -> Result<SliceChange> {
        self.post_json(
            HttpMethod::Put,
            &format!("{}/slices/{name}", self.url.api),
            request,
        )
    }

    /// Delete slice `name`.
    ///
    /// # Errors
    ///
    /// Request failures and the server's refusal (no such slice).
    pub fn delete_slice(&self, name: &str, request: &SliceDeleteRequest) -> Result<SliceChange> {
        self.post_json(
            HttpMethod::Delete,
            &format!("{}/slices/{name}", self.url.api),
            request,
        )
    }
}

/// Local branches with work to check in: every branch whose tip is a commit
/// on top of one of the checkout's snapshots (not a snapshot itself).
///
/// # Errors
///
/// Ref and ancestry failures.
pub fn branches_with_work(
    repo: &Repository,
    marker: &CheckoutMarker,
) -> Result<Vec<(String, ObjectId)>> {
    let roots: Vec<ObjectId> = marker
        .roots
        .iter()
        .filter_map(|r| ObjectId::from_hex(&r.commit).ok())
        .collect();
    let mut out = Vec::new();
    for (refname, tip) in crate::refs::list_refs(repo.git_dir(), "refs/heads/")? {
        if roots.contains(&tip) {
            continue;
        }
        let mut on_snapshot = false;
        for root in &roots {
            if crate::merge_base::is_ancestor(repo, *root, tip)? {
                on_snapshot = true;
                break;
            }
        }
        if on_snapshot {
            let name = refname
                .strip_prefix("refs/heads/")
                .unwrap_or(&refname)
                .to_owned();
            out.push((name, tip));
        }
    }
    Ok(out)
}

/// What makes a repository a snapshot checkout: where it came from and which
/// snapshot commits it has. Kept as [`MARKER_FILE`] in the repository's common
/// git directory, so every worktree of a checkout shares it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckoutMarker {
    /// The repository URL it was checked out from.
    pub url: String,
    /// The checkout's id on the server.
    pub id: String,
    /// The target branch.
    pub branch: String,
    /// The checkout's paths.
    pub paths: Vec<String>,
    /// The snapshot commits, oldest first.
    pub roots: Vec<SnapshotRoot>,
    /// Tips of branches this checkout checked in that have landed in
    /// [`Self::branch`] (the server merged them into it, or it had them
    /// already): every later snapshot has their commits' changes, though not
    /// as ancestors, so refreshes never replay them ([`land_integration`]).
    /// A tip no branch, and no worktree's detached `HEAD`, builds on any
    /// more is dropped.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub landed: Vec<String>,
}

/// Where the marker of the repository whose git directory is `git_dir` is:
/// in its common git directory, which a linked worktree's `commondir` names.
fn marker_path(git_dir: &Path) -> PathBuf {
    crate::refs::common_dir(git_dir)
        .unwrap_or_else(|| git_dir.to_path_buf())
        .join(MARKER_FILE)
}

impl CheckoutMarker {
    /// Read the marker of the repository whose git directory is `git_dir`
    /// (the main one or a linked worktree's).
    ///
    /// # Returns
    ///
    /// `None` when it is not a snapshot checkout.
    #[must_use]
    pub fn read(git_dir: &Path) -> Option<Self> {
        serde_json::from_slice(&std::fs::read(marker_path(git_dir)).ok()?).ok()
    }

    /// Write it into the common git directory of the repository whose git
    /// directory is `git_dir`, replacing the old one in one rename.
    ///
    /// # Errors
    ///
    /// File write failures.
    pub fn write(&self, git_dir: &Path) -> Result<()> {
        let bytes =
            serde_json::to_vec_pretty(self).map_err(|e| std::io::Error::other(e.to_string()))?;
        let path = marker_path(git_dir);
        let tmp = path.with_file_name(format!("{MARKER_FILE}.tmp"));
        std::fs::write(&tmp, bytes)?;
        std::fs::rename(&tmp, path)?;
        Ok(())
    }

    /// The checkout's newest snapshot, the last of [`Self::roots`].
    #[must_use]
    pub fn last(&self) -> Option<&SnapshotRoot> {
        self.roots.last()
    }

    /// The local ref the checkout keeps its newest snapshot at
    /// ([`upstream_ref`] of [`Self::branch`]).
    #[must_use]
    pub fn upstream_ref(&self) -> String {
        upstream_ref(&self.branch)
    }
}

/// A checkout built on disk.
#[derive(Debug)]
pub struct Materialized {
    /// The new repository.
    pub repo: Repository,
    /// The work branch checked out.
    pub work: String,
    /// Files written to the work tree.
    pub files: u64,
}

/// Build the checkout described by `info` in `dest` from its downloaded
/// `bundle`.
///
/// Creates the repository, unpacks the bundle, checks that the snapshot
/// commit is byte for byte the one the server described, points
/// [`upstream_ref`] (`refs/remotes/origin/<branch>`, which
/// `refs/remotes/origin/HEAD` names) and the new branch `work` at it,
/// configures `origin` as `repo_url` fetching [`snapshot_fetch_refspec`] with
/// no tags and pushing [`out_push_refspec`], writes the [`CheckoutMarker`] and
/// checks out the files.
///
/// # Errors
///
/// [`CheckoutError::DestinationNotEmpty`], [`CheckoutError::Mismatch`] for a
/// download that is not the described snapshot, and repository failures.
#[allow(clippy::too_many_arguments)]
pub fn materialize(
    dest: &Path,
    info: &CheckoutInfo,
    bundle: &Path,
    repo_url: &str,
    work: &str,
    progress: &mut dyn Progress,
    cancel: &dyn Cancel,
) -> Result<Materialized> {
    if dest.is_dir() && std::fs::read_dir(dest)?.next().is_some() {
        return Err(CheckoutError::DestinationNotEmpty(dest.to_path_buf()));
    }
    std::fs::create_dir_all(dest)?;
    let repo = Repository::init(
        dest,
        &InitOptions {
            initial_branch: Some(work.to_owned()),
            ..InitOptions::default()
        },
    )?;
    let opened = repo
        .bundles()
        .open(bundle)
        .map_err(|e| crate::error::Error::Message(format!("bundle: {e}")))?;
    let unbundled = opened
        .unbundle_with_progress(&repo, progress, cancel)
        .map_err(|e| crate::error::Error::Message(format!("bundle: {e}")))?;
    let mismatch = |got: String| CheckoutError::Mismatch {
        expected: info.root.clone(),
        got,
    };
    let root = ObjectId::from_hex(&info.root).map_err(|_| mismatch(info.root.clone()))?;
    let tip = unbundled
        .refs
        .first()
        .map(|r| r.oid)
        .ok_or_else(|| mismatch("an empty bundle".to_owned()))?;
    if tip != root {
        return Err(mismatch(tip.to_hex()));
    }
    let object = repo.odb().read(&root)?;
    if object.data != info.root_object.as_bytes() {
        return Err(mismatch(format!(
            "{} with different contents",
            root.to_hex()
        )));
    }
    let git_dir = repo.git_dir().to_path_buf();
    let upstream = upstream_ref(&info.branch);
    crate::refs::write_ref(&git_dir, &upstream, &root)?;
    crate::refs::write_symbolic_ref(&git_dir, "refs/remotes/origin/HEAD", &upstream)?;
    crate::refs::write_ref(&git_dir, &format!("refs/heads/{work}"), &root)?;
    crate::refs::write_symbolic_ref(&git_dir, "HEAD", &format!("refs/heads/{work}"))?;
    let config_path = git_dir.join("config");
    let content = std::fs::read_to_string(&config_path).unwrap_or_default();
    let mut config = crate::config::ConfigFile::parse(
        &config_path,
        &content,
        crate::config::ConfigScope::Local,
    )?;
    config.set("remote.origin.url", repo_url)?;
    config.set(
        "remote.origin.fetch",
        &snapshot_fetch_refspec(&info.id, &info.branch),
    )?;
    config.set("remote.origin.push", &out_push_refspec(&info.id))?;
    config.set("remote.origin.tagOpt", "--no-tags")?;
    config.write()?;
    CheckoutMarker {
        url: repo_url.to_owned(),
        id: info.id.clone(),
        branch: info.branch.clone(),
        paths: info.paths.clone(),
        roots: info.roots.clone(),
        landed: Vec::new(),
    }
    .write(&git_dir)?;
    let tree = ObjectId::from_hex(&info.tree).map_err(|_| mismatch(info.tree.clone()))?;
    crate::porcelain::checkout::checkout_between_trees_with_progress(
        &repo, None, &tree, progress, cancel,
    )?;
    let files = u64::try_from(repo.index_handle().load()?.entries().len()).unwrap_or(u64::MAX);
    Ok(Materialized {
        repo,
        work: work.to_owned(),
        files,
    })
}

const WORDS: &[&str] = &[
    "amber", "brook", "cedar", "dune", "ember", "fern", "glade", "harbor", "iris", "juniper",
    "kestrel", "lagoon", "maple", "nectar", "orchid", "pine", "quartz", "river", "sage", "thistle",
    "umber", "violet", "willow", "yarrow", "zephyr", "aspen", "birch", "coral", "delta", "elm",
    "flint", "grove", "hazel", "inlet", "jasper", "lark", "moss", "north", "oak", "pebble",
    "quill", "reed", "slate", "tide", "vale", "wren",
];

/// A work branch name for a new checkout: the local part of `email` and two
/// words chosen by `random`, like `alice/quiet-river`.
#[must_use]
pub fn suggest_work_branch(email: Option<&str>, random: [u8; 2]) -> String {
    let who: String = email
        .and_then(|e| e.split('@').next())
        .unwrap_or_default()
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c.to_ascii_lowercase()
            } else {
                '-'
            }
        })
        .collect();
    let who = who.trim_matches('-');
    let a = WORDS[usize::from(random[0]) % WORDS.len()];
    let b = WORDS[usize::from(random[1]) % WORDS.len()];
    if who.is_empty() {
        format!("checkout/{a}-{b}")
    } else {
        format!("{who}/{a}-{b}")
    }
}

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

    #[test]
    fn idents_resolve_like_commit_authors_and_sign_cleanly() {
        let env_of = |vars: &[(&str, &str)]| {
            crate::config::environment::Environment::from_vars(
                vars.iter().map(|(k, v)| ((*k).into(), (*v).into())),
                std::path::PathBuf::from("/"),
            )
        };
        let env = env_of(&[
            ("GIT_AUTHOR_NAME", "A U Thor"),
            ("GIT_AUTHOR_EMAIL", "author@example.com"),
        ]);
        let mut config = crate::config::ConfigSet::new();
        let _ = config.add_command_override("user.name", "Alice");
        let _ = config.add_command_override("user.email", "alice@example.com");
        assert_eq!(
            Ident::author(&env, &config).ok(),
            Some(Ident {
                name: "A U Thor".to_owned(),
                email: "author@example.com".to_owned()
            }),
            "the environment wins over config, as for a commit"
        );
        let bare = env_of(&[]);
        assert_eq!(
            Ident::author(&bare, &config).ok(),
            Some(Ident {
                name: "Alice".to_owned(),
                email: "alice@example.com".to_owned()
            })
        );
        assert!(Ident::author(&bare, &crate::config::ConfigSet::new()).is_err());

        let time = time::OffsetDateTime::from_unix_timestamp(1_700_000_000)
            .unwrap_or(time::OffsetDateTime::UNIX_EPOCH);
        let sneaky = Ident {
            name: "Eve\nencoding bogus".to_owned(),
            email: "e>v<e@x".to_owned(),
        };
        assert_eq!(
            sneaky
                .signature(time)
                .map(|s| s.header_line())
                .ok()
                .as_deref(),
            Some("Eveencoding bogus <eve@x> 1700000000 +0000")
        );
        let nameless = Ident {
            name: "<>".to_owned(),
            email: "bob@example.com".to_owned(),
        };
        assert_eq!(
            nameless.signature(time).map(|s| s.name).ok().as_deref(),
            Some("bob@example.com")
        );
    }

    #[test]
    fn paths_are_normalized() {
        let paths: Vec<String> = ["b/", "a/x", "a", " c ", "", "a/y"]
            .iter()
            .map(|s| (*s).to_owned())
            .collect();
        assert_eq!(
            normalize_paths(&paths).ok(),
            Some(vec!["a".to_owned(), "b".to_owned(), "c".to_owned()])
        );
        assert!(normalize_paths(&["/abs".to_owned()]).is_err());
        assert!(normalize_paths(&["a/../b".to_owned()]).is_err());
        assert!(normalize_paths(&["a//b".to_owned()]).is_err());
    }

    #[test]
    fn views_are_the_paths_and_the_files_above_them() {
        let paths = vec!["src/deep".to_owned(), "docs/guide.md".to_owned()];
        for (path, seen) in [
            ("README", true),
            ("src/a.rs", true),
            ("src/deep/b.rs", true),
            ("src/deep/more/c.rs", true),
            ("src/other/d.rs", false),
            ("docs/guide.md", true),
            ("docs/other.md", true),
            ("docs/api/x.md", false),
            ("srcx/a.rs", false),
            ("src/deeper/a.rs", false),
        ] {
            assert_eq!(in_view(path.as_bytes(), &paths), seen, "{path}");
        }
        assert!(in_view(b"anything/at/all", &[]));
    }

    #[test]
    fn urls_split_into_repository_and_endpoint() {
        let u = CheckoutUrl::parse("http://h:8080/demo.git").ok();
        assert_eq!(
            u,
            Some(CheckoutUrl {
                repo_url: "http://h:8080/demo.git".to_owned(),
                name: "demo".to_owned(),
                api: "http://h:8080/.grit/checkouts/demo".to_owned(),
            })
        );
        let nested = CheckoutUrl::parse("https://h/org/app/").ok();
        assert_eq!(nested.as_ref().map(|u| u.name.as_str()), Some("app"));
        assert_eq!(
            nested.map(|u| u.api),
            Some("https://h/.grit/checkouts/org/app".to_owned())
        );
        assert!(CheckoutUrl::parse("http://h/").is_err());
        assert!(CheckoutUrl::parse("ssh://h/demo").is_err());
    }

    #[test]
    fn snapshot_objects_are_deterministic() {
        let tree = ObjectId::from_hex("4b825dc642cb6eb9a060e54bf8d69288fbee4904").ok();
        let base = ObjectId::from_hex("1111111111111111111111111111111111111111").ok();
        let (Some(tree), Some(base)) = (tree, base) else {
            panic!("oids");
        };
        let a = snapshot_object(tree, None, base, 1_700_000_000, "Fix it\n\nBody\n");
        assert_eq!(
            a,
            snapshot_object(tree, None, base, 1_700_000_000, "Fix it\n\nBody\n")
        );
        let text = String::from_utf8_lossy(&a);
        assert!(text.starts_with("tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\nauthor grit-checkout <snapshot@grit-checkout> 1700000000 +0000\n"), "{text}");
        assert!(
            text.contains("\n\nSnapshot of 111111111111: Fix it\n"),
            "{text}"
        );
        assert!(
            text.ends_with("Grit-Checkout-Base: 1111111111111111111111111111111111111111\n"),
            "{text}"
        );
    }

    #[test]
    fn work_branches_are_named_for_the_committer() {
        assert_eq!(
            suggest_work_branch(Some("Alice.B@example.com"), [0, 1]),
            "alice-b/amber-brook"
        );
        assert_eq!(suggest_work_branch(None, [2, 3]), "checkout/cedar-dune");
    }

    /// A bare repository whose large blob `src/big` lives on the promisor `lop`:
    /// its commit and trees are in a promisor pack, `src/a` in an ordinary pack,
    /// `src/big` nowhere. Returns the commit and the big blob's id and data.
    fn offloaded(dir: &Path) -> (ObjectId, ObjectId, Vec<u8>) {
        use crate::objects::ObjectKind;
        let repo = Repository::init(dir, &InitOptions::new().with_bare(true)).unwrap();
        let odb = repo.odb();
        let small = odb
            .write_loose_materialize(ObjectKind::Blob, b"a\n")
            .unwrap();
        let data = vec![b'x'; 4096];
        let big = odb
            .write_loose_materialize(ObjectKind::Blob, &data)
            .unwrap();
        let tree_of = |entries: &[(&str, &str, ObjectId)]| {
            let mut body = Vec::new();
            for (mode, name, oid) in entries {
                body.extend_from_slice(format!("{mode} {name}\0").as_bytes());
                body.extend_from_slice(oid.as_bytes());
            }
            odb.write_loose_materialize(ObjectKind::Tree, &body)
                .unwrap()
        };
        let src = tree_of(&[("100644", "a", small), ("100644", "big", big)]);
        let root = tree_of(&[("40000", "src", src)]);
        let commit =
            format!("tree {root}\nauthor A <a@e> 1 +0000\ncommitter A <a@e> 1 +0000\n\nc\n");
        let commit = odb
            .write_loose_materialize(ObjectKind::Commit, commit.as_bytes())
            .unwrap();
        for (oids, promisor) in [(vec![commit, root, src], true), (vec![small], false)] {
            let pack = crate::pack_objects::build_pack_from_send_list(
                odb,
                &oids,
                &std::collections::HashSet::new(),
                &crate::pack_objects::PackBuildOptions::default(),
                &std::collections::HashMap::new(),
            )
            .unwrap();
            crate::index_pack::install_pack_bytes(
                pack,
                odb,
                &crate::index_pack::IngestPackOptions {
                    mark_promisor_pack: promisor,
                    ..Default::default()
                },
            )
            .unwrap();
        }
        crate::prune_packed::prune_packed_objects(odb.objects_dir(), Default::default()).unwrap();
        let hex = big.to_hex();
        std::fs::remove_file(dir.join("objects").join(&hex[..2]).join(&hex[2..])).unwrap();
        let mut config = std::fs::read_to_string(dir.join("config")).unwrap();
        config.push_str("[remote \"lop\"]\n\turl = /nowhere\n\tpromisor = true\n");
        std::fs::write(dir.join("config"), config).unwrap();
        crate::pack::clear_pack_cache();
        (commit, big, data)
    }

    /// Writes the blobs it is asked for from `blobs`, or nothing.
    struct StubFetcher {
        blobs: Vec<(ObjectId, Vec<u8>)>,
        calls: std::sync::Mutex<Vec<Vec<ObjectId>>>,
    }

    impl crate::promisor_fetch::PromisorFetcher for StubFetcher {
        fn fetch_missing(&self, repo: &Repository, oids: &[ObjectId]) -> crate::error::Result<()> {
            self.calls
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .push(oids.to_vec());
            for (oid, data) in &self.blobs {
                if oids.contains(oid) {
                    repo.odb()
                        .write_loose_materialize(crate::objects::ObjectKind::Blob, data)?;
                }
            }
            Ok(())
        }
    }

    fn open_with(dir: &Path, fetcher: Option<std::sync::Arc<StubFetcher>>) -> Repository {
        let fetcher =
            fetcher.map(|f| f as std::sync::Arc<dyn crate::promisor_fetch::PromisorFetcher>);
        Repository::open(
            dir,
            &crate::config::environment::RepositoryOptions::empty().with_promisor_fetcher(fetcher),
        )
        .unwrap()
    }

    #[test]
    fn a_snapshot_of_offloaded_blobs_is_refused_without_lazy_fetch() {
        let tmp = tempfile::tempdir().unwrap();
        let (commit, big, _) = offloaded(tmp.path());
        let repo = open_with(tmp.path(), None);
        let err = make_snapshot(&repo, commit, &["src".to_owned()], None).unwrap_err();
        assert!(
            matches!(err, CheckoutError::PromisedBlobs { oid, count: 1 } if oid == big),
            "{err:?}"
        );
        assert!(err.to_string().contains("uploadpack.lazyFetch"), "{err}");
    }

    #[test]
    fn a_snapshot_of_offloaded_blobs_fetches_them_in_one_request() {
        let tmp = tempfile::tempdir().unwrap();
        let (commit, big, data) = offloaded(tmp.path());
        let fetcher = std::sync::Arc::new(StubFetcher {
            blobs: vec![(big, data)],
            calls: std::sync::Mutex::default(),
        });
        let repo = open_with(tmp.path(), Some(std::sync::Arc::clone(&fetcher)));
        let snap = make_snapshot(&repo, commit, &["src".to_owned()], None).unwrap();
        assert_eq!((snap.files, snap.bytes), (2, 4096 + 2));
        assert_eq!(*fetcher.calls.lock().unwrap(), vec![vec![big]]);
        // Everything is here now; the bundle path finds nothing to fetch.
        assert_eq!(fetch_promised_blobs(&repo, snap.commit).unwrap(), 0);
        assert_eq!(fetcher.calls.lock().unwrap().len(), 1);
    }

    #[test]
    fn a_fetch_that_brings_nothing_is_reported() {
        let tmp = tempfile::tempdir().unwrap();
        let (commit, big, _) = offloaded(tmp.path());
        let fetcher = std::sync::Arc::new(StubFetcher {
            blobs: Vec::new(),
            calls: std::sync::Mutex::default(),
        });
        let repo = open_with(tmp.path(), Some(fetcher));
        let err = fetch_promised_blobs(&repo, commit).unwrap_err();
        assert!(
            matches!(err, CheckoutError::PromisedBlobsNotFetched { oid, count: 1, .. } if oid == big),
            "{err:?}"
        );
    }

    #[test]
    fn a_repository_without_promisor_remotes_is_not_checked() {
        let tmp = tempfile::tempdir().unwrap();
        let (commit, _, _) = offloaded(tmp.path());
        let config = std::fs::read_to_string(tmp.path().join("config")).unwrap();
        let plain = config.replace("\tpromisor = true\n", "");
        std::fs::write(tmp.path().join("config"), plain).unwrap();
        let repo = open_with(tmp.path(), None);
        // Not a partial repository: the check is skipped and the stats read fails.
        let err = make_snapshot(&repo, commit, &["src".to_owned()], None).unwrap_err();
        assert!(
            !matches!(err, CheckoutError::PromisedBlobs { .. }),
            "{err:?}"
        );
    }
}