git-lfs 0.7.0

Large file storage for git, implemented in Rust
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
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
//! End-to-end tests against the built `git-lfs` binary.
//!
//! These spawn the binary in a fresh git repo via `std::process::Command`,
//! pipe in stdin, and assert on stdout/stderr/exit-status. Mirrors what the
//! upstream shell tests in `tests/t-clean.sh` and `tests/t-smudge.sh` would
//! check, without needing the upstream Go test infrastructure.

use std::io::Write;
use std::path::Path;
use std::process::{Command, Output, Stdio};

use tempfile::TempDir;

const BIN: &str = env!("CARGO_BIN_EXE_git-lfs");

/// Initialize a fresh git repo in a tempdir and return it.
fn fresh_repo() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let status = Command::new("git")
        .args(["init", "--quiet"])
        .arg(tmp.path())
        .status()
        .unwrap();
    assert!(status.success(), "git init failed");
    tmp
}

/// Run `git-lfs <args>` in `cwd` with `input` on stdin and capture the result.
///
/// PATH is augmented with the directory containing the test binary so
/// that `git` can find `git-lfs` when invoking the configured filters
/// (clean / smudge / process). Without this, anything that goes through
/// git's filter machinery — `git checkout` notably — silently no-ops on
/// LFS-tracked files.
fn run_in(cwd: &Path, args: &[&str], input: &[u8]) -> Output {
    let bin_dir = Path::new(BIN).parent().unwrap();
    let path_var = std::env::var("PATH").unwrap_or_default();
    let new_path = format!("{}:{path_var}", bin_dir.display());

    let mut child = Command::new(BIN)
        .args(args)
        .current_dir(cwd)
        .env("PATH", new_path)
        // Hermetic: ignore the developer's ~/.gitconfig and /etc/gitconfig
        // so behavior doesn't change based on whether the dev has Git LFS
        // (or any other filter) installed globally.
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.as_mut().unwrap().write_all(input).unwrap();
    drop(child.stdin.take());
    child.wait_with_output().unwrap()
}

#[test]
fn clean_smudge_round_trip() {
    let repo = fresh_repo();
    let content = b"hello world\n";

    let cleaned = run_in(repo.path(), &["clean"], content);
    assert!(
        cleaned.status.success(),
        "clean failed: {}",
        String::from_utf8_lossy(&cleaned.stderr),
    );
    let pointer = cleaned.stdout;
    assert!(pointer.starts_with(b"version https://git-lfs.github.com/spec/v1\n"));

    let smudged = run_in(repo.path(), &["smudge"], &pointer);
    assert!(
        smudged.status.success(),
        "smudge failed: {}",
        String::from_utf8_lossy(&smudged.stderr),
    );
    assert_eq!(smudged.stdout, content);
}

#[test]
fn matches_upstream_t_smudge_fixture() {
    // Cross-check against the exact OID/size that upstream's t-smudge.sh uses
    // for "smudge a\n": pointer fcf5015df... 9.
    let repo = fresh_repo();
    let cleaned = run_in(repo.path(), &["clean"], b"smudge a\n");
    let expected = "version https://git-lfs.github.com/spec/v1\n\
                    oid sha256:fcf5015df7a9089a7aa7fe74139d4b8f7d62e52d5a34f9a87aeffc8e8c668254\n\
                    size 9\n";
    assert_eq!(
        String::from_utf8_lossy(&cleaned.stdout),
        expected,
        "pointer encoding diverges from upstream fixture",
    );

    let smudged = run_in(repo.path(), &["smudge"], &cleaned.stdout);
    assert_eq!(smudged.stdout, b"smudge a\n");
}

#[test]
fn clean_writes_object_to_sharded_path() {
    let repo = fresh_repo();
    run_in(repo.path(), &["clean"], b"abc");
    // SHA-256("abc")
    let oid = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
    let object_path = repo
        .path()
        .join(".git/lfs/objects")
        .join(&oid[0..2])
        .join(&oid[2..4])
        .join(oid);
    assert!(object_path.is_file(), "expected object at {object_path:?}");
}

#[test]
fn clean_passes_through_existing_pointer() {
    // Mirrors t-clean.sh "clean a pointer": piping a pointer through clean
    // emits the same bytes and inserts nothing into the store.
    let repo = fresh_repo();
    let pointer = b"version https://git-lfs.github.com/spec/v1\n\
                    oid sha256:cd293be6cea034bd45a0352775a219ef5dc7825ce55d1f7dae9762d80ce64411\n\
                    size 9\n";
    let out = run_in(repo.path(), &["clean"], pointer);
    assert!(out.status.success());
    assert_eq!(out.stdout, pointer);
    assert!(!repo.path().join(".git/lfs/objects").exists());
}

#[test]
fn smudge_passes_through_non_pointer() {
    // Mirrors t-smudge.sh "smudge with invalid pointer": short non-pointer
    // input flows out unchanged.
    let repo = fresh_repo();
    for input in [&b"wat"[..], b"not a git-lfs file", b"version "] {
        let out = run_in(repo.path(), &["smudge"], input);
        assert!(out.status.success(), "smudge failed for {input:?}");
        assert_eq!(out.stdout, input);
    }
}

#[test]
fn smudge_missing_object_without_lfs_url_errors() {
    // No `lfs.url` and no `remote.origin.url` configured + missing object →
    // smudge attempts to fetch, can't resolve an LFS endpoint, and fails
    // with a clear error. Previously (before transfer wiring) this
    // surfaced as ObjectMissing; now it surfaces as a fetch failure that
    // names the unresolved endpoint.
    let repo = fresh_repo();
    let pointer = b"version https://git-lfs.github.com/spec/v1\n\
                    oid sha256:0000000000000000000000000000000000000000000000000000000000000001\n\
                    size 5\n";
    let out = run_in(repo.path(), &["smudge"], pointer);
    assert!(!out.status.success());
    assert!(out.stdout.is_empty(), "no partial output on miss");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("LFS endpoint") || stderr.contains("origin"),
        "unexpected stderr: {stderr}"
    );
}

#[test]
fn outside_repo_errors() {
    // Not a git repo — `git rev-parse` fails, we should exit 1 with a useful
    // error on stderr (and not write garbage to stdout).
    let tmp = TempDir::new().unwrap();
    let out = run_in(tmp.path(), &["clean"], b"x");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("not a git repository"),
        "unexpected stderr: {stderr}"
    );
}

// ---------- install ----------
//
// All install tests use `--local` so they only touch the test repo's
// `.git/config` and never the developer's `~/.gitconfig`.

/// Read a single config value from the local repo. Helper for assertions.
fn read_local_config(repo: &Path, key: &str) -> Option<String> {
    let out = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(["config", "--local", "--get", key])
        .output()
        .unwrap();
    if out.status.success() {
        Some(String::from_utf8_lossy(&out.stdout).trim().to_owned())
    } else {
        None
    }
}

#[test]
fn install_local_sets_filter_config() {
    let repo = fresh_repo();
    let out = run_in(repo.path(), &["install", "--local"], b"");
    assert!(
        out.status.success(),
        "install failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
    assert!(String::from_utf8_lossy(&out.stdout).contains("Git LFS initialized"));

    assert_eq!(
        read_local_config(repo.path(), "filter.lfs.clean").as_deref(),
        Some("git-lfs clean -- %f"),
    );
    assert_eq!(
        read_local_config(repo.path(), "filter.lfs.smudge").as_deref(),
        Some("git-lfs smudge -- %f"),
    );
    assert_eq!(
        read_local_config(repo.path(), "filter.lfs.process").as_deref(),
        Some("git-lfs filter-process"),
    );
    assert_eq!(
        read_local_config(repo.path(), "filter.lfs.required").as_deref(),
        Some("true"),
    );
}

#[test]
fn install_local_writes_executable_hooks() {
    let repo = fresh_repo();
    run_in(repo.path(), &["install", "--local"], b"");

    for hook in ["pre-push", "post-checkout", "post-commit", "post-merge"] {
        let path = repo.path().join(".git/hooks").join(hook);
        assert!(path.is_file(), "missing hook: {path:?}");
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.starts_with("#!/bin/sh\n"));
        assert!(
            content.contains(&format!("git lfs {hook} \"$@\"")),
            "hook {hook} missing dispatch line",
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o755, "hook {hook} not executable");
        }
    }
}

#[test]
fn install_is_idempotent() {
    let repo = fresh_repo();
    let first = run_in(repo.path(), &["install", "--local"], b"");
    assert!(first.status.success());
    let second = run_in(repo.path(), &["install", "--local"], b"");
    assert!(
        second.status.success(),
        "second install failed: {}",
        String::from_utf8_lossy(&second.stderr),
    );
}

#[test]
fn install_errors_on_conflicting_config_without_force() {
    let repo = fresh_repo();
    // Pre-populate one of the keys with a different value.
    let status = Command::new("git")
        .arg("-C")
        .arg(repo.path())
        .args([
            "config",
            "--local",
            "filter.lfs.clean",
            "/usr/local/bin/old-lfs clean",
        ])
        .status()
        .unwrap();
    assert!(status.success());

    let out = run_in(repo.path(), &["install", "--local"], b"");
    assert!(!out.status.success());
    // The conflict goes on stdout (matches upstream + the t-install
    // `tee install.log` capture), with the upstream-format
    // `the "filter.lfs.clean" attribute should be ...` line and a
    // follow-up `Run \`git lfs install --force\`...` hint.
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("--force"),
        "stdout should suggest --force: {stdout}"
    );
    assert!(
        stdout.contains("attribute should be"),
        "stdout should describe the attribute mismatch: {stdout}"
    );
}

#[test]
fn install_force_overwrites_conflicting_config() {
    let repo = fresh_repo();
    Command::new("git")
        .arg("-C")
        .arg(repo.path())
        .args(["config", "--local", "filter.lfs.clean", "old"])
        .status()
        .unwrap();

    let out = run_in(repo.path(), &["install", "--local", "--force"], b"");
    assert!(out.status.success());
    assert_eq!(
        read_local_config(repo.path(), "filter.lfs.clean").as_deref(),
        Some("git-lfs clean -- %f"),
    );
}

#[test]
fn install_skip_repo_writes_no_hooks() {
    let repo = fresh_repo();
    run_in(repo.path(), &["install", "--local", "--skip-repo"], b"");
    // Config is set, but no hooks were written.
    assert!(read_local_config(repo.path(), "filter.lfs.clean").is_some());
    assert!(!repo.path().join(".git/hooks/pre-push").exists());
}

// ---------- uninstall ----------

#[test]
fn uninstall_local_clears_config_and_removes_hooks() {
    let repo = fresh_repo();
    run_in(repo.path(), &["install", "--local"], b"");
    let out = run_in(repo.path(), &["uninstall", "--local"], b"");
    assert!(
        out.status.success(),
        "uninstall failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
    assert!(
        String::from_utf8_lossy(&out.stdout)
            .contains("Local Git LFS configuration has been removed"),
    );

    for key in [
        "filter.lfs.clean",
        "filter.lfs.smudge",
        "filter.lfs.process",
        "filter.lfs.required",
    ] {
        assert!(
            read_local_config(repo.path(), key).is_none(),
            "{key} still set"
        );
    }
    for hook in ["pre-push", "post-checkout", "post-commit", "post-merge"] {
        assert!(
            !repo.path().join(".git/hooks").join(hook).exists(),
            "hook {hook} still present",
        );
    }
}

#[test]
fn uninstall_is_idempotent_when_nothing_installed() {
    let repo = fresh_repo();
    let out = run_in(repo.path(), &["uninstall", "--local"], b"");
    assert!(
        out.status.success(),
        "uninstall on clean repo failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
}

#[test]
fn uninstall_preserves_user_modified_hooks() {
    let repo = fresh_repo();
    run_in(repo.path(), &["install", "--local"], b"");
    // Replace the pre-push hook with a user-customized version.
    let pre_push = repo.path().join(".git/hooks/pre-push");
    let custom = "#!/bin/sh\necho 'my custom hook'\n";
    std::fs::write(&pre_push, custom).unwrap();

    let out = run_in(repo.path(), &["uninstall", "--local"], b"");
    assert!(out.status.success());

    // Customized hook is left in place; the others (still ours) are gone.
    assert!(pre_push.exists(), "user-modified pre-push was deleted");
    assert_eq!(std::fs::read_to_string(&pre_push).unwrap(), custom);
    assert!(!repo.path().join(".git/hooks/post-checkout").exists());
}

#[test]
fn uninstall_skip_repo_leaves_hooks_alone() {
    let repo = fresh_repo();
    run_in(repo.path(), &["install", "--local"], b"");
    let out = run_in(repo.path(), &["uninstall", "--local", "--skip-repo"], b"");
    assert!(out.status.success());
    // Config gone…
    assert!(read_local_config(repo.path(), "filter.lfs.clean").is_none());
    // …but hooks still present.
    assert!(repo.path().join(".git/hooks/pre-push").exists());
}

// ---------- track ----------

#[test]
fn track_creates_gitattributes_and_emits_message() {
    let repo = fresh_repo();
    let out = run_in(repo.path(), &["track", "*.jpg"], b"");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    // Matches the grep in upstream's t-track.sh: "Tracking \"\*.jpg\"".
    assert!(
        stdout.contains(r#"Tracking "*.jpg""#),
        "unexpected stdout: {stdout}"
    );

    let content = std::fs::read_to_string(repo.path().join(".gitattributes")).unwrap();
    assert_eq!(content, "*.jpg filter=lfs diff=lfs merge=lfs -text\n");
}

#[test]
fn track_already_supported_is_idempotent() {
    let repo = fresh_repo();
    run_in(repo.path(), &["track", "*.jpg"], b"");
    let out = run_in(repo.path(), &["track", "*.jpg"], b"");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    // Matches upstream's grep: "\"*.jpg\" already supported".
    assert!(
        stdout.contains(r#""*.jpg" already supported"#),
        "unexpected stdout: {stdout}",
    );
    let content = std::fs::read_to_string(repo.path().join(".gitattributes")).unwrap();
    assert_eq!(content.matches("*.jpg").count(), 1);
}

#[test]
fn track_preserves_existing_gitattributes() {
    let repo = fresh_repo();
    let initial = "* text=auto\n#*.cs diff=csharp\n";
    std::fs::write(repo.path().join(".gitattributes"), initial).unwrap();
    run_in(repo.path(), &["track", "*.jpg"], b"");
    let content = std::fs::read_to_string(repo.path().join(".gitattributes")).unwrap();
    assert!(content.starts_with("* text=auto\n#*.cs diff=csharp\n"));
    assert!(content.contains("*.jpg filter=lfs"));
}

#[test]
fn track_no_args_lists_patterns() {
    let repo = fresh_repo();
    run_in(repo.path(), &["track", "*.jpg"], b"");
    run_in(repo.path(), &["track", "*.png"], b"");
    let out = run_in(repo.path(), &["track"], b"");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("Listing tracked patterns"));
    assert!(stdout.contains("*.jpg (.gitattributes)"));
    assert!(stdout.contains("*.png (.gitattributes)"));
}

#[test]
fn track_then_clean_filter_path() {
    // Track a pattern and then clean a matching file's content. This proves
    // the two pieces compose: track sets up .gitattributes, the clean filter
    // turns content into a pointer + populates the store.
    let repo = fresh_repo();
    run_in(repo.path(), &["track", "*.bin"], b"");
    let out = run_in(repo.path(), &["clean", "data.bin"], b"binary blob");
    assert!(out.status.success());
    assert!(
        out.stdout
            .starts_with(b"version https://git-lfs.github.com/spec/v1\n")
    );
}

// ---------- untrack ----------

#[test]
fn untrack_removes_pattern_and_emits_message() {
    let repo = fresh_repo();
    run_in(repo.path(), &["track", "*.jpg"], b"");
    run_in(repo.path(), &["track", "*.png"], b"");
    let out = run_in(repo.path(), &["untrack", "*.jpg"], b"");
    assert!(
        out.status.success(),
        "untrack failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains(r#"Untracking "*.jpg""#),
        "unexpected stdout: {stdout}"
    );

    let content = std::fs::read_to_string(repo.path().join(".gitattributes")).unwrap();
    assert!(!content.contains("*.jpg"));
    assert!(content.contains("*.png filter=lfs"));
}

#[test]
fn untrack_unknown_pattern_reports_not_tracked() {
    let repo = fresh_repo();
    run_in(repo.path(), &["track", "*.jpg"], b"");
    let out = run_in(repo.path(), &["untrack", "*.png"], b"");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains(r#""*.png" was not tracked"#),
        "unexpected stdout: {stdout}"
    );
    // *.jpg still tracked, file unchanged.
    let content = std::fs::read_to_string(repo.path().join(".gitattributes")).unwrap();
    assert_eq!(content, "*.jpg filter=lfs diff=lfs merge=lfs -text\n");
}

#[test]
fn untrack_no_args_errors() {
    let repo = fresh_repo();
    let out = run_in(repo.path(), &["untrack"], b"");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("untrack"), "expected usage hint: {stderr}");
}

#[test]
fn untrack_then_track_round_trips() {
    let repo = fresh_repo();
    run_in(repo.path(), &["track", "*.jpg"], b"");
    run_in(repo.path(), &["untrack", "*.jpg"], b"");
    run_in(repo.path(), &["track", "*.jpg"], b"");
    let content = std::fs::read_to_string(repo.path().join(".gitattributes")).unwrap();
    assert_eq!(content.matches("*.jpg filter=lfs").count(), 1);
}

// ---------- smudge with on-demand download --------------------------------
//
// One end-to-end test that proves the new wiring: lfs.url → batch API →
// basic transfer → store, all driven from the smudge subcommand. Lives
// next to the other smudge tests but uses tokio + wiremock, so it's
// gated as a separate module.

#[tokio::test]
async fn smudge_downloads_missing_object_via_lfs_url() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // SHA-256 of "downloaded\n" — the bytes we'll have wiremock serve.
    const OID: &str = "30031a9831674dd684c3817399acebc88a116ce5a7a3fbc0cf34d92521a534e6";
    const CONTENT: &[u8] = b"downloaded\n";

    let server = MockServer::start().await;
    let storage_url = format!("{}/storage/{OID}", server.uri());

    Mock::given(m_method("POST"))
        .and(m_path("/objects/batch"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "transfer": "basic",
            "objects": [{
                "oid": OID, "size": CONTENT.len(),
                "actions": { "download": { "href": storage_url } }
            }]
        })))
        .mount(&server)
        .await;

    Mock::given(m_method("GET"))
        .and(m_path(format!("/storage/{OID}")))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(CONTENT))
        .mount(&server)
        .await;

    // Set lfs.url so the fetcher can find the wiremock.
    let repo = fresh_repo();
    let status = Command::new("git")
        .arg("-C")
        .arg(repo.path())
        .args(["config", "--local", "lfs.url", &server.uri()])
        .status()
        .unwrap();
    assert!(status.success());

    let pointer = format!(
        "version https://git-lfs.github.com/spec/v1\n\
         oid sha256:{OID}\n\
         size {}\n",
        CONTENT.len(),
    );

    // run_in is sync; spawn it on the blocking pool so we don't deadlock
    // the current-thread runtime that wiremock is using.
    let path = repo.path().to_owned();
    let pointer_bytes = pointer.into_bytes();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["smudge"], &pointer_bytes))
        .await
        .unwrap();

    assert!(
        out.status.success(),
        "smudge failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
    assert_eq!(out.stdout, CONTENT, "smudge stdout != served bytes");

    // The fetched object should now be in the local store, sharded under
    // .git/lfs/objects/<aa>/<bb>/<full-oid>.
    let stored = repo
        .path()
        .join(".git/lfs/objects")
        .join(&OID[0..2])
        .join(&OID[2..4])
        .join(OID);
    assert!(stored.is_file(), "expected stored object at {stored:?}");
}

#[tokio::test]
async fn smudge_uses_remote_origin_url_when_no_lfs_url_set() {
    // Same wiring as `smudge_downloads_missing_object_via_lfs_url`, but
    // configures `remote.origin.url` instead of `lfs.url` to prove the
    // endpoint resolver derives `<remote>.git/info/lfs` correctly. The
    // wiremock stands in for that derived URL.
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    const OID: &str = "30031a9831674dd684c3817399acebc88a116ce5a7a3fbc0cf34d92521a534e6";
    const CONTENT: &[u8] = b"downloaded\n";

    let server = MockServer::start().await;
    let storage_url = format!("{}/storage/{OID}", server.uri());

    // The derived endpoint will tack `.git/info/lfs` onto the remote URL,
    // so the path the batch lands on is `/repo.git/info/lfs/objects/batch`.
    Mock::given(m_method("POST"))
        .and(m_path("/repo.git/info/lfs/objects/batch"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "transfer": "basic",
            "objects": [{
                "oid": OID, "size": CONTENT.len(),
                "actions": { "download": { "href": storage_url } }
            }]
        })))
        .mount(&server)
        .await;
    Mock::given(m_method("GET"))
        .and(m_path(format!("/storage/{OID}")))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(CONTENT))
        .mount(&server)
        .await;

    let repo = fresh_repo();
    let remote_url = format!("{}/repo", server.uri());
    let status = Command::new("git")
        .arg("-C")
        .arg(repo.path())
        .args(["config", "--local", "remote.origin.url", &remote_url])
        .status()
        .unwrap();
    assert!(status.success());

    let pointer = format!(
        "version https://git-lfs.github.com/spec/v1\n\
         oid sha256:{OID}\n\
         size {}\n",
        CONTENT.len(),
    );

    let path = repo.path().to_owned();
    let pointer_bytes = pointer.into_bytes();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["smudge"], &pointer_bytes))
        .await
        .unwrap();
    assert!(
        out.status.success(),
        "smudge failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
    assert_eq!(out.stdout, CONTENT);
}

#[test]
fn smudge_with_no_endpoint_fails_with_clear_message() {
    // Repo has neither `lfs.url` nor `remote.origin.url` — the resolver
    // returns `Unresolved` and the CLI should surface that as a non-zero
    // exit with a sensible message rather than panicking or hanging.
    let repo = fresh_repo();
    let pointer = b"version https://git-lfs.github.com/spec/v1\n\
                    oid sha256:30031a9831674dd684c3817399acebc88a116ce5a7a3fbc0cf34d92521a534e6\n\
                    size 11\n";
    let out = run_in(repo.path(), &["smudge"], pointer);
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("LFS endpoint") || stderr.contains("origin"),
        "expected endpoint-resolution error in stderr: {stderr}",
    );
}

#[tokio::test]
async fn smudge_401_with_no_credentials_fails_cleanly() {
    // Server demands auth; the configured credential helper chain (in-process
    // cache → `git credential`) has nothing to give in this throwaway repo,
    // so the smudge should propagate the 401 as a non-zero exit instead of
    // hanging or panicking.
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    const OID: &str = "30031a9831674dd684c3817399acebc88a116ce5a7a3fbc0cf34d92521a534e6";
    const CONTENT: &[u8] = b"downloaded\n";

    let server = MockServer::start().await;
    Mock::given(m_method("POST"))
        .and(m_path("/objects/batch"))
        .respond_with(
            ResponseTemplate::new(401)
                .insert_header("LFS-Authenticate", "Basic realm=\"x\"")
                .set_body_json(json!({"message": "auth required"})),
        )
        .mount(&server)
        .await;

    let repo = fresh_repo();
    // Point lfs.url at the wiremock and disable the user's real credential
    // helpers so `git credential fill` won't successfully resolve anything
    // (which would happen on a developer machine with a global helper).
    let status = Command::new("git")
        .arg("-C")
        .arg(repo.path())
        .args(["config", "--local", "lfs.url", &server.uri()])
        .status()
        .unwrap();
    assert!(status.success());

    let pointer = format!(
        "version https://git-lfs.github.com/spec/v1\n\
         oid sha256:{OID}\n\
         size {}\n",
        CONTENT.len(),
    );

    let path = repo.path().to_owned();
    let pointer_bytes = pointer.into_bytes();
    let out = tokio::task::spawn_blocking(move || {
        // GIT_TERMINAL_PROMPT=0 + an empty GIT_CONFIG_GLOBAL stop the
        // user's globally-configured helpers from filling in creds during
        // the test (which would change the response from 401 to 200 and
        // make the assertion meaningless).
        let bin_dir = Path::new(BIN).parent().unwrap();
        let path_var = std::env::var("PATH").unwrap_or_default();
        let new_path = format!("{}:{path_var}", bin_dir.display());
        let mut child = Command::new(BIN)
            .args(["smudge"])
            .current_dir(&path)
            .env("PATH", new_path)
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .as_mut()
            .unwrap()
            .write_all(&pointer_bytes)
            .unwrap();
        drop(child.stdin.take());
        child.wait_with_output().unwrap()
    })
    .await
    .unwrap();

    assert!(
        !out.status.success(),
        "expected smudge to fail with 401; stdout: {} stderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
}

// ---------- fetch ---------------------------------------------------------

/// Init a repo and configure a deterministic identity so commits work
/// regardless of the developer's git config (or lack thereof).
fn fresh_repo_with_identity() -> TempDir {
    let repo = fresh_repo();
    git_in(repo.path(), &["config", "user.email", "test@example.com"]);
    git_in(repo.path(), &["config", "user.name", "test"]);
    git_in(repo.path(), &["config", "commit.gpgsign", "false"]);
    repo
}

fn git_in(cwd: &Path, args: &[&str]) {
    // Hermetic: the developer's ~/.gitconfig may have `filter.lfs.clean`
    // installed globally, which would clean-filter test fixtures behind
    // our back. Strip global + system config so test repos see only what
    // the test sets up.
    //
    // PATH is augmented with the test binary's directory so `git add`
    // can find `git-lfs` when a `filter.lfs.process` config (set by
    // `install_lfs`) hands the file off for clean-filtering.
    let bin_dir = Path::new(BIN).parent().unwrap();
    let path_var = std::env::var("PATH").unwrap_or_default();
    let new_path = format!("{}:{}", bin_dir.display(), path_var);
    let status = Command::new("git")
        .arg("-C")
        .arg(cwd)
        .args(args)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .env("PATH", new_path)
        .status()
        .unwrap();
    assert!(status.success(), "git {args:?} failed");
}

/// Write `pointer_text` to `path` in `repo`, then add+commit.
fn commit_pointer_at(repo: &Path, path: &str, pointer_text: &[u8]) {
    std::fs::write(repo.join(path), pointer_text).unwrap();
    git_in(repo, &["add", path]);
    git_in(repo, &["commit", "-q", "-m", &format!("add {path}")]);
}

/// Write `.gitattributes` content to `repo` and commit it. Used by tests
/// that need an `.gitattributes`-aware command (e.g. fsck) to know which
/// paths are LFS-tracked.
fn commit_gitattributes(repo: &Path, content: &str) {
    std::fs::write(repo.join(".gitattributes"), content).unwrap();
    git_in(repo, &["add", ".gitattributes"]);
    git_in(repo, &["commit", "-q", "-m", "add .gitattributes"]);
}

fn pointer_text(oid: &str, size: usize) -> Vec<u8> {
    format!("version https://git-lfs.github.com/spec/v1\noid sha256:{oid}\nsize {size}\n")
        .into_bytes()
}

/// Extract the OID hex from a pointer file's `oid sha256:` line.
fn oid_from_pointer(pointer: &[u8]) -> String {
    let s = std::str::from_utf8(pointer).expect("pointer is utf-8");
    for line in s.lines() {
        if let Some(rest) = line.strip_prefix("oid sha256:") {
            return rest.trim().to_owned();
        }
    }
    panic!("no oid line in pointer: {s}");
}

/// `git rev-parse HEAD` for the given repo.
fn head_oid_str(cwd: &Path) -> String {
    let out = Command::new("git")
        .arg("-C")
        .arg(cwd)
        .args(["rev-parse", "HEAD"])
        .output()
        .unwrap();
    assert!(out.status.success(), "rev-parse failed");
    String::from_utf8_lossy(&out.stdout).trim().to_owned()
}

#[tokio::test]
async fn fetch_downloads_objects_referenced_by_head() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // Two distinct LFS objects committed under different paths.
    const OID_A: &str = "30031a9831674dd684c3817399acebc88a116ce5a7a3fbc0cf34d92521a534e6";
    const A: &[u8] = b"downloaded\n";
    // sha256("two\n")
    const OID_B: &str = "27dd8ed44a83ff94d557f9fd0412ed5a8cbca69ea04922d88c01184a07300a5a";
    const B: &[u8] = b"two\n";

    let server = MockServer::start().await;
    let url_a = format!("{}/storage/{OID_A}", server.uri());
    let url_b = format!("{}/storage/{OID_B}", server.uri());

    Mock::given(m_method("POST"))
        .and(m_path("/objects/batch"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "transfer": "basic",
            "objects": [
                { "oid": OID_A, "size": A.len(), "actions": { "download": { "href": url_a } } },
                { "oid": OID_B, "size": B.len(), "actions": { "download": { "href": url_b } } }
            ]
        })))
        .mount(&server)
        .await;
    Mock::given(m_method("GET"))
        .and(m_path(format!("/storage/{OID_A}")))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(A))
        .mount(&server)
        .await;
    Mock::given(m_method("GET"))
        .and(m_path(format!("/storage/{OID_B}")))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(B))
        .mount(&server)
        .await;

    let repo = fresh_repo_with_identity();
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", &server.uri()],
    );
    commit_gitattributes(repo.path(), "*.bin filter=lfs diff=lfs merge=lfs -text\n");
    commit_pointer_at(repo.path(), "a.bin", &pointer_text(OID_A, A.len()));
    commit_pointer_at(repo.path(), "b.bin", &pointer_text(OID_B, B.len()));

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["fetch"], b""))
        .await
        .unwrap();
    assert!(
        out.status.success(),
        "fetch failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("Downloading LFS objects: 100% (2/2)"),
        "unexpected stderr: {stderr}",
    );

    for (oid, _content) in [(OID_A, A), (OID_B, B)] {
        let stored = repo
            .path()
            .join(".git/lfs/objects")
            .join(&oid[0..2])
            .join(&oid[2..4])
            .join(oid);
        assert!(stored.is_file(), "missing stored object: {stored:?}");
    }
}

#[tokio::test]
async fn fetch_is_noop_when_objects_already_in_store() {
    use wiremock::MockServer;

    // Wiremock with no mocks — any HTTP call would 404. We're proving the
    // fetch command short-circuits before hitting the network.
    let server = MockServer::start().await;
    let repo = fresh_repo_with_identity();
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", &server.uri()],
    );

    // Stage an object in the local store via the clean filter so its
    // OID + content are consistent — same path the smudge tests use.
    let cleaned = run_in(repo.path(), &["clean"], b"already-here\n");
    assert!(cleaned.status.success());
    let pointer_bytes = cleaned.stdout;
    commit_pointer_at(repo.path(), "a.bin", &pointer_bytes);

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["fetch"], b""))
        .await
        .unwrap();
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_eq!(stdout, "", "unexpected stdout: {stdout}");
    // No download attempt — silent success matches upstream's no-op.
    assert!(
        !stderr.contains("Downloading LFS objects:"),
        "unexpected progress on no-op: {stderr}",
    );
}

#[tokio::test]
async fn pull_materializes_pointer_files_into_real_content() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // Simulates the post-clone state: working tree has pointer text,
    // store is empty, lfs.url is configured. `git lfs pull` should
    // download the object and rewrite the working-tree file.
    const OID: &str = "30031a9831674dd684c3817399acebc88a116ce5a7a3fbc0cf34d92521a534e6";
    const CONTENT: &[u8] = b"downloaded\n";

    let server = MockServer::start().await;
    let storage_url = format!("{}/storage/{OID}", server.uri());

    Mock::given(m_method("POST"))
        .and(m_path("/objects/batch"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "transfer": "basic",
            "objects": [{
                "oid": OID, "size": CONTENT.len(),
                "actions": { "download": { "href": storage_url } }
            }]
        })))
        .mount(&server)
        .await;
    Mock::given(m_method("GET"))
        .and(m_path(format!("/storage/{OID}")))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(CONTENT))
        .mount(&server)
        .await;

    let repo = fresh_repo_with_identity();
    install_lfs(repo.path());
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", &server.uri()],
    );

    // Commit the pointer text directly. This simulates the post-clone
    // state where the working tree holds pointer text (because clone's
    // smudge was skipped or the store was empty at the time).
    commit_gitattributes(repo.path(), "*.bin filter=lfs diff=lfs merge=lfs -text\n");
    commit_pointer_at(repo.path(), "data.bin", &pointer_text(OID, CONTENT.len()));
    // Sanity: working tree currently has pointer text, not real content.
    let wt_before = std::fs::read(repo.path().join("data.bin")).unwrap();
    assert!(wt_before.starts_with(b"version https://git-lfs.github.com/spec/v1\n"));

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["pull"], b""))
        .await
        .unwrap();
    assert!(
        out.status.success(),
        "pull failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );

    // Working tree now has actual content.
    let wt_after = std::fs::read(repo.path().join("data.bin")).unwrap();
    assert_eq!(wt_after, CONTENT, "working tree not materialized");
}

#[tokio::test]
async fn fetch_returns_failure_exit_when_some_objects_fail() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // Server reports the object as missing in the batch response; should
    // not be retried, fetch should exit non-zero.
    const OID: &str = "30031a9831674dd684c3817399acebc88a116ce5a7a3fbc0cf34d92521a534e6";
    const SIZE: usize = 11;

    let server = MockServer::start().await;
    Mock::given(m_method("POST"))
        .and(m_path("/objects/batch"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "transfer": "basic",
            "objects": [{
                "oid": OID, "size": SIZE,
                "error": { "code": 404, "message": "not on server" }
            }]
        })))
        .mount(&server)
        .await;

    let repo = fresh_repo_with_identity();
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", &server.uri()],
    );
    commit_gitattributes(repo.path(), "*.bin filter=lfs diff=lfs merge=lfs -text\n");
    commit_pointer_at(repo.path(), "a.bin", &pointer_text(OID, SIZE));

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["fetch"], b""))
        .await
        .unwrap();
    assert!(!out.status.success(), "fetch should have exited non-zero");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("not on server") || stderr.contains("failed to download"),
        "unexpected stderr: {stderr}"
    );
}

// ---------- push ---------------------------------------------------------

#[tokio::test]
async fn push_uploads_only_objects_not_in_remote_tracking() {
    use serde_json::json;
    use wiremock::matchers::{body_bytes, method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // Two commits: an "old" pointer (already on the remote) and a
    // "new" pointer (about to be pushed). A fake refs/remotes/origin/main
    // pointing at the first commit tells push that's the remote's state.
    const OLD: &[u8] = b"old payload\n";
    const NEW: &[u8] = b"new payload\n";

    let server = MockServer::start().await;
    let repo = fresh_repo_with_identity();
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", &server.uri()],
    );

    // Use clean to populate the local store + emit canonical pointer text.
    let cleaned_old = run_in(repo.path(), &["clean"], OLD);
    assert!(cleaned_old.status.success());
    commit_pointer_at(repo.path(), "old.bin", &cleaned_old.stdout);
    let first_commit = head_oid_str(repo.path());

    let cleaned_new = run_in(repo.path(), &["clean"], NEW);
    assert!(cleaned_new.status.success());
    commit_pointer_at(repo.path(), "new.bin", &cleaned_new.stdout);

    let new_oid = oid_from_pointer(&cleaned_new.stdout);
    let old_oid = oid_from_pointer(&cleaned_old.stdout);

    // Fake "origin" tracking ref at the first commit.
    git_in(
        repo.path(),
        &["update-ref", "refs/remotes/origin/main", &first_commit],
    );

    // Batch should only see the NEW oid in the request — and we'll
    // assert that with body_bytes-style matching by checking that
    // wiremock's PUT mock for `old_oid` sees zero hits.
    let upload_url = format!("{}/storage/{new_oid}", server.uri());
    Mock::given(m_method("POST"))
        .and(m_path("/objects/batch"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "transfer": "basic",
            "objects": [{
                "oid": new_oid, "size": NEW.len(),
                "actions": { "upload": { "href": upload_url } }
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(m_method("PUT"))
        .and(m_path(format!("/storage/{new_oid}")))
        .and(body_bytes(NEW))
        .respond_with(ResponseTemplate::new(200))
        .expect(1)
        .mount(&server)
        .await;

    // No mock for the OLD oid's storage URL — if push attempts a PUT for
    // it, wiremock returns 404 by default and the test will fail.

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["push", "origin", "HEAD"], b""))
        .await
        .unwrap();
    assert!(
        out.status.success(),
        "push failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("Uploading LFS objects: 100% (1/1)"),
        "unexpected stdout: {stdout}",
    );
    assert_ne!(new_oid, old_oid, "test fixture sanity");
}

#[tokio::test]
async fn push_is_noop_when_remote_tracking_matches_head() {
    use wiremock::MockServer;

    let server = MockServer::start().await;
    let repo = fresh_repo_with_identity();
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", &server.uri()],
    );

    let cleaned = run_in(repo.path(), &["clean"], b"only commit\n");
    commit_pointer_at(repo.path(), "a.bin", &cleaned.stdout);
    let head = head_oid_str(repo.path());
    // Fake remote already at HEAD → nothing new to push.
    git_in(
        repo.path(),
        &["update-ref", "refs/remotes/origin/main", &head],
    );

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["push", "origin", "HEAD"], b""))
        .await
        .unwrap();
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    // No upload attempted, so no progress meter — silent success.
    // The progress line goes to stdout (matches upstream's
    // tasklog→Stdout sink, see commands/uploader.go), so checking
    // stdout is enough.
    assert!(
        !stdout.contains("Uploading LFS objects:"),
        "unexpected progress on no-op: {stdout}",
    );
}

#[tokio::test]
async fn pre_push_uploads_new_commit_objects_via_stdin_protocol() {
    use serde_json::json;
    use wiremock::matchers::{body_bytes, method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // Two commits: pre-push driven by stdin like git would.
    const OLD: &[u8] = b"old\n";
    const NEW: &[u8] = b"new\n";

    let server = MockServer::start().await;
    let repo = fresh_repo_with_identity();
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", &server.uri()],
    );

    let cleaned_old = run_in(repo.path(), &["clean"], OLD);
    commit_pointer_at(repo.path(), "old.bin", &cleaned_old.stdout);
    let first_commit = head_oid_str(repo.path());

    let cleaned_new = run_in(repo.path(), &["clean"], NEW);
    commit_pointer_at(repo.path(), "new.bin", &cleaned_new.stdout);
    let head = head_oid_str(repo.path());

    let new_oid = oid_from_pointer(&cleaned_new.stdout);
    let upload_url = format!("{}/storage/{new_oid}", server.uri());

    Mock::given(m_method("POST"))
        .and(m_path("/objects/batch"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "transfer": "basic",
            "objects": [{
                "oid": new_oid, "size": NEW.len(),
                "actions": { "upload": { "href": upload_url } }
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(m_method("PUT"))
        .and(m_path(format!("/storage/{new_oid}")))
        .and(body_bytes(NEW))
        .respond_with(ResponseTemplate::new(200))
        .expect(1)
        .mount(&server)
        .await;

    // git's pre-push stdin format: <local-ref> <local-sha> <remote-ref> <remote-sha>
    let stdin = format!("refs/heads/main {head} refs/heads/main {first_commit}\n");
    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || {
        run_in(
            &path,
            &["pre-push", "origin", "https://example/dummy"],
            stdin.as_bytes(),
        )
    })
    .await
    .unwrap();
    assert!(
        out.status.success(),
        "pre-push failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
}

#[tokio::test]
async fn pre_push_skips_branch_deletes() {
    // Local sha is all zeros → branch delete → nothing to push.
    // No mocks: any HTTP call would 404 and the test would fail.
    use wiremock::MockServer;

    let server = MockServer::start().await;
    let repo = fresh_repo_with_identity();
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", &server.uri()],
    );
    // Need at least one commit for git rev-parse to work later — but
    // for the pre-push call itself the stdin alone drives behavior.
    let cleaned = run_in(repo.path(), &["clean"], b"x\n");
    commit_pointer_at(repo.path(), "x.bin", &cleaned.stdout);

    let zero = "0000000000000000000000000000000000000000";
    let some_remote = head_oid_str(repo.path());
    let stdin = format!("(delete) {zero} refs/heads/dead {some_remote}\n");
    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || {
        run_in(
            &path,
            &["pre-push", "origin", "https://example/dummy"],
            stdin.as_bytes(),
        )
    })
    .await
    .unwrap();
    assert!(
        out.status.success(),
        "pre-push should succeed for delete-only push: {}",
        String::from_utf8_lossy(&out.stderr),
    );
}

#[tokio::test]
async fn pre_push_new_branch_uses_remote_tracking_as_exclude() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // Brand-new branch: remote-sha is all zeros. We should fall back
    // to refs/remotes/origin/* as the exclude set. Set up a remote
    // tracking ref at commit 1; only commit 2's object should upload.
    const OLD: &[u8] = b"old payload\n";
    const NEW: &[u8] = b"new payload\n";

    let server = MockServer::start().await;
    let repo = fresh_repo_with_identity();
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", &server.uri()],
    );

    let cleaned_old = run_in(repo.path(), &["clean"], OLD);
    commit_pointer_at(repo.path(), "old.bin", &cleaned_old.stdout);
    let first_commit = head_oid_str(repo.path());

    let cleaned_new = run_in(repo.path(), &["clean"], NEW);
    commit_pointer_at(repo.path(), "new.bin", &cleaned_new.stdout);
    let head = head_oid_str(repo.path());

    git_in(
        repo.path(),
        &["update-ref", "refs/remotes/origin/main", &first_commit],
    );

    let new_oid = oid_from_pointer(&cleaned_new.stdout);
    let upload_url = format!("{}/storage/{new_oid}", server.uri());

    Mock::given(m_method("POST"))
        .and(m_path("/objects/batch"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "transfer": "basic",
            "objects": [{
                "oid": new_oid, "size": NEW.len(),
                "actions": { "upload": { "href": upload_url } }
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(m_method("PUT"))
        .and(m_path(format!("/storage/{new_oid}")))
        .respond_with(ResponseTemplate::new(200))
        .expect(1)
        .mount(&server)
        .await;

    // Push of a new branch (refs/heads/feature) — remote-sha all zeros.
    let zero = "0000000000000000000000000000000000000000";
    let stdin = format!("refs/heads/feature {head} refs/heads/feature {zero}\n");
    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || {
        run_in(
            &path,
            &["pre-push", "origin", "https://example/dummy"],
            stdin.as_bytes(),
        )
    })
    .await
    .unwrap();
    assert!(
        out.status.success(),
        "pre-push failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
}

#[tokio::test]
async fn pre_push_respects_git_lfs_skip_push_env() {
    use wiremock::MockServer;

    // Even with a real refspec on stdin, GIT_LFS_SKIP_PUSH=1 should
    // make pre-push exit cleanly without scanning or uploading.
    let server = MockServer::start().await;
    let repo = fresh_repo_with_identity();
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", &server.uri()],
    );
    let cleaned = run_in(repo.path(), &["clean"], b"payload\n");
    commit_pointer_at(repo.path(), "x.bin", &cleaned.stdout);
    let head = head_oid_str(repo.path());

    let zero = "0000000000000000000000000000000000000000";
    let stdin = format!("refs/heads/main {head} refs/heads/main {zero}\n");

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || {
        // run_in already augments PATH. We construct Command directly
        // here to add the env var. Mirrors run_in's PATH handling.
        let bin_dir = Path::new(BIN).parent().unwrap();
        let path_var = std::env::var("PATH").unwrap_or_default();
        let new_path = format!("{}:{path_var}", bin_dir.display());
        let mut child = Command::new(BIN)
            .args(["pre-push", "origin", "https://example/dummy"])
            .current_dir(&path)
            .env("PATH", new_path)
            .env("GIT_LFS_SKIP_PUSH", "1")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        // GIT_LFS_SKIP_PUSH=1 lets pre-push exit before reading stdin, so
        // the write races with child exit. EPIPE here is fine — we're
        // asserting the child exits cleanly, not that it consumed input.
        let _ = child.stdin.as_mut().unwrap().write_all(stdin.as_bytes());
        drop(child.stdin.take());
        child.wait_with_output().unwrap()
    })
    .await
    .unwrap();
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[tokio::test]
async fn push_handles_server_already_has_object() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // Server returns the object with no `actions` → batch's "I already
    // have this" semantics. Transfer should treat as success without
    // attempting the PUT.
    let server = MockServer::start().await;
    let repo = fresh_repo_with_identity();
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", &server.uri()],
    );

    let cleaned = run_in(repo.path(), &["clean"], b"already on server\n");
    commit_pointer_at(repo.path(), "x.bin", &cleaned.stdout);
    let oid = oid_from_pointer(&cleaned.stdout);

    Mock::given(m_method("POST"))
        .and(m_path("/objects/batch"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "transfer": "basic",
            "objects": [{ "oid": oid, "size": "already on server\n".len() }]
        })))
        .mount(&server)
        .await;

    // Note: NO mount for any PUT path. If push attempts an upload,
    // wiremock 404s and the test fails.

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["push", "origin", "HEAD"], b""))
        .await
        .unwrap();
    assert!(
        out.status.success(),
        "push failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("Uploading LFS objects: 100% (1/1)"),
        "unexpected stdout: {stdout}",
    );
}

// ---------- ls-files -----------------------------------------------------

/// SHA-256 of `b"hello world\n"` — used in several ls-files / status tests
/// because it's also what `clean` produces for that content, so we can
/// cross-check the marker logic against a real store entry.
const HELLO_OID: &str = "a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447";
const HELLO_LEN: usize = 12;

#[test]
fn ls_files_lists_committed_pointer_with_short_oid_and_marker() {
    let repo = fresh_repo_with_identity();
    let p = pointer_text(HELLO_OID, HELLO_LEN);
    commit_pointer_at(repo.path(), "big.bin", &p);

    let out = run_in(repo.path(), &["ls-files"], b"");
    assert!(
        out.status.success(),
        "ls-files failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    // Format: "<oid10> <marker> <name>". File is on disk at `big.bin` —
    // but it's a *pointer*, not the real 12-byte content, so the marker
    // is `-` (size mismatch).
    assert_eq!(
        stdout.trim(),
        format!("{} - big.bin", &HELLO_OID[..10]),
        "got: {stdout:?}"
    );
}

#[test]
fn ls_files_long_emits_full_oid() {
    let repo = fresh_repo_with_identity();
    commit_pointer_at(repo.path(), "big.bin", &pointer_text(HELLO_OID, HELLO_LEN));

    let out = run_in(repo.path(), &["ls-files", "--long"], b"");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains(HELLO_OID),
        "long form should contain full OID: {stdout}"
    );
}

#[test]
fn ls_files_name_only_emits_just_path() {
    let repo = fresh_repo_with_identity();
    std::fs::create_dir_all(repo.path().join("data")).unwrap();
    commit_pointer_at(
        repo.path(),
        "data/blob.bin",
        &pointer_text(HELLO_OID, HELLO_LEN),
    );

    let out = run_in(repo.path(), &["ls-files", "--name-only"], b"");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(stdout.trim(), "data/blob.bin");
}

#[test]
fn ls_files_size_appends_humanized_bytes() {
    let repo = fresh_repo_with_identity();
    commit_pointer_at(repo.path(), "big.bin", &pointer_text(HELLO_OID, 1_572_864));

    let out = run_in(repo.path(), &["ls-files", "--size"], b"");
    let stdout = String::from_utf8_lossy(&out.stdout);
    // 1.5 MiB → "1.50 MB" with our humanizer.
    assert!(
        stdout.contains("(1.50 MB)"),
        "expected size suffix, got: {stdout}"
    );
}

#[test]
fn ls_files_skips_plain_blobs() {
    let repo = fresh_repo_with_identity();
    std::fs::write(repo.path().join("plain.txt"), b"just text").unwrap();
    git_in(repo.path(), &["add", "plain.txt"]);
    git_in(repo.path(), &["commit", "-q", "-m", "plain"]);

    let out = run_in(repo.path(), &["ls-files"], b"");
    assert!(out.status.success());
    assert!(
        out.stdout.is_empty(),
        "expected empty output, got: {:?}",
        String::from_utf8_lossy(&out.stdout)
    );
}

#[test]
fn ls_files_empty_repo_prints_nothing() {
    // No commits yet — must not panic, must succeed silently.
    let repo = fresh_repo_with_identity();
    let out = run_in(repo.path(), &["ls-files"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(out.stdout.is_empty());
}

#[test]
fn ls_files_explicit_ref_walks_that_tree() {
    let repo = fresh_repo_with_identity();
    commit_pointer_at(
        repo.path(),
        "first.bin",
        &pointer_text(HELLO_OID, HELLO_LEN),
    );
    let first = head_oid_str(repo.path());
    // Second commit replaces the pointer with plain content.
    std::fs::write(repo.path().join("first.bin"), b"plain text now").unwrap();
    git_in(repo.path(), &["add", "first.bin"]);
    git_in(repo.path(), &["commit", "-q", "-m", "overwrite"]);

    // At HEAD, no pointers visible.
    let head_out = run_in(repo.path(), &["ls-files"], b"");
    assert!(
        head_out.stdout.is_empty(),
        "{:?}",
        String::from_utf8_lossy(&head_out.stdout)
    );

    // At the older commit, the pointer is visible.
    let old_out = run_in(repo.path(), &["ls-files", &first], b"");
    let stdout = String::from_utf8_lossy(&old_out.stdout);
    assert!(
        stdout.contains("first.bin"),
        "expected first.bin in output, got: {stdout}"
    );
}

#[test]
fn ls_files_all_walks_history_across_refs() {
    let repo = fresh_repo_with_identity();
    commit_pointer_at(
        repo.path(),
        "first.bin",
        &pointer_text(HELLO_OID, HELLO_LEN),
    );
    // Replace with plain content. Without --all, ls-files (HEAD tree)
    // would no longer see the pointer.
    std::fs::write(repo.path().join("first.bin"), b"plain text").unwrap();
    git_in(repo.path(), &["add", "first.bin"]);
    git_in(repo.path(), &["commit", "-q", "-m", "overwrite"]);

    let out = run_in(repo.path(), &["ls-files", "--all"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains(&HELLO_OID[..10]),
        "--all should resurrect historical pointer: {stdout}"
    );
}

#[test]
fn ls_files_json_is_parseable_and_complete() {
    let repo = fresh_repo_with_identity();
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(HELLO_OID, HELLO_LEN));

    let out = run_in(repo.path(), &["ls-files", "--json"], b"");
    assert!(out.status.success());
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("valid JSON");
    let files = v["files"].as_array().expect("files array");
    assert_eq!(files.len(), 1);
    let f = &files[0];
    assert_eq!(f["name"], "x.bin");
    assert_eq!(f["size"], HELLO_LEN);
    assert_eq!(f["oid"], HELLO_OID);
    assert_eq!(f["oid_type"], "sha256");
    assert_eq!(f["version"], "https://git-lfs.github.com/spec/v1");
    assert_eq!(f["checkout"], false);
    assert_eq!(f["downloaded"], false);
}

#[test]
fn ls_files_debug_emits_per_file_block() {
    let repo = fresh_repo_with_identity();
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(HELLO_OID, HELLO_LEN));

    let out = run_in(repo.path(), &["ls-files", "--debug"], b"");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("filepath: x.bin"), "{stdout}");
    assert!(stdout.contains(&format!("size: {HELLO_LEN}")), "{stdout}");
    assert!(stdout.contains("oid: sha256 "), "{stdout}");
    assert!(
        stdout.contains("version: https://git-lfs.github.com/spec/v1"),
        "{stdout}"
    );
}

// ---------- status -------------------------------------------------------

#[test]
fn status_default_lists_staged_and_unstaged_lfs_changes() {
    let repo = fresh_repo_with_identity();
    // Commit a pointer at HEAD so we have something to diff against.
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(HELLO_OID, HELLO_LEN));

    // Stage a modification: new pointer pointing at a different OID.
    let other_oid = "1111111111111111111111111111111111111111111111111111111111111111";
    std::fs::write(repo.path().join("x.bin"), pointer_text(other_oid, 99)).unwrap();
    git_in(repo.path(), &["add", "x.bin"]);

    // Then make an *additional* unstaged modification on top.
    std::fs::write(repo.path().join("x.bin"), pointer_text(other_oid, 12345)).unwrap();

    let out = run_in(repo.path(), &["status"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("On branch "), "{stdout}");
    assert!(stdout.contains("Objects to be committed:"), "{stdout}");
    assert!(
        stdout.contains("Objects not staged for commit:"),
        "{stdout}"
    );
    assert!(stdout.contains("x.bin"), "{stdout}");
    assert!(
        stdout.contains("LFS:"),
        "expected LFS classification: {stdout}"
    );
}

#[test]
fn status_classifies_non_lfs_blob_as_git() {
    let repo = fresh_repo_with_identity();
    // Plain (non-pointer) blob, modified+staged.
    std::fs::write(repo.path().join("plain.txt"), b"first\n").unwrap();
    git_in(repo.path(), &["add", "plain.txt"]);
    git_in(repo.path(), &["commit", "-q", "-m", "add plain"]);

    std::fs::write(repo.path().join("plain.txt"), b"second\n").unwrap();
    git_in(repo.path(), &["add", "plain.txt"]);

    let out = run_in(repo.path(), &["status"], b"");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("plain.txt"), "{stdout}");
    assert!(
        stdout.contains("Git:"),
        "expected Git classification, got: {stdout}"
    );
    assert!(
        !stdout.contains("LFS:"),
        "non-pointer should not be LFS: {stdout}"
    );
}

#[test]
fn status_porcelain_one_line_per_change() {
    let repo = fresh_repo_with_identity();
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(HELLO_OID, HELLO_LEN));
    let other = "1111111111111111111111111111111111111111111111111111111111111111";
    std::fs::write(repo.path().join("x.bin"), pointer_text(other, 99)).unwrap();
    git_in(repo.path(), &["add", "x.bin"]);

    let out = run_in(repo.path(), &["status", "--porcelain"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    // 'M' modification → " M x.bin" (leading space, single-letter status).
    // trim_end keeps the leading space, which is significant.
    assert_eq!(stdout.trim_end(), " M x.bin", "got: {stdout:?}");
}

#[test]
fn status_json_only_emits_lfs_entries() {
    let repo = fresh_repo_with_identity();
    // Two committed files: one LFS pointer, one plain.
    commit_pointer_at(repo.path(), "p.bin", &pointer_text(HELLO_OID, HELLO_LEN));
    std::fs::write(repo.path().join("plain.txt"), b"first\n").unwrap();
    git_in(repo.path(), &["add", "plain.txt"]);
    git_in(repo.path(), &["commit", "-q", "-m", "add plain"]);

    // Stage a modification to BOTH.
    let other = "2222222222222222222222222222222222222222222222222222222222222222";
    std::fs::write(repo.path().join("p.bin"), pointer_text(other, 99)).unwrap();
    std::fs::write(repo.path().join("plain.txt"), b"second\n").unwrap();
    git_in(repo.path(), &["add", "p.bin", "plain.txt"]);

    let out = run_in(repo.path(), &["status", "--json"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("valid JSON");
    let files = v["files"].as_object().expect("files object");
    // Only the LFS file should appear.
    assert!(files.contains_key("p.bin"), "missing p.bin: {v}");
    assert!(
        !files.contains_key("plain.txt"),
        "plain.txt leaked into JSON: {v}"
    );
    assert_eq!(files["p.bin"]["status"], "M");
}

#[test]
fn status_empty_repo_emits_section_layout() {
    // Before the initial commit, upstream `git lfs status` emits the
    // normal section layout against the empty tree — no "No commits
    // yet" message and no "On branch ..." header. Matches t-status's
    // "before initial commit" expectations.
    let repo = fresh_repo_with_identity();
    let out = run_in(repo.path(), &["status"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("Objects to be committed:"), "{stdout}");
    assert!(
        stdout.contains("Objects not staged for commit:"),
        "{stdout}"
    );
    assert!(!stdout.contains("On branch"), "{stdout}");
}

#[test]
fn status_handles_addition_with_zero_src_sha() {
    // Stage a brand-new pointer file. Diff-index will report src_sha as
    // zero; status must classify the dst side and not crash on the
    // "from" lookup.
    let repo = fresh_repo_with_identity();
    // Need an initial commit so diff-index has a HEAD to compare against.
    std::fs::write(repo.path().join("seed"), b"x").unwrap();
    git_in(repo.path(), &["add", "seed"]);
    git_in(repo.path(), &["commit", "-q", "-m", "seed"]);

    std::fs::write(
        repo.path().join("new.bin"),
        pointer_text(HELLO_OID, HELLO_LEN),
    )
    .unwrap();
    git_in(repo.path(), &["add", "new.bin"]);

    let out = run_in(repo.path(), &["status"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("new.bin"), "{stdout}");
    assert!(stdout.contains("LFS:"), "{stdout}");
}

// ---------- env ----------------------------------------------------------

#[test]
fn env_in_repo_emits_version_paths_and_filter_config() {
    let repo = fresh_repo_with_identity();
    git_in(
        repo.path(),
        &["config", "--local", "lfs.url", "https://example.test/lfs"],
    );
    // Pretend `git lfs install --local` ran by setting one filter
    // explicitly — env should reflect it back.
    git_in(
        repo.path(),
        &[
            "config",
            "--local",
            "filter.lfs.clean",
            "git-lfs clean -- %f",
        ],
    );

    let out = run_in(repo.path(), &["env"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);

    assert!(
        stdout.starts_with("git-lfs/"),
        "missing version banner: {stdout}"
    );
    assert!(
        stdout.contains("git version "),
        "missing git version: {stdout}"
    );
    assert!(
        stdout.contains("Endpoint=https://example.test/lfs"),
        "missing endpoint: {stdout}"
    );
    assert!(
        stdout.contains("LocalGitDir="),
        "missing LocalGitDir: {stdout}"
    );
    assert!(
        stdout.contains("LocalMediaDir="),
        "missing LocalMediaDir: {stdout}"
    );
    assert!(stdout.contains("TempDir="), "missing TempDir: {stdout}");
    assert!(
        stdout.contains(r#"git config filter.lfs.clean = "git-lfs clean -- %f""#),
        "missing filter config line: {stdout}",
    );
}

#[test]
fn env_outside_repo_emits_empty_repo_paths_and_succeeds() {
    let tmp = TempDir::new().unwrap();
    // Note: NOT a git repo. env should still run.
    let out = run_in(tmp.path(), &["env"], b"");
    assert!(
        out.status.success(),
        "env outside repo should succeed; stderr: {}",
        String::from_utf8_lossy(&out.stderr),
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("git-lfs/"),
        "version still expected: {stdout}"
    );
    // Outside a repo, upstream still emits the path lines with empty
    // values for the repo-specific ones (and relative forms for
    // LocalMediaDir / TempDir / LfsStorageDir). The filter.lfs.* keys
    // come straight from `git config` — empty here because this test
    // points GIT_CONFIG_{GLOBAL,SYSTEM} at /dev/null, so no scope has
    // them set. (When a real user has run `git lfs install`, the
    // global scope is present and would supply the canonical strings.)
    assert!(stdout.contains("LocalGitDir="), "{stdout}");
    assert!(stdout.contains("LocalWorkingDir="), "{stdout}");
    assert!(
        stdout.contains("git config filter.lfs.process = \"\""),
        "{stdout}"
    );
}

#[test]
fn ls_files_marker_star_when_real_content_present_at_right_size() {
    // Simulate "checkout already happened": commit a pointer in git, but
    // also write the real content (12 bytes of "hello world\n") at the
    // working-tree path. Then the marker should flip from `-` to `*`.
    let repo = fresh_repo_with_identity();
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(HELLO_OID, HELLO_LEN));
    std::fs::write(repo.path().join("x.bin"), b"hello world\n").unwrap();

    let out = run_in(repo.path(), &["ls-files"], b"");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains(" * x.bin"),
        "expected `*` marker, got: {stdout}"
    );
}

// ---------- migrate export -----------------------------------------------
//
// Round-trip: run import to convert plain blobs into pointers, then
// run export to convert them back. The end state of the working tree
// should match the original content, and the .gitattributes lines
// should reflect the un-tracked patterns.

#[test]
fn migrate_export_inverts_import_via_round_trip() {
    let repo = fresh_repo_with_identity();
    let original = vec![b'Z'; 256];
    commit_plain_file(repo.path(), "data.bin", &original);

    // Forward: convert to LFS.
    let imp = run_in(
        repo.path(),
        &["migrate", "import", "--include", "*.bin"],
        b"",
    );
    assert!(
        imp.status.success(),
        "import stderr: {}",
        String::from_utf8_lossy(&imp.stderr)
    );
    let after_import = std::fs::read(repo.path().join("data.bin")).unwrap();
    assert!(
        String::from_utf8_lossy(&after_import).starts_with("version https://"),
        "import should leave pointer text",
    );

    // Inverse: expand pointers back to raw content.
    let exp = run_in(
        repo.path(),
        &["migrate", "export", "--include", "*.bin"],
        b"",
    );
    assert!(
        exp.status.success(),
        "export stderr: {}",
        String::from_utf8_lossy(&exp.stderr)
    );
    let after_export = std::fs::read(repo.path().join("data.bin")).unwrap();
    assert_eq!(
        after_export, original,
        "round-trip should restore original bytes"
    );

    // .gitattributes should now declare the path as un-tracked.
    let attrs = std::fs::read_to_string(repo.path().join(".gitattributes")).unwrap();
    assert!(
        attrs.contains("*.bin !text !filter !merge !diff"),
        "expected un-track line: {attrs}",
    );
    // And the original `filter=lfs` line should be gone.
    assert!(
        !attrs.contains("*.bin filter=lfs"),
        "filter=lfs line should be removed: {attrs}",
    );
}

#[test]
fn migrate_export_requires_include() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "x.bin", b"x");

    let out = run_in(repo.path(), &["migrate", "export"], b"");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("One or more files must be specified with --include"),
        "{stderr}"
    );
}

#[test]
fn migrate_export_refuses_dirty_working_tree() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "x.bin", b"x");
    std::fs::write(repo.path().join("x.bin"), b"changed").unwrap();

    let out = run_in(
        repo.path(),
        &["migrate", "export", "--include", "*.bin"],
        b"",
    );
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("uncommitted changes"), "{stderr}");
}

#[test]
fn migrate_export_leaves_pointer_alone_when_object_missing_from_store() {
    // Hand-craft a repo where the working tree contains a pointer
    // file referencing an OID we never put in the store. Export
    // should leave the pointer in place rather than silently
    // truncating it.
    let repo = fresh_repo_with_identity();
    commit_pointer_at(
        repo.path(),
        "missing.bin",
        &pointer_text(HELLO_OID, HELLO_LEN),
    );

    let out = run_in(
        repo.path(),
        &["migrate", "export", "--include", "*.bin"],
        b"",
    );
    assert!(
        out.status.success(),
        "export should still succeed; stderr: {}",
        String::from_utf8_lossy(&out.stderr),
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("Expanded 0 pointer"),
        "expected zero conversions: {stdout}"
    );
    // Working-tree file is still pointer text — not truncated.
    let bin = std::fs::read(repo.path().join("missing.bin")).unwrap();
    assert!(
        String::from_utf8_lossy(&bin).starts_with("version https://"),
        "missing.bin should still be pointer text",
    );
}

#[test]
fn migrate_export_only_unconverts_paths_matching_include() {
    let repo = fresh_repo_with_identity();
    // Distinct content per file so each gets its own git blob OID —
    // see the "first-reference wins" deferral in NOTES.md for why
    // identical content across paths can't be split selectively.
    commit_plain_file(repo.path(), "convert.bin", &[b'A'; 200]);
    commit_plain_file(repo.path(), "keep.bin", &[b'B'; 200]);

    // Import both into LFS.
    let imp = run_in(
        repo.path(),
        &["migrate", "import", "--include", "*.bin"],
        b"",
    );
    assert!(
        imp.status.success(),
        "{}",
        String::from_utf8_lossy(&imp.stderr)
    );

    // Export only convert.bin back. keep.bin should stay as a pointer.
    let exp = run_in(
        repo.path(),
        &["migrate", "export", "--include", "convert.bin"],
        b"",
    );
    assert!(
        exp.status.success(),
        "{}",
        String::from_utf8_lossy(&exp.stderr)
    );

    let convert = std::fs::read(repo.path().join("convert.bin")).unwrap();
    assert_eq!(convert, vec![b'A'; 200], "convert.bin restored");

    let keep = std::fs::read(repo.path().join("keep.bin")).unwrap();
    assert!(
        String::from_utf8_lossy(&keep).starts_with("version https://"),
        "keep.bin must stay pointer-form: {:?}",
        String::from_utf8_lossy(&keep),
    );
}

// ---------- migrate import -----------------------------------------------

#[test]
fn migrate_import_rewrites_history_so_matching_blobs_become_pointers() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "readme.txt", b"plain text\n");
    commit_plain_file(repo.path(), "data.bin", &vec![b'X'; 256]);

    let out = run_in(
        repo.path(),
        &["migrate", "import", "--include", "*.bin"],
        b"",
    );
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("Converted 1 blob"), "{stdout}");

    let bin_after = std::fs::read(repo.path().join("data.bin")).unwrap();
    let s = String::from_utf8_lossy(&bin_after);
    assert!(
        s.starts_with("version https://git-lfs.github.com/spec/v1\n"),
        "data.bin should be pointer text: {s:?}",
    );
    let attrs = std::fs::read_to_string(repo.path().join(".gitattributes")).unwrap();
    assert!(
        attrs.contains("*.bin filter=lfs diff=lfs merge=lfs -text"),
        "{attrs}",
    );
}

#[test]
fn migrate_import_preserves_non_matching_files() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "keep.txt", b"plain content\n");
    commit_plain_file(repo.path(), "data.bin", &[b'X'; 100]);

    let out = run_in(
        repo.path(),
        &["migrate", "import", "--include", "*.bin"],
        b"",
    );
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let txt = std::fs::read(repo.path().join("keep.txt")).unwrap();
    assert_eq!(txt, b"plain content\n");
}

#[test]
fn migrate_import_above_filters_by_size() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "small.bin", &[0u8; 50]);
    commit_plain_file(repo.path(), "large.bin", &vec![0u8; 5_000]);

    let out = run_in(repo.path(), &["migrate", "import", "--above", "1k"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    let small = std::fs::read(repo.path().join("small.bin")).unwrap();
    assert_eq!(small.len(), 50, "small.bin should remain plain");

    let large = std::fs::read(repo.path().join("large.bin")).unwrap();
    let s = String::from_utf8_lossy(&large);
    assert!(
        s.starts_with("version https://git-lfs.github.com/spec/v1\n"),
        "large.bin should be pointer text: {s:?}",
    );
}

#[test]
fn migrate_import_default_converts_all_files() {
    // Upstream's `migrate import` with no flags walks every blob and
    // derives `*.<ext>` patterns from the converted paths. Used to be
    // an error in this port; we caught up to upstream behavior in
    // the import-polish pass.
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "x.bin", b"hello");

    let out = run_in(repo.path(), &["migrate", "import"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let bin = std::fs::read(repo.path().join("x.bin")).unwrap();
    let s = String::from_utf8_lossy(&bin);
    assert!(
        s.starts_with("version https://git-lfs.github.com/spec/v1\n"),
        "expected pointer text: {s:?}"
    );
}

#[test]
fn migrate_import_refuses_dirty_working_tree() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "x.bin", b"x");
    std::fs::write(repo.path().join("x.bin"), b"changed").unwrap();

    let out = run_in(
        repo.path(),
        &["migrate", "import", "--include", "*.bin"],
        b"",
    );
    assert!(!out.status.success(), "expected refusal");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("uncommitted changes"), "{stderr}");
}

#[test]
fn migrate_import_no_rewrite_appends_one_commit() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(
        repo.path(),
        ".gitattributes",
        b"*.bin filter=lfs diff=lfs merge=lfs -text\n",
    );
    commit_plain_file(repo.path(), "x.bin", &[b'X'; 100]);

    let head_before = head_oid_str(repo.path());

    let out = run_in(
        repo.path(),
        &["migrate", "import", "--no-rewrite", "x.bin"],
        b"",
    );
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr),
    );

    let head_after = head_oid_str(repo.path());
    assert_ne!(head_before, head_after, "HEAD should advance");

    let bin = std::fs::read(repo.path().join("x.bin")).unwrap();
    let s = String::from_utf8_lossy(&bin);
    assert!(
        s.starts_with("version https://git-lfs.github.com/spec/v1\n"),
        "{s:?}"
    );

    let parent_out = Command::new("git")
        .arg("-C")
        .arg(repo.path())
        .args(["rev-parse", "HEAD~1"])
        .output()
        .unwrap();
    let parent = String::from_utf8_lossy(&parent_out.stdout)
        .trim()
        .to_owned();
    assert_eq!(parent, head_before);
}

#[test]
fn migrate_import_no_rewrite_skips_already_pointer_files() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(
        repo.path(),
        ".gitattributes",
        b"*.bin filter=lfs diff=lfs merge=lfs -text\n",
    );
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(HELLO_OID, HELLO_LEN));
    let head_before = head_oid_str(repo.path());

    let out = run_in(
        repo.path(),
        &["migrate", "import", "--no-rewrite", "x.bin"],
        b"",
    );
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let head_after = head_oid_str(repo.path());
    assert_eq!(head_before, head_after, "no commit should be appended");
}

#[test]
fn migrate_import_no_rewrite_requires_paths() {
    let repo = fresh_repo_with_identity();
    let out = run_in(repo.path(), &["migrate", "import", "--no-rewrite"], b"");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("requires one or more paths"), "{stderr}");
}

#[test]
fn migrate_import_writes_lfs_object_to_store() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "data.bin", &[b'Y'; 200]);

    let out = run_in(
        repo.path(),
        &["migrate", "import", "--include", "*.bin"],
        b"",
    );
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    use sha2::{Digest, Sha256};
    let oid_bytes: [u8; 32] = Sha256::digest(vec![b'Y'; 200].as_slice()).into();
    let oid_hex: String = oid_bytes.iter().fold(String::new(), |mut s, b| {
        use std::fmt::Write;
        let _ = write!(s, "{b:02x}");
        s
    });
    let stored = repo
        .path()
        .join(".git/lfs/objects")
        .join(&oid_hex[0..2])
        .join(&oid_hex[2..4])
        .join(&oid_hex);
    assert!(stored.is_file(), "expected stored object at {stored:?}");
    let content = std::fs::read(&stored).unwrap();
    assert_eq!(content, vec![b'Y'; 200]);
}

// ---------- migrate info -------------------------------------------------

/// Helper: write `path` with `content` and commit it. Used for migrate
/// info fixtures where we don't care about LFS pointer-ness.
fn commit_plain_file(repo: &Path, path: &str, content: &[u8]) {
    if let Some(parent) = std::path::Path::new(path).parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(repo.join(parent)).unwrap();
    }
    std::fs::write(repo.join(path), content).unwrap();
    git_in(repo, &["add", path]);
    git_in(repo, &["commit", "-q", "-m", &format!("add {path}")]);
}

#[test]
fn migrate_info_groups_by_extension_and_sorts_by_size() {
    let repo = fresh_repo_with_identity();
    // Two .png files (totaling 30 bytes), one .jpg (5 bytes).
    commit_plain_file(repo.path(), "a.png", &[b'a'; 20]);
    commit_plain_file(repo.path(), "b.png", &[b'b'; 10]);
    commit_plain_file(repo.path(), "c.jpg", &[b'c'; 5]);

    let out = run_in(repo.path(), &["migrate", "info"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    let png_pos = stdout.find("*.png").unwrap_or(usize::MAX);
    let jpg_pos = stdout.find("*.jpg").unwrap_or(usize::MAX);
    assert!(
        png_pos < jpg_pos,
        "*.png should sort above *.jpg by size: {stdout}"
    );
    assert!(
        stdout.contains("2/2 files"),
        "expected png to count 2 files: {stdout}"
    );
}

#[test]
fn migrate_info_above_threshold_excludes_smaller_files() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "small.bin", &[0u8; 50]);
    commit_plain_file(repo.path(), "large.bin", &vec![0u8; 5_000]);

    let out = run_in(repo.path(), &["migrate", "info", "--above", "1k"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    // Two total .bin, one above threshold.
    assert!(
        stdout.contains("1/2 files") || stdout.contains("1/1 files"),
        "{stdout}"
    );
    // The percentage shown should reflect "1 above out of 2 total" =
    // 50%. (If our pipeline only ever sees files matching the filter,
    // it'd report 100% — assert against the wrong-path interpretation.)
    assert!(
        stdout.contains("50%"),
        "expected 50% (1/2 above), got: {stdout}"
    );
}

#[test]
fn migrate_info_top_n_caps_extension_rows() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "a.aaa", b"x");
    commit_plain_file(repo.path(), "b.bbb", b"x");
    commit_plain_file(repo.path(), "c.ccc", b"x");

    let out = run_in(repo.path(), &["migrate", "info", "--top", "1"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    // Exactly one *.<ext> row should appear.
    let ext_lines: Vec<_> = stdout.lines().filter(|l| l.starts_with("*.")).collect();
    assert_eq!(ext_lines.len(), 1, "expected 1 row, got: {ext_lines:?}");
}

#[test]
fn migrate_info_include_filter_restricts_to_matching_paths() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "data.png", b"X");
    commit_plain_file(repo.path(), "other.txt", b"Y");

    let out = run_in(repo.path(), &["migrate", "info", "--include", "*.png"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("*.png"), "{stdout}");
    assert!(
        !stdout.contains("*.txt"),
        "*.txt should be excluded by include filter: {stdout}"
    );
}

#[test]
fn migrate_info_pointers_follow_buckets_lfs_separately() {
    let repo = fresh_repo_with_identity();
    // Plain files vs. LFS pointer files — pointer should land in the
    // "LFS Objects" bucket, not under *.bin.
    commit_plain_file(repo.path(), "plain.bin", &[b'X'; 100]);
    commit_pointer_at(
        repo.path(),
        "pointer.bin",
        &pointer_text(HELLO_OID, 999_999),
    );

    let out = run_in(repo.path(), &["migrate", "info"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("LFS Objects"),
        "expected LFS Objects bucket: {stdout}"
    );
    // *.bin should still appear (plain.bin), but with only 1 file (not 2).
    let bin_line = stdout.lines().find(|l| l.starts_with("*.bin"));
    assert!(bin_line.is_some(), "expected *.bin row: {stdout}");
    assert!(
        bin_line.unwrap().contains("1/1"),
        "expected only plain.bin in *.bin: {stdout}"
    );
}

#[test]
fn migrate_info_pointers_ignore_drops_lfs_files_entirely() {
    let repo = fresh_repo_with_identity();
    commit_plain_file(repo.path(), "plain.bin", &[b'X'; 100]);
    commit_pointer_at(
        repo.path(),
        "pointer.bin",
        &pointer_text(HELLO_OID, 999_999),
    );

    let out = run_in(
        repo.path(),
        &["migrate", "info", "--pointers", "ignore"],
        b"",
    );
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        !stdout.contains("LFS Objects"),
        "ignore should drop LFS bucket: {stdout}"
    );
}

#[test]
fn migrate_info_pointers_no_follow_treats_pointers_as_regular_blobs() {
    let repo = fresh_repo_with_identity();
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(HELLO_OID, 999_999));

    let out = run_in(
        repo.path(),
        &["migrate", "info", "--pointers", "no-follow"],
        b"",
    );
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    // No special LFS bucket; the pointer's blob is counted under *.bin
    // using the actual blob size on disk (~133 bytes), not the pointer's
    // recorded 999999.
    assert!(!stdout.contains("LFS Objects"), "{stdout}");
    assert!(stdout.contains("*.bin"), "{stdout}");
}

#[test]
fn migrate_info_empty_repo_prints_nothing() {
    let repo = fresh_repo_with_identity();
    let out = run_in(repo.path(), &["migrate", "info"], b"");
    // No commits; HEAD doesn't exist. Should succeed silently.
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        out.stdout.is_empty(),
        "stdout: {:?}",
        String::from_utf8_lossy(&out.stdout)
    );
}

#[test]
fn migrate_info_above_with_invalid_size_errors() {
    let repo = fresh_repo_with_identity();
    let out = run_in(repo.path(), &["migrate", "info", "--above", "garbage"], b"");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("invalid size"), "{stderr}");
}

#[test]
fn migrate_info_unknown_pointers_value_errors() {
    let repo = fresh_repo_with_identity();
    let out = run_in(repo.path(), &["migrate", "info", "--pointers", "yolo"], b"");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("Unsupported --pointers option value"),
        "{stderr}"
    );
}

// ---------- post-checkout / post-commit / post-merge --------------------
//
// v0 ships these as exit-0 stubs. The real reason they exist now: our
// `git lfs install` writes hook scripts that invoke `git lfs
// post-checkout` etc., so without the subcommands every git checkout
// would fail with "unrecognized subcommand". These tests pin the
// argument shapes upstream's hooks expect, so when real lockable
// behavior lands we don't accidentally change the surface.

#[test]
fn post_checkout_accepts_three_args_and_exits_zero() {
    let repo = fresh_repo();
    let out = run_in(
        repo.path(),
        &[
            "post-checkout",
            "0000000000000000000000000000000000000000",
            "1111111111111111111111111111111111111111",
            "1",
        ],
        b"",
    );
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn post_checkout_with_wrong_arg_count_fails() {
    let repo = fresh_repo();
    let out = run_in(repo.path(), &["post-checkout", "only-one-arg"], b"");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("expected 3 args"), "{stderr}");
}

#[test]
fn post_commit_accepts_no_args_and_exits_zero() {
    let repo = fresh_repo();
    let out = run_in(repo.path(), &["post-commit"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn post_merge_accepts_one_arg_and_exits_zero() {
    let repo = fresh_repo();
    let out = run_in(repo.path(), &["post-merge", "0"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn post_merge_with_no_args_fails() {
    let repo = fresh_repo();
    let out = run_in(repo.path(), &["post-merge"], b"");
    assert!(!out.status.success());
}

#[test]
fn install_then_real_git_checkout_does_not_fail_via_post_checkout_hook() {
    // This is the test that justifies the exit-0 stubs. Without them,
    // installing the hooks then running `git checkout -b new-branch`
    // (which fires post-checkout) would error out from inside git.
    let repo = fresh_repo_with_identity();
    install_lfs(repo.path());
    std::fs::write(repo.path().join("a.txt"), b"hi").unwrap();
    git_in(repo.path(), &["add", "a.txt"]);
    git_in(repo.path(), &["commit", "-q", "-m", "seed"]);
    // Trigger the post-checkout hook: switch to a new branch.
    let bin_dir = std::path::Path::new(BIN).parent().unwrap();
    let path_var = std::env::var("PATH").unwrap_or_default();
    let new_path = format!("{}:{path_var}", bin_dir.display());
    let status = Command::new("git")
        .arg("-C")
        .arg(repo.path())
        .args(["checkout", "-b", "new-branch", "-q"])
        .env("PATH", new_path)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .status()
        .unwrap();
    assert!(
        status.success(),
        "git checkout -b failed (post-checkout hook errored?)"
    );
}

// ---------- checkout -----------------------------------------------------

/// `git lfs install --local` so the smudge filter is configured. Without
/// this, checkout returns early with the "not installed" message, which
/// is a useful safety net but obscures the assertions we want to make.
fn install_lfs(repo: &Path) {
    let bin_dir = std::path::Path::new(BIN).parent().unwrap();
    let path_var = std::env::var("PATH").unwrap_or_default();
    let new_path = format!("{}:{path_var}", bin_dir.display());
    let status = Command::new(BIN)
        .args(["install", "--local"])
        .current_dir(repo)
        .env("PATH", new_path)
        .status()
        .unwrap();
    assert!(status.success(), "git lfs install --local failed");
}

#[test]
fn checkout_without_install_emits_friendly_message() {
    let repo = fresh_repo_with_identity();
    let oid = put_object_in_store(repo.path(), b"hello world\n");
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(&oid, 12));

    let out = run_in(repo.path(), &["checkout"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("Git LFS is not installed"), "{stdout}");
}

#[test]
fn checkout_materializes_pointer_text_into_real_content() {
    let repo = fresh_repo_with_identity();
    install_lfs(repo.path());
    let oid = put_object_in_store(repo.path(), b"hello world\n");
    commit_gitattributes(repo.path(), "*.bin filter=lfs diff=lfs merge=lfs -text\n");
    // Working-tree file is currently the pointer text (just-after-clone state).
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(&oid, 12));

    let before = std::fs::read(repo.path().join("x.bin")).unwrap();
    assert!(before.starts_with(b"version https://git-lfs.github.com/spec/v1\n"));

    let out = run_in(repo.path(), &["checkout"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let after = std::fs::read(repo.path().join("x.bin")).unwrap();
    assert_eq!(after, b"hello world\n");
}

#[test]
fn checkout_with_path_filters_only_those_files() {
    let repo = fresh_repo_with_identity();
    install_lfs(repo.path());
    let oid_a = put_object_in_store(repo.path(), b"alpha bytes\n");
    let oid_b = put_object_in_store(repo.path(), b"beta bytes!\n");
    commit_gitattributes(repo.path(), "*.bin filter=lfs diff=lfs merge=lfs -text\n");
    commit_pointer_at(repo.path(), "a.bin", &pointer_text(&oid_a, 12));
    commit_pointer_at(repo.path(), "b.bin", &pointer_text(&oid_b, 12));

    // Only check out a.bin.
    let out = run_in(repo.path(), &["checkout", "a.bin"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(
        std::fs::read(repo.path().join("a.bin")).unwrap(),
        b"alpha bytes\n"
    );
    // b.bin still has its pointer text — we filtered it out.
    let b = std::fs::read(repo.path().join("b.bin")).unwrap();
    assert!(
        b.starts_with(b"version https://git-lfs.github.com/spec/v1\n"),
        "b.bin should still be a pointer"
    );
}

#[test]
fn checkout_with_directory_pattern_matches_subtree() {
    let repo = fresh_repo_with_identity();
    install_lfs(repo.path());
    std::fs::create_dir_all(repo.path().join("data")).unwrap();
    let oid_top = put_object_in_store(repo.path(), b"top-level!!!\n");
    let oid_sub = put_object_in_store(repo.path(), b"in subtree!!\n");
    commit_gitattributes(repo.path(), "*.bin filter=lfs diff=lfs merge=lfs -text\n");
    commit_pointer_at(repo.path(), "top.bin", &pointer_text(&oid_top, 13));
    commit_pointer_at(repo.path(), "data/sub.bin", &pointer_text(&oid_sub, 13));

    let out = run_in(repo.path(), &["checkout", "data/"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(
        std::fs::read(repo.path().join("data/sub.bin")).unwrap(),
        b"in subtree!!\n",
    );
    // top.bin is outside the data/ pattern → still pointer text.
    let top = std::fs::read(repo.path().join("top.bin")).unwrap();
    assert!(top.starts_with(b"version https://git-lfs.github.com/spec/v1\n"));
}

#[test]
fn checkout_no_pointers_says_nothing_to_checkout() {
    let repo = fresh_repo_with_identity();
    install_lfs(repo.path());
    std::fs::write(repo.path().join("plain.txt"), b"plain\n").unwrap();
    git_in(repo.path(), &["add", "plain.txt"]);
    git_in(repo.path(), &["commit", "-q", "-m", "plain"]);

    let out = run_in(repo.path(), &["checkout"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("Nothing to checkout"), "{stdout}");
}

#[test]
fn checkout_skips_pointer_when_object_missing_locally() {
    // Pointer references an OID we never put in the store, and there's
    // no remote to fetch from. checkout should leave the pointer text
    // alone rather than truncating the file.
    let repo = fresh_repo_with_identity();
    install_lfs(repo.path());
    commit_gitattributes(repo.path(), "*.bin filter=lfs diff=lfs merge=lfs -text\n");
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(HELLO_OID, HELLO_LEN));

    let out = run_in(repo.path(), &["checkout"], b"");
    // The command exits non-zero because the fetch attempt fails (no remote).
    let stderr = String::from_utf8_lossy(&out.stderr);
    // Whichever way it exits, the file must still be pointer text — never truncated.
    let after = std::fs::read(repo.path().join("x.bin")).unwrap();
    assert!(
        after.starts_with(b"version https://git-lfs.github.com/spec/v1\n"),
        "x.bin should remain pointer text, got: {:?}, stderr: {stderr}",
        String::from_utf8_lossy(&after),
    );
}

// ---------- prune --------------------------------------------------------

#[test]
fn prune_no_objects_says_so() {
    let repo = fresh_repo_with_identity();
    let out = run_in(repo.path(), &["prune"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("No local LFS objects to prune"), "{stdout}");
}

#[test]
fn prune_retains_objects_referenced_by_head_tree() {
    let repo = fresh_repo_with_identity();
    let oid = put_object_in_store(repo.path(), b"hello world\n");
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(&oid, 12));

    let out = run_in(repo.path(), &["prune"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("1 local objects, 1 retained"), "{stdout}");

    // Object still on disk.
    let path = repo
        .path()
        .join(".git/lfs/objects")
        .join(&oid[0..2])
        .join(&oid[2..4])
        .join(&oid);
    assert!(path.is_file(), "expected object preserved at {path:?}");
}

#[test]
fn prune_deletes_object_not_referenced_anywhere() {
    let repo = fresh_repo_with_identity();
    // Make a HEAD with no LFS pointers (just plain content) — anything
    // in the store is fair game.
    std::fs::write(repo.path().join("plain.txt"), b"hi").unwrap();
    git_in(repo.path(), &["add", "plain.txt"]);
    git_in(repo.path(), &["commit", "-q", "-m", "plain"]);

    let orphan_oid = put_object_in_store(repo.path(), b"orphan content");
    let path = repo
        .path()
        .join(".git/lfs/objects")
        .join(&orphan_oid[0..2])
        .join(&orphan_oid[2..4])
        .join(&orphan_oid);
    assert!(path.is_file(), "fixture pre-condition");

    let out = run_in(repo.path(), &["prune"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("1 local objects, 0 retained"), "{stdout}");
    assert!(stdout.contains("Deleting objects: 100% (1/1)"), "{stdout}");
    assert!(
        !path.is_file(),
        "orphan object should be deleted at {path:?}"
    );
}

#[test]
fn prune_dry_run_does_not_delete() {
    let repo = fresh_repo_with_identity();
    std::fs::write(repo.path().join("plain.txt"), b"hi").unwrap();
    git_in(repo.path(), &["add", "plain.txt"]);
    git_in(repo.path(), &["commit", "-q", "-m", "plain"]);

    let orphan_oid = put_object_in_store(repo.path(), b"orphan");
    let path = repo
        .path()
        .join(".git/lfs/objects")
        .join(&orphan_oid[0..2])
        .join(&orphan_oid[2..4])
        .join(&orphan_oid);

    let out = run_in(repo.path(), &["prune", "--dry-run"], b"");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("1 files would be pruned"), "{stdout}");
    // File still there.
    assert!(path.is_file(), "dry-run should not delete: {path:?}");
}

#[test]
fn prune_verbose_lists_each_pruned_object() {
    let repo = fresh_repo_with_identity();
    std::fs::write(repo.path().join("plain.txt"), b"hi").unwrap();
    git_in(repo.path(), &["add", "plain.txt"]);
    git_in(repo.path(), &["commit", "-q", "-m", "plain"]);

    let orphan_oid = put_object_in_store(repo.path(), b"orphan content goes here");

    let out = run_in(repo.path(), &["prune", "--verbose"], b"");
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    // First 10 chars of the OID appear (full OID actually) on a `* ` line.
    assert!(
        stdout.contains(&orphan_oid),
        "expected OID in verbose output: {stdout}"
    );
}

#[test]
fn prune_retains_unpushed_commits() {
    // The pointer is in HEAD but NOT in any old version of HEAD's tree
    // — it's only reachable via the most recent commit, which hasn't
    // been pushed. Prune must retain it.
    let repo = fresh_repo_with_identity();
    // First commit: plain content, simulates "what's on the remote".
    std::fs::write(repo.path().join("plain.txt"), b"hi").unwrap();
    git_in(repo.path(), &["add", "plain.txt"]);
    git_in(repo.path(), &["commit", "-q", "-m", "plain"]);
    // Mark this commit as the remote tip.
    git_in(
        repo.path(),
        &["update-ref", "refs/remotes/origin/main", "HEAD"],
    );

    // Now add an LFS pointer locally and commit (unpushed).
    let oid = put_object_in_store(repo.path(), b"unpushed content");
    let p = pointer_text(&oid, b"unpushed content".len());
    std::fs::write(repo.path().join("data.bin"), &p).unwrap();
    git_in(repo.path(), &["add", "data.bin"]);
    git_in(repo.path(), &["commit", "-q", "-m", "add data"]);

    // Replace HEAD's data.bin with plain content so HEAD's *tree* no
    // longer references the LFS pointer — but the unpushed commit still
    // does, so we must retain.
    std::fs::write(repo.path().join("data.bin"), b"plain replacement").unwrap();
    git_in(repo.path(), &["add", "data.bin"]);
    git_in(repo.path(), &["commit", "-q", "-m", "replace"]);

    let path = repo
        .path()
        .join(".git/lfs/objects")
        .join(&oid[0..2])
        .join(&oid[2..4])
        .join(&oid);

    let out = run_in(repo.path(), &["prune", "--dry-run"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("1 local objects, 1 retained"),
        "expected unpushed pointer to be retained, got: {stdout}",
    );
    assert!(path.is_file(), "object must still exist");
}

#[test]
fn prune_with_no_remote_falls_back_to_head_tree_only() {
    // No remote configured — unpushed retain step degrades to
    // "everything in HEAD's tree." An object ONLY in earlier history
    // is then prunable, just like upstream.
    let repo = fresh_repo_with_identity();
    let oid = put_object_in_store(repo.path(), b"old content");
    commit_pointer_at(
        repo.path(),
        "old.bin",
        &pointer_text(&oid, b"old content".len()),
    );
    // Replace with plain content. Earlier commit still references the
    // pointer (history), but HEAD's tree doesn't.
    std::fs::write(repo.path().join("old.bin"), b"plain text").unwrap();
    git_in(repo.path(), &["add", "old.bin"]);
    git_in(repo.path(), &["commit", "-q", "-m", "replace"]);

    let path = repo
        .path()
        .join(".git/lfs/objects")
        .join(&oid[0..2])
        .join(&oid[2..4])
        .join(&oid);
    assert!(path.is_file(), "fixture pre-condition");

    let out = run_in(repo.path(), &["prune"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    // No origin remote → unpushed scan returns the FULL HEAD history
    // (since exclude set is empty), which still references this OID,
    // so it's retained even without a remote.
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("1 local objects, 1 retained"), "{stdout}");
    assert!(path.is_file());
}

// ---------- fsck ---------------------------------------------------------

/// Helper: write the LFS object for `content` directly into a repo's
/// store, sharded under `.git/lfs/objects/<aa>/<bb>/<oid>`. Sidesteps
/// having to wire the clean filter just to populate test fixtures.
fn put_object_in_store(repo: &Path, content: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let oid_bytes: [u8; 32] = Sha256::digest(content).into();
    let oid = oid_bytes.iter().fold(String::new(), |mut s, b| {
        use std::fmt::Write;
        let _ = write!(s, "{b:02x}");
        s
    });
    let dir = repo
        .join(".git/lfs/objects")
        .join(&oid[0..2])
        .join(&oid[2..4]);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join(&oid), content).unwrap();
    oid
}

#[test]
fn fsck_reports_ok_when_pointers_match_store() {
    let repo = fresh_repo_with_identity();
    let oid = put_object_in_store(repo.path(), b"hello world\n");
    commit_pointer_at(repo.path(), "x.bin", &pointer_text(&oid, 12));

    let out = run_in(repo.path(), &["fsck"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("Git LFS fsck OK"), "{stdout}");
}

#[test]
fn fsck_reports_missing_object_and_exits_one() {
    let repo = fresh_repo_with_identity();
    // Pointer references an OID we never put in the store and there's
    // no `lfs.fetchexclude` covering it, so fsck reports it as
    // openError and exits 1 — matching upstream + `t-fsck.sh::fsck
    // detects invalid objects`.
    commit_pointer_at(
        repo.path(),
        "missing.bin",
        &pointer_text(HELLO_OID, HELLO_LEN),
    );

    let out = run_in(repo.path(), &["fsck", "--dry-run"], b"");
    assert_eq!(out.status.code(), Some(1));
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("openError"),
        "expected openError, got: {stdout}"
    );
    assert!(stdout.contains("missing.bin"), "{stdout}");
}

#[test]
fn fsck_skips_objects_excluded_by_lfs_fetchexclude() {
    let repo = fresh_repo_with_identity();
    // Set up a pointer whose object is missing locally. Without
    // exclude config, fsck would flag it; with `lfs.fetchexclude`
    // covering the path, fsck silently skips and exits 0.
    git_in(repo.path(), &["config", "lfs.fetchexclude", "missing*"]);
    commit_pointer_at(
        repo.path(),
        "missing.bin",
        &pointer_text(HELLO_OID, HELLO_LEN),
    );

    let out = run_in(repo.path(), &["fsck", "--dry-run"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        !stdout.contains("openError"),
        "should skip excluded path: {stdout}",
    );
}

#[test]
fn fsck_reports_corrupt_object_and_quarantines_it() {
    let repo = fresh_repo_with_identity();
    // Put an object whose contents don't match its filename's OID.
    let claimed_oid = HELLO_OID; // OID of "hello world\n"
    let dir = repo
        .path()
        .join(".git/lfs/objects")
        .join(&claimed_oid[0..2])
        .join(&claimed_oid[2..4]);
    std::fs::create_dir_all(&dir).unwrap();
    // Wrong content — would hash to something else entirely.
    std::fs::write(dir.join(claimed_oid), b"wrong content").unwrap();

    commit_pointer_at(
        repo.path(),
        "tamper.bin",
        &pointer_text(claimed_oid, HELLO_LEN),
    );

    let out = run_in(repo.path(), &["fsck"], b"");
    assert_eq!(out.status.code(), Some(1));
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("corruptObject"), "{stdout}");
    assert!(stdout.contains("moving corrupt objects"), "{stdout}");
    // Quarantined file lives at .git/lfs/bad/<oid>.
    let bad = repo.path().join(".git/lfs/bad").join(claimed_oid);
    assert!(bad.is_file(), "expected quarantined file at {bad:?}");
    // Original location is gone.
    assert!(
        !dir.join(claimed_oid).exists(),
        "store still has corrupt file"
    );
}

#[test]
fn fsck_dry_run_does_not_quarantine() {
    let repo = fresh_repo_with_identity();
    let claimed_oid = HELLO_OID;
    let dir = repo
        .path()
        .join(".git/lfs/objects")
        .join(&claimed_oid[0..2])
        .join(&claimed_oid[2..4]);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join(claimed_oid), b"wrong content").unwrap();
    commit_pointer_at(
        repo.path(),
        "tamper.bin",
        &pointer_text(claimed_oid, HELLO_LEN),
    );

    let out = run_in(repo.path(), &["fsck", "--dry-run"], b"");
    assert_eq!(out.status.code(), Some(1));
    // File is still in the store (not quarantined).
    assert!(
        dir.join(claimed_oid).is_file(),
        "dry-run should not move files"
    );
    // No bad/ directory created at all.
    assert!(!repo.path().join(".git/lfs/bad").exists());
}

#[test]
fn fsck_pointers_only_skips_object_check() {
    // A pointer that references a missing object would normally fail
    // `--objects`; with `--pointers` only, we ignore that and only
    // report non-canonical pointers.
    let repo = fresh_repo_with_identity();
    commit_gitattributes(repo.path(), "*.bin filter=lfs diff=lfs merge=lfs -text\n");
    commit_pointer_at(
        repo.path(),
        "missing.bin",
        &pointer_text(HELLO_OID, HELLO_LEN),
    );

    let out = run_in(repo.path(), &["fsck", "--pointers"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("Git LFS fsck OK"), "{stdout}");
}

#[test]
fn fsck_pointers_flags_non_canonical_pointer() {
    let repo = fresh_repo_with_identity();
    commit_gitattributes(repo.path(), "*.bin filter=lfs diff=lfs merge=lfs -text\n");
    // Pointer with no trailing newline — parses, isn't canonical.
    let mut p = pointer_text(HELLO_OID, HELLO_LEN);
    assert_eq!(p.last(), Some(&b'\n'));
    p.pop();
    commit_pointer_at(repo.path(), "non.bin", &p);

    let out = run_in(repo.path(), &["fsck", "--pointers"], b"");
    assert_eq!(out.status.code(), Some(1));
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("nonCanonicalPointer"), "{stdout}");
}

#[test]
fn fsck_pointers_flags_unexpected_git_object_for_non_pointer_blob() {
    // A path that .gitattributes tracks as filter=lfs but whose
    // committed blob isn't a valid pointer should be reported as
    // `unexpectedGitObject` — matches upstream's t-fsck.sh behavior.
    let repo = fresh_repo_with_identity();
    commit_gitattributes(repo.path(), "*.bin filter=lfs diff=lfs merge=lfs -text\n");
    // Plain text content — definitely not a pointer.
    commit_pointer_at(repo.path(), "rogue.bin", b"not a pointer at all\n");

    let out = run_in(repo.path(), &["fsck", "--pointers"], b"");
    assert_eq!(out.status.code(), Some(1));
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("unexpectedGitObject"), "{stdout}");
    assert!(stdout.contains("rogue.bin"), "{stdout}");
}

#[test]
fn fsck_pointers_skips_blobs_for_paths_not_lfs_tracked() {
    // A non-canonical pointer at a path that isn't filter=lfs should
    // not be flagged — fsck classifies *against* .gitattributes.
    let repo = fresh_repo_with_identity();
    let mut p = pointer_text(HELLO_OID, HELLO_LEN);
    p.pop();
    commit_pointer_at(repo.path(), "untracked.bin", &p);

    let out = run_in(repo.path(), &["fsck", "--pointers"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn fsck_objects_only_skips_pointer_canonicality_check() {
    // A non-canonical pointer should NOT fail --objects; the missing
    // object it references should.
    let repo = fresh_repo_with_identity();
    let mut p = pointer_text(HELLO_OID, HELLO_LEN);
    p.pop(); // strip trailing newline → non-canonical
    commit_pointer_at(repo.path(), "non.bin", &p);

    let out = run_in(repo.path(), &["fsck", "--objects", "--dry-run"], b"");
    assert_eq!(out.status.code(), Some(1));
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("openError"), "expected openError: {stdout}");
    assert!(
        !stdout.contains("nonCanonicalPointer"),
        "should skip canonical check: {stdout}"
    );
}

// ---------- version ------------------------------------------------------

#[test]
fn version_prints_banner_and_succeeds() {
    let repo = fresh_repo();
    let out = run_in(repo.path(), &["version"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.starts_with("git-lfs/"), "{stdout}");
}

#[test]
fn version_works_outside_repo_too() {
    let tmp = TempDir::new().unwrap();
    let out = run_in(tmp.path(), &["version"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

// ---------- pointer ------------------------------------------------------

#[test]
fn pointer_check_returns_zero_for_valid_pointer() {
    let repo = fresh_repo();
    let p = pointer_text(HELLO_OID, HELLO_LEN);
    std::fs::write(repo.path().join("p.txt"), &p).unwrap();
    let out = run_in(repo.path(), &["pointer", "--check", "--file", "p.txt"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn pointer_check_exits_one_for_non_pointer() {
    let repo = fresh_repo();
    std::fs::write(repo.path().join("p.txt"), b"this is plain text\n").unwrap();
    let out = run_in(repo.path(), &["pointer", "--check", "--file", "p.txt"], b"");
    assert_eq!(
        out.status.code(),
        Some(1),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn pointer_check_strict_exits_two_for_noncanonical() {
    let repo = fresh_repo();
    // Missing trailing newline parses but isn't byte-canonical.
    let mut p = pointer_text(HELLO_OID, HELLO_LEN);
    assert_eq!(p.last(), Some(&b'\n'));
    p.pop(); // strip trailing newline
    std::fs::write(repo.path().join("p.txt"), &p).unwrap();
    let out = run_in(
        repo.path(),
        &["pointer", "--check", "--strict", "--file", "p.txt"],
        b"",
    );
    assert_eq!(
        out.status.code(),
        Some(2),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn pointer_file_emits_canonical_pointer_for_a_blob() {
    let repo = fresh_repo();
    std::fs::write(repo.path().join("data.bin"), b"hello world\n").unwrap();
    let out = run_in(repo.path(), &["pointer", "--file", "data.bin"], b"");
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    let expected = pointer_text(HELLO_OID, HELLO_LEN);
    let expected_str = String::from_utf8_lossy(&expected);
    assert_eq!(stdout, expected_str, "got: {stdout:?}");
    // The "Git LFS pointer for ..." banner goes to stderr.
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("Git LFS pointer for data.bin"), "{stderr}");
}

#[test]
fn pointer_compare_succeeds_when_canonical_match() {
    let repo = fresh_repo();
    std::fs::write(repo.path().join("data.bin"), b"hello world\n").unwrap();
    // Pre-built canonical pointer for that exact content.
    std::fs::write(
        repo.path().join("ref.ptr"),
        pointer_text(HELLO_OID, HELLO_LEN),
    )
    .unwrap();

    let out = run_in(
        repo.path(),
        &["pointer", "--file", "data.bin", "--pointer", "ref.ptr"],
        b"",
    );
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(!stderr.contains("Pointers do not match"), "{stderr}");
}

#[test]
fn pointer_compare_fails_on_mismatch() {
    let repo = fresh_repo();
    std::fs::write(repo.path().join("data.bin"), b"hello world\n").unwrap();
    // Pointer for a *different* OID — should mismatch.
    let other_oid = "0000000000000000000000000000000000000000000000000000000000000001";
    std::fs::write(
        repo.path().join("ref.ptr"),
        pointer_text(other_oid, HELLO_LEN),
    )
    .unwrap();

    let out = run_in(
        repo.path(),
        &["pointer", "--file", "data.bin", "--pointer", "ref.ptr"],
        b"",
    );
    assert_eq!(out.status.code(), Some(1), "expected mismatch exit");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("Pointers do not match"), "{stderr}");
}

#[test]
fn pointer_stdin_mode_parses_pointer_from_stdin() {
    let repo = fresh_repo();
    let p = pointer_text(HELLO_OID, HELLO_LEN);
    let out = run_in(repo.path(), &["pointer", "--stdin"], &p);
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("Pointer from STDIN"), "{stderr}");
    // The echoed pointer text appears in stderr.
    assert!(stderr.contains(HELLO_OID), "{stderr}");
}

#[test]
fn pointer_no_args_says_nothing_to_do() {
    let repo = fresh_repo();
    let out = run_in(repo.path(), &["pointer"], b"");
    assert_eq!(out.status.code(), Some(1));
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("Nothing to do"), "{stderr}");
}

// ---------- lock / locks / unlock ----------------------------------------
//
// All three speak the locking JSON API; we wiremock the server side and
// assert on what the binary prints + which endpoints it hits. Each test
// uses `lfs.url` pointed at the mock so the endpoint resolver doesn't
// need a real remote.

/// Create a fresh repo + configure `lfs.url` to point at the mock.
async fn lock_test_repo(server_uri: &str) -> TempDir {
    let repo = fresh_repo_with_identity();
    let status = Command::new("git")
        .arg("-C")
        .arg(repo.path())
        .args(["config", "--local", "lfs.url", server_uri])
        .status()
        .unwrap();
    assert!(status.success());
    repo
}

/// Stage and commit `rel_path` in `repo`. Used by lock/unlock tests so
/// our uncommitted-changes guard doesn't block path-based unlock paths.
fn commit_path(repo: &Path, rel_path: &str) {
    let add = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(["add", "--", rel_path])
        .status()
        .unwrap();
    assert!(add.success(), "git add {rel_path} failed");
    let commit = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(["commit", "-q", "-m", "test"])
        .status()
        .unwrap();
    assert!(commit.success(), "git commit failed");
}

#[tokio::test]
async fn lock_creates_lock_and_prints_locked_message() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(m_method("POST"))
        .and(m_path("/locks"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "lock": {
                "id": "lock-id-1",
                "path": "data.bin",
                "locked_at": "2026-04-25T12:00:00Z",
                "owner": { "name": "test" }
            }
        })))
        .mount(&server)
        .await;

    let repo = lock_test_repo(&server.uri()).await;
    // Need the file to exist so resolve_lock_path doesn't reject it.
    std::fs::write(repo.path().join("data.bin"), b"x").unwrap();

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["lock", "data.bin"], b""))
        .await
        .unwrap();
    assert!(
        out.status.success(),
        "lock failed: {}",
        String::from_utf8_lossy(&out.stderr),
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    // Upstream's `t-lock.sh` greps for "Locked <path>" and extracts
    // the id from the trailing parens (`Locked data.bin (lock-id-1)`).
    assert_eq!(stdout.trim_end(), "Locked data.bin (lock-id-1)");
}

#[tokio::test]
async fn lock_conflict_surfaces_existing_owner() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(m_method("POST"))
        .and(m_path("/locks"))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "lock": {
                "id": "existing",
                "path": "data.bin",
                "locked_at": "2026-04-25T12:00:00Z",
                "owner": { "name": "alice" }
            },
            "message": "already created lock"
        })))
        .mount(&server)
        .await;

    let repo = lock_test_repo(&server.uri()).await;
    std::fs::write(repo.path().join("data.bin"), b"x").unwrap();

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["lock", "data.bin"], b""))
        .await
        .unwrap();
    // Conflict makes the command fail.
    assert!(!out.status.success(), "expected conflict to fail");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("already created lock"), "{stderr}");
    assert!(
        stderr.contains("alice"),
        "should name conflict owner: {stderr}"
    );
}

#[tokio::test]
async fn lock_json_emits_array_of_locks() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(m_method("POST"))
        .and(m_path("/locks"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "lock": {
                "id": "json-lock",
                "path": "x.bin",
                "locked_at": "2026-04-25T12:00:00Z",
                "owner": { "name": "test" }
            }
        })))
        .mount(&server)
        .await;

    let repo = lock_test_repo(&server.uri()).await;
    std::fs::write(repo.path().join("x.bin"), b"x").unwrap();

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["lock", "x.bin", "--json"], b""))
        .await
        .unwrap();
    assert!(out.status.success());
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("valid JSON");
    let arr = v.as_array().expect("array");
    assert_eq!(arr.len(), 1);
    assert_eq!(arr[0]["id"], "json-lock");
    assert_eq!(arr[0]["path"], "x.bin");
}

#[tokio::test]
async fn locks_lists_and_paginates_via_cursor() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;

    // Page 1: returns one lock + a next cursor.
    Mock::given(m_method("GET"))
        .and(m_path("/locks"))
        .and(query_param_absent("cursor"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "locks": [
                { "id": "id-a", "path": "a.bin", "locked_at": "2026-04-25T12:00:00Z",
                  "owner": { "name": "alice" } }
            ],
            "next_cursor": "page2"
        })))
        .mount(&server)
        .await;

    // Page 2: returns the second lock + no next cursor.
    Mock::given(m_method("GET"))
        .and(m_path("/locks"))
        .and(query_param("cursor", "page2"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "locks": [
                { "id": "id-b", "path": "b.bin", "locked_at": "2026-04-25T12:00:00Z",
                  "owner": { "name": "bob" } }
            ]
        })))
        .mount(&server)
        .await;

    let repo = lock_test_repo(&server.uri()).await;
    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["locks"], b""))
        .await
        .unwrap();
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("a.bin"), "page 1 missing: {stdout}");
    assert!(stdout.contains("b.bin"), "page 2 missing: {stdout}");
    assert!(stdout.contains("ID:id-a"), "{stdout}");
    assert!(stdout.contains("ID:id-b"), "{stdout}");
}

/// `wiremock` does not provide a built-in matcher for "query param absent",
/// so we build one. Used by the pagination test to ensure page 1 is the
/// request without a `cursor` parameter.
fn query_param_absent(name: &'static str) -> impl wiremock::Match {
    struct Absent(&'static str);
    impl wiremock::Match for Absent {
        fn matches(&self, req: &wiremock::Request) -> bool {
            !req.url.query_pairs().any(|(k, _)| k == self.0)
        }
    }
    Absent(name)
}

#[tokio::test]
async fn locks_verify_prefixes_owned_with_capital_o() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(m_method("POST"))
        .and(m_path("/locks/verify"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "ours": [
                { "id": "mine", "path": "mine.bin", "locked_at": "2026-04-25T12:00:00Z",
                  "owner": { "name": "me" } }
            ],
            "theirs": [
                { "id": "theirs", "path": "their.bin", "locked_at": "2026-04-25T12:00:00Z",
                  "owner": { "name": "them" } }
            ]
        })))
        .mount(&server)
        .await;

    let repo = lock_test_repo(&server.uri()).await;
    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["locks", "--verify"], b""))
        .await
        .unwrap();
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    // Owned line starts with "O ", others with two spaces.
    let mine_line = stdout
        .lines()
        .find(|l| l.contains("mine.bin"))
        .expect("mine line");
    let their_line = stdout
        .lines()
        .find(|l| l.contains("their.bin"))
        .expect("their line");
    assert!(
        mine_line.starts_with("O "),
        "expected `O ` prefix on owned: {mine_line:?}"
    );
    assert!(
        their_line.starts_with("  "),
        "expected `  ` prefix on others: {their_line:?}"
    );
}

#[tokio::test]
async fn unlock_by_id_calls_delete_and_prints_message() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(m_method("POST"))
        .and(m_path("/locks/abc123/unlock"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "lock": {
                "id": "abc123",
                "path": "data.bin",
                "locked_at": "2026-04-25T12:00:00Z",
                "owner": { "name": "test" }
            }
        })))
        .mount(&server)
        .await;

    let repo = lock_test_repo(&server.uri()).await;
    let path = repo.path().to_owned();
    let out =
        tokio::task::spawn_blocking(move || run_in(&path, &["unlock", "--id", "abc123"], b""))
            .await
            .unwrap();
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("Unlocked Lock abc123"), "{stdout}");
}

#[tokio::test]
async fn unlock_by_path_looks_up_id_then_deletes() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    // Path → id lookup.
    Mock::given(m_method("GET"))
        .and(m_path("/locks"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "locks": [
                { "id": "by-path-id", "path": "data.bin",
                  "locked_at": "2026-04-25T12:00:00Z", "owner": { "name": "test" } }
            ]
        })))
        .mount(&server)
        .await;
    Mock::given(m_method("POST"))
        .and(m_path("/locks/by-path-id/unlock"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "lock": {
                "id": "by-path-id", "path": "data.bin",
                "locked_at": "2026-04-25T12:00:00Z", "owner": { "name": "test" }
            }
        })))
        .mount(&server)
        .await;

    let repo = lock_test_repo(&server.uri()).await;
    // Commit the file so unlock's uncommitted-changes guard doesn't
    // block the path-based flow before it reaches the API.
    std::fs::write(repo.path().join("data.bin"), b"x").unwrap();
    commit_path(repo.path(), "data.bin");

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["unlock", "data.bin"], b""))
        .await
        .unwrap();
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("Unlocked data.bin"), "{stdout}");
}

#[tokio::test]
async fn unlock_by_path_when_not_locked_fails() {
    use serde_json::json;
    use wiremock::matchers::{method as m_method, path as m_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    // List returns no matches for the path.
    Mock::given(m_method("GET"))
        .and(m_path("/locks"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"locks": []})))
        .mount(&server)
        .await;

    let repo = lock_test_repo(&server.uri()).await;
    std::fs::write(repo.path().join("data.bin"), b"x").unwrap();
    commit_path(repo.path(), "data.bin");

    let path = repo.path().to_owned();
    let out = tokio::task::spawn_blocking(move || run_in(&path, &["unlock", "data.bin"], b""))
        .await
        .unwrap();
    assert!(
        !out.status.success(),
        "expected failure when path not locked"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("not locked"), "{stderr}");
}

#[test]
fn unlock_requires_either_id_or_path() {
    let repo = fresh_repo_with_identity();
    let out = run_in(repo.path(), &["unlock"], b"");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("--id or a set of paths"), "{stderr}");
}