jj-cli 0.41.0

Jujutsu - an experimental version control system
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
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
// Copyright 2022 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::borrow::Cow;
use std::cell::OnceCell;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::env;
use std::ffi::OsString;
use std::fmt;
use std::fmt::Debug;
use std::io;
use std::io::Write as _;
use std::mem;
use std::path::Path;
use std::path::PathBuf;
use std::pin::Pin;
use std::rc::Rc;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::LazyLock;
use std::time::SystemTime;

use bstr::ByteVec as _;
use chrono::TimeZone as _;
use clap::ArgAction;
use clap::ArgMatches;
use clap::Command;
use clap::FromArgMatches as _;
use clap::builder::MapValueParser;
use clap::builder::NonEmptyStringValueParser;
use clap::builder::TypedValueParser as _;
use clap::builder::ValueParserFactory;
use clap::error::ContextKind;
use clap::error::ContextValue;
use clap_complete::ArgValueCandidates;
use clap_complete::ArgValueCompleter;
use futures::TryStreamExt as _;
use futures::future::try_join_all;
use indexmap::IndexMap;
use indexmap::IndexSet;
use indoc::indoc;
use indoc::writedoc;
use itertools::Itertools as _;
use jj_lib::backend::BackendResult;
use jj_lib::backend::ChangeId;
use jj_lib::backend::CommitId;
use jj_lib::backend::TreeValue;
use jj_lib::commit::Commit;
use jj_lib::config::ConfigGetError;
use jj_lib::config::ConfigGetResultExt as _;
use jj_lib::config::ConfigLayer;
use jj_lib::config::ConfigMigrationRule;
use jj_lib::config::ConfigNamePathBuf;
use jj_lib::config::ConfigSource;
use jj_lib::config::ConfigValue;
use jj_lib::config::StackedConfig;
use jj_lib::conflicts::ConflictMarkerStyle;
use jj_lib::fileset;
use jj_lib::fileset::FilesetAliasesMap;
use jj_lib::fileset::FilesetDiagnostics;
use jj_lib::fileset::FilesetExpression;
use jj_lib::fileset::FilesetParseContext;
use jj_lib::gitignore::GitIgnoreError;
use jj_lib::gitignore::GitIgnoreFile;
use jj_lib::id_prefix::IdPrefixContext;
use jj_lib::lock::FileLock;
use jj_lib::matchers::Matcher;
use jj_lib::matchers::NothingMatcher;
use jj_lib::merge::Diff;
use jj_lib::merge::MergedTreeValue;
use jj_lib::merged_tree::MergedTree;
use jj_lib::object_id::ObjectId as _;
use jj_lib::op_heads_store;
use jj_lib::op_store::OpStoreError;
use jj_lib::op_store::OperationId;
use jj_lib::op_store::RefTarget;
use jj_lib::op_walk;
use jj_lib::op_walk::OpsetEvaluationError;
use jj_lib::operation::Operation;
use jj_lib::ref_name::RefName;
use jj_lib::ref_name::RefNameBuf;
use jj_lib::ref_name::RemoteName;
use jj_lib::ref_name::RemoteRefSymbol;
use jj_lib::ref_name::WorkspaceName;
use jj_lib::ref_name::WorkspaceNameBuf;
use jj_lib::repo::CheckOutCommitError;
use jj_lib::repo::EditCommitError;
use jj_lib::repo::MutableRepo;
use jj_lib::repo::ReadonlyRepo;
use jj_lib::repo::Repo;
use jj_lib::repo::RepoLoader;
use jj_lib::repo::StoreFactories;
use jj_lib::repo::StoreLoadError;
use jj_lib::repo::merge_factories_map;
use jj_lib::repo_path::RepoPath;
use jj_lib::repo_path::RepoPathBuf;
use jj_lib::repo_path::RepoPathUiConverter;
use jj_lib::repo_path::UiPathParseError;
use jj_lib::revset;
use jj_lib::revset::ResolvedRevsetExpression;
use jj_lib::revset::RevsetAliasesMap;
use jj_lib::revset::RevsetDiagnostics;
use jj_lib::revset::RevsetExpression;
use jj_lib::revset::RevsetExtensions;
use jj_lib::revset::RevsetFilterPredicate;
use jj_lib::revset::RevsetFunction;
use jj_lib::revset::RevsetParseContext;
use jj_lib::revset::RevsetStreamExt as _;
use jj_lib::revset::RevsetWorkspaceContext;
use jj_lib::revset::SymbolResolverExtension;
use jj_lib::revset::UserRevsetExpression;
use jj_lib::rewrite::restore_tree;
use jj_lib::settings::HumanByteSize;
use jj_lib::settings::UserSettings;
use jj_lib::store::Store;
use jj_lib::str_util::StringExpression;
use jj_lib::str_util::StringMatcher;
use jj_lib::str_util::StringPattern;
use jj_lib::transaction::Transaction;
use jj_lib::transaction::TransactionCommitError;
use jj_lib::working_copy;
use jj_lib::working_copy::CheckoutStats;
use jj_lib::working_copy::LockedWorkingCopy;
use jj_lib::working_copy::SnapshotOptions;
use jj_lib::working_copy::SnapshotStats;
use jj_lib::working_copy::UntrackedReason;
use jj_lib::working_copy::WorkingCopy;
use jj_lib::working_copy::WorkingCopyFactory;
use jj_lib::working_copy::WorkingCopyFreshness;
use jj_lib::workspace::DefaultWorkspaceLoaderFactory;
use jj_lib::workspace::LockedWorkspace;
use jj_lib::workspace::WorkingCopyFactories;
use jj_lib::workspace::Workspace;
use jj_lib::workspace::WorkspaceLoadError;
use jj_lib::workspace::WorkspaceLoader;
use jj_lib::workspace::WorkspaceLoaderFactory;
use jj_lib::workspace::default_working_copy_factories;
use jj_lib::workspace::get_working_copy_factory;
use pollster::FutureExt as _;
use tracing::instrument;
use tracing_chrome::ChromeLayerBuilder;
use tracing_subscriber::prelude::*;

use crate::command_error::CommandError;
use crate::command_error::cli_error;
use crate::command_error::config_error_with_message;
use crate::command_error::handle_command_result;
use crate::command_error::internal_error;
use crate::command_error::internal_error_with_message;
use crate::command_error::print_error_sources;
use crate::command_error::print_parse_diagnostics;
use crate::command_error::user_error;
use crate::command_error::user_error_with_message;
use crate::commit_templater::CommitTemplateLanguage;
use crate::commit_templater::CommitTemplateLanguageExtension;
use crate::complete;
use crate::config::ConfigArgKind;
use crate::config::ConfigEnv;
use crate::config::RawConfig;
use crate::config::config_from_environment;
use crate::config::load_aliases_map;
use crate::config::parse_config_args;
use crate::description_util::TextEditor;
use crate::diff_util;
use crate::diff_util::DiffFormat;
use crate::diff_util::DiffFormatArgs;
use crate::diff_util::DiffRenderer;
use crate::formatter::FormatRecorder;
use crate::formatter::Formatter;
use crate::formatter::FormatterExt as _;
use crate::merge_tools::DiffEditor;
use crate::merge_tools::MergeEditor;
use crate::merge_tools::MergeToolConfigError;
use crate::operation_templater::OperationTemplateLanguage;
use crate::operation_templater::OperationTemplateLanguageExtension;
use crate::revset_util;
use crate::revset_util::RevsetExpressionEvaluator;
use crate::revset_util::parse_union_name_patterns;
use crate::template_builder;
use crate::template_builder::TemplateLanguage;
use crate::template_parser::TemplateAliasesMap;
use crate::template_parser::TemplateDiagnostics;
use crate::templater::TemplateRenderer;
use crate::templater::WrapTemplateProperty;
use crate::text_util;
use crate::ui::ColorChoice;
use crate::ui::Ui;

const SHORT_CHANGE_ID_TEMPLATE_TEXT: &str = "format_short_change_id_with_change_offset(self)";

#[derive(Clone)]
struct ChromeTracingFlushGuard {
    _inner: Option<Rc<tracing_chrome::FlushGuard>>,
}

impl Debug for ChromeTracingFlushGuard {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let Self { _inner } = self;
        f.debug_struct("ChromeTracingFlushGuard")
            .finish_non_exhaustive()
    }
}

/// Handle to initialize or change tracing subscription.
#[derive(Clone, Debug)]
pub struct TracingSubscription {
    reload_log_filter: tracing_subscriber::reload::Handle<
        tracing_subscriber::EnvFilter,
        tracing_subscriber::Registry,
    >,
    _chrome_tracing_flush_guard: ChromeTracingFlushGuard,
}

impl TracingSubscription {
    const ENV_VAR_NAME: &str = "JJ_LOG";

    /// Initializes tracing with the default configuration. This should be
    /// called as early as possible.
    pub fn init() -> Self {
        let filter = tracing_subscriber::EnvFilter::builder()
            .with_default_directive(tracing::metadata::LevelFilter::ERROR.into())
            .with_env_var(Self::ENV_VAR_NAME)
            .from_env_lossy();
        let (filter, reload_log_filter) = tracing_subscriber::reload::Layer::new(filter);

        let (chrome_tracing_layer, chrome_tracing_flush_guard) = match std::env::var("JJ_TRACE") {
            Ok(filename) => {
                let filename = if filename.is_empty() {
                    format!(
                        "jj-trace-{}.json",
                        SystemTime::now()
                            .duration_since(SystemTime::UNIX_EPOCH)
                            .unwrap()
                            .as_secs(),
                    )
                } else {
                    filename
                };
                let include_args = std::env::var("JJ_TRACE_INCLUDE_ARGS").is_ok();
                let (layer, guard) = ChromeLayerBuilder::new()
                    .file(filename)
                    .include_args(include_args)
                    .build();
                (
                    Some(layer),
                    ChromeTracingFlushGuard {
                        _inner: Some(Rc::new(guard)),
                    },
                )
            }
            Err(_) => (None, ChromeTracingFlushGuard { _inner: None }),
        };

        tracing_subscriber::registry()
            .with(
                tracing_subscriber::fmt::Layer::default()
                    .with_writer(std::io::stderr)
                    .with_filter(filter),
            )
            .with(chrome_tracing_layer)
            .init();
        Self {
            reload_log_filter,
            _chrome_tracing_flush_guard: chrome_tracing_flush_guard,
        }
    }

    pub fn enable_debug_logging(&self) -> Result<(), CommandError> {
        self.reload_log_filter
            .modify(|filter| {
                // The default is INFO.
                // jj-lib and jj-cli are whitelisted for DEBUG logging.
                // This ensures that other crates' logging doesn't show up by default.
                *filter = tracing_subscriber::EnvFilter::builder()
                    .with_default_directive(tracing::metadata::LevelFilter::INFO.into())
                    .with_env_var(Self::ENV_VAR_NAME)
                    .from_env_lossy()
                    .add_directive("jj_lib=debug".parse().unwrap())
                    .add_directive("jj_cli=debug".parse().unwrap());
            })
            .map_err(|err| internal_error_with_message("failed to enable debug logging", err))?;
        tracing::info!("debug logging enabled");
        Ok(())
    }
}

#[derive(Clone)]
pub struct CommandHelper {
    data: Rc<CommandHelperData>,
}

struct CommandHelperData {
    app: Command,
    cwd: PathBuf,
    string_args: Vec<String>,
    matches: ArgMatches,
    global_args: GlobalArgs,
    config_env: ConfigEnv,
    config_migrations: Vec<ConfigMigrationRule>,
    raw_config: RawConfig,
    settings: UserSettings,
    revset_extensions: Arc<RevsetExtensions>,
    commit_template_extensions: Vec<Arc<dyn CommitTemplateLanguageExtension>>,
    operation_template_extensions: Vec<Arc<dyn OperationTemplateLanguageExtension>>,
    maybe_workspace_loader: Result<Box<dyn WorkspaceLoader>, CommandError>,
    store_factories: StoreFactories,
    working_copy_factories: WorkingCopyFactories,
    workspace_loader_factory: Box<dyn WorkspaceLoaderFactory>,
}

impl CommandHelper {
    pub fn app(&self) -> &Command {
        &self.data.app
    }

    /// Canonical form of the current working directory path.
    ///
    /// A loaded `Workspace::workspace_root()` also returns a canonical path, so
    /// relative paths can be easily computed from these paths.
    pub fn cwd(&self) -> &Path {
        &self.data.cwd
    }

    pub fn string_args(&self) -> &Vec<String> {
        &self.data.string_args
    }

    pub fn matches(&self) -> &ArgMatches {
        &self.data.matches
    }

    pub fn global_args(&self) -> &GlobalArgs {
        &self.data.global_args
    }

    pub fn config_env(&self) -> &ConfigEnv {
        &self.data.config_env
    }

    /// Unprocessed (or unresolved) configuration data.
    ///
    /// Use this only if the unmodified config data is needed. For example, `jj
    /// config set` should use this to write updated data back to file.
    pub fn raw_config(&self) -> &RawConfig {
        &self.data.raw_config
    }

    /// Settings for the current command and workspace.
    ///
    /// This may be different from the settings for new workspace created by
    /// e.g. `jj git init`. There may be conditional variables and repo config
    /// loaded for the cwd workspace.
    pub fn settings(&self) -> &UserSettings {
        &self.data.settings
    }

    /// Resolves configuration for new workspace located at the specified path.
    pub fn settings_for_new_workspace(
        &self,
        ui: &Ui,
        workspace_root: &Path,
    ) -> Result<(UserSettings, ConfigEnv), CommandError> {
        let mut config_env = self.data.config_env.clone();
        let mut raw_config = self.data.raw_config.clone();
        let repo_path = workspace_root.join(".jj").join("repo");
        config_env.reset_repo_path(&repo_path);
        config_env.reload_repo_config(ui, &mut raw_config)?;
        config_env.reset_workspace_path(workspace_root);
        config_env.reload_workspace_config(ui, &mut raw_config)?;
        let mut config = config_env.resolve_config(&raw_config)?;
        // No migration messages here, which would usually be emitted before.
        jj_lib::config::migrate(&mut config, &self.data.config_migrations)?;
        Ok((self.data.settings.with_new_config(config)?, config_env))
    }

    /// Loads text editor from the settings.
    pub fn text_editor(&self) -> Result<TextEditor, ConfigGetError> {
        TextEditor::from_settings(self.settings())
    }

    pub fn revset_extensions(&self) -> &Arc<RevsetExtensions> {
        &self.data.revset_extensions
    }

    /// Parses template of the given language into evaluation tree.
    ///
    /// This function also loads template aliases from the settings. Use
    /// `WorkspaceCommandHelper::parse_template()` if you've already
    /// instantiated the workspace helper.
    pub fn parse_template<'a, C, L>(
        &self,
        ui: &Ui,
        language: &L,
        template_text: &str,
    ) -> Result<TemplateRenderer<'a, C>, CommandError>
    where
        C: Clone + 'a,
        L: TemplateLanguage<'a> + ?Sized,
        L::Property: WrapTemplateProperty<'a, C>,
    {
        let mut diagnostics = TemplateDiagnostics::new();
        let aliases = load_template_aliases(ui, self.settings().config())?;
        let template =
            template_builder::parse(language, &mut diagnostics, template_text, &aliases)?;
        print_parse_diagnostics(ui, "In template expression", &diagnostics)?;
        Ok(template)
    }

    pub fn should_commit_transaction(&self) -> bool {
        !self.global_args().no_integrate_operation
    }

    async fn maybe_commit_transaction(
        &self,
        tx: Transaction,
        description: impl Into<String>,
    ) -> Result<Arc<ReadonlyRepo>, TransactionCommitError> {
        let unpublished_op = tx.write(description).await?;
        if self.should_commit_transaction() {
            unpublished_op.publish().await
        } else {
            Ok(unpublished_op.leave_unpublished())
        }
    }

    pub fn workspace_loader(&self) -> Result<&dyn WorkspaceLoader, CommandError> {
        self.data
            .maybe_workspace_loader
            .as_deref()
            .map_err(Clone::clone)
    }

    fn new_workspace_loader_at(
        &self,
        workspace_root: &Path,
    ) -> Result<Box<dyn WorkspaceLoader>, CommandError> {
        self.data
            .workspace_loader_factory
            .create(workspace_root)
            .map_err(|err| map_workspace_load_error(err, None))
    }

    /// Loads workspace and repo, then snapshots the working copy if allowed.
    #[instrument(skip(self, ui))]
    pub fn workspace_helper(&self, ui: &Ui) -> Result<WorkspaceCommandHelper, CommandError> {
        let (workspace_command, stats) = self.workspace_helper_with_stats(ui)?;
        print_snapshot_stats(ui, &stats, workspace_command.env().path_converter())?;
        Ok(workspace_command)
    }

    /// Loads workspace and repo, then snapshots the working copy if allowed and
    /// returns the SnapshotStats.
    ///
    /// Note that unless you have a good reason not to do so, you should always
    /// call [`print_snapshot_stats`] with the [`SnapshotStats`] returned by
    /// this function to present possible untracked files to the user.
    #[instrument(skip(self, ui))]
    pub fn workspace_helper_with_stats(
        &self,
        ui: &Ui,
    ) -> Result<(WorkspaceCommandHelper, SnapshotStats), CommandError> {
        let mut workspace_command = self.workspace_helper_no_snapshot(ui)?;

        let (workspace_command, stats) = match workspace_command.maybe_snapshot_impl(ui).block_on()
        {
            Ok(stats) => (workspace_command, stats),
            Err(SnapshotWorkingCopyError::Command(err)) => return Err(err),
            Err(SnapshotWorkingCopyError::StaleWorkingCopy(err)) => {
                let auto_update_stale = self.settings().get_bool("snapshot.auto-update-stale")?;
                if !auto_update_stale {
                    return Err(err);
                }

                // We detected the working copy was stale and the client is configured to
                // auto-update-stale, so let's do that now. We need to do it up here, not at a
                // lower level (e.g. inside snapshot_working_copy()) to avoid recursive locking
                // of the working copy.
                self.recover_stale_working_copy(ui).block_on()?
            }
        };

        Ok((workspace_command, stats))
    }

    /// Loads workspace and repo, but never snapshots the working copy. Most
    /// commands should use `workspace_helper()` instead.
    #[instrument(skip(self, ui))]
    pub fn workspace_helper_no_snapshot(
        &self,
        ui: &Ui,
    ) -> Result<WorkspaceCommandHelper, CommandError> {
        let workspace = self.load_workspace()?;
        let op_head =
            self.resolve_operation(ui, workspace.repo_loader(), workspace.workspace_name())?;
        let repo = workspace.repo_loader().load_at(&op_head).block_on()?;
        let mut env = self.workspace_environment(ui, &workspace)?;
        if let Err(err) =
            revset_util::try_resolve_trunk_alias(repo.as_ref(), &env.revset_parse_context())
        {
            // The fallback can be builtin_trunk() if we're willing to support
            // inferred trunk forever. (#7990)
            let fallback = "root()";
            writeln!(
                ui.warning_default(),
                "Failed to resolve `revset-aliases.trunk()`: {err}"
            )?;
            writeln!(
                ui.warning_no_heading(),
                "The `trunk()` alias is temporarily set to `{fallback}`."
            )?;
            writeln!(
                ui.hint_default(),
                "Use `jj config edit --repo` to adjust the `trunk()` alias."
            )?;
            env.revset_aliases_map
                .insert("trunk()", fallback)
                .expect("valid syntax");
            env.reload_revset_expressions(ui)?;
        }
        WorkspaceCommandHelper::new(ui, workspace, repo, env, self.is_at_head_operation())
    }

    pub fn get_working_copy_factory(&self) -> Result<&dyn WorkingCopyFactory, CommandError> {
        let loader = self.workspace_loader()?;

        // We convert StoreLoadError -> WorkspaceLoadError -> CommandError
        let factory: Result<_, WorkspaceLoadError> =
            get_working_copy_factory(loader, &self.data.working_copy_factories)
                .map_err(|e| e.into());
        let factory = factory.map_err(|err| {
            map_workspace_load_error(err, self.data.global_args.repository.as_deref())
        })?;
        Ok(factory)
    }

    /// Loads workspace for the current command.
    #[instrument(skip_all)]
    pub fn load_workspace(&self) -> Result<Workspace, CommandError> {
        let loader = self.workspace_loader()?;
        loader
            .load(
                &self.data.settings,
                &self.data.store_factories,
                &self.data.working_copy_factories,
            )
            .map_err(|err| {
                map_workspace_load_error(err, self.data.global_args.repository.as_deref())
            })
    }

    /// Loads workspace located at the specified path.
    #[instrument(skip(self, settings))]
    pub fn load_workspace_at(
        &self,
        workspace_root: &Path,
        settings: &UserSettings,
    ) -> Result<Workspace, CommandError> {
        let loader = self.new_workspace_loader_at(workspace_root)?;
        loader
            .load(
                settings,
                &self.data.store_factories,
                &self.data.working_copy_factories,
            )
            .map_err(|err| map_workspace_load_error(err, None))
    }

    /// Note that unless you have a good reason not to do so, you should always
    /// call [`print_snapshot_stats`] with the [`SnapshotStats`] returned by
    /// this function to present possible untracked files to the user.
    pub async fn recover_stale_working_copy(
        &self,
        ui: &Ui,
    ) -> Result<(WorkspaceCommandHelper, SnapshotStats), CommandError> {
        let workspace = self.load_workspace()?;
        let op_id = workspace.working_copy().operation_id();

        match workspace.repo_loader().load_operation(op_id).await {
            Ok(op) => {
                let repo = workspace.repo_loader().load_at(&op).await?;
                let mut workspace_command = self.for_workable_repo(ui, workspace, repo)?;
                workspace_command.check_working_copy_writable()?;

                // Snapshot the current working copy on top of the last known working-copy
                // operation, then merge the divergent operations. The wc_commit_id of the
                // merged repo wouldn't change because the old one wins, but it's probably
                // fine if we picked the new wc_commit_id.
                let stale_stats = workspace_command
                    .snapshot_working_copy(ui)
                    .await
                    .map_err(|err| err.into_command_error())?;

                let wc_commit_id = workspace_command.get_wc_commit_id().unwrap();
                let repo = workspace_command.repo().clone();
                let stale_wc_commit = repo.store().get_commit_async(wc_commit_id).await?;

                let mut workspace_command = self.workspace_helper_no_snapshot(ui)?;

                let repo = workspace_command.repo().clone();
                let (mut locked_ws, desired_wc_commit) = workspace_command
                    .unchecked_start_working_copy_mutation()
                    .await?;
                match WorkingCopyFreshness::check_stale(
                    locked_ws.locked_wc(),
                    &desired_wc_commit,
                    &repo,
                )
                .await?
                {
                    WorkingCopyFreshness::Fresh | WorkingCopyFreshness::Updated(_) => {
                        drop(locked_ws);
                        writeln!(
                            ui.status(),
                            "Attempted recovery, but the working copy is not stale"
                        )?;
                    }
                    WorkingCopyFreshness::WorkingCopyStale
                    | WorkingCopyFreshness::SiblingOperation => {
                        let stats = update_stale_working_copy(
                            locked_ws,
                            repo.op_id().clone(),
                            &stale_wc_commit,
                            &desired_wc_commit,
                        )
                        .await?;
                        workspace_command.print_updated_working_copy_stats(
                            ui,
                            Some(&stale_wc_commit),
                            &desired_wc_commit,
                            &stats,
                        )?;
                        writeln!(
                            ui.status(),
                            "Updated working copy to fresh commit {}",
                            short_commit_hash(desired_wc_commit.id())
                        )?;
                    }
                }

                // There may be Git refs to import, so snapshot again. Git HEAD
                // will also be imported if it was updated after the working
                // copy became stale. The result wouldn't be ideal, but there
                // should be no data loss at least.
                let fresh_stats = workspace_command
                    .maybe_snapshot_impl(ui)
                    .await
                    .map_err(|err| err.into_command_error())?;
                let merged_stats = {
                    let SnapshotStats {
                        mut untracked_paths,
                    } = stale_stats;
                    untracked_paths.extend(fresh_stats.untracked_paths);
                    SnapshotStats { untracked_paths }
                };
                Ok((workspace_command, merged_stats))
            }
            Err(e @ OpStoreError::ObjectNotFound { .. }) => {
                writeln!(
                    ui.status(),
                    "Failed to read working copy's current operation; attempting recovery. Error \
                     message from read attempt: {e}"
                )?;

                let mut workspace_command = self.workspace_helper_no_snapshot(ui)?;
                let stats = workspace_command
                    .create_and_check_out_recovery_commit(ui)
                    .await?;
                Ok((workspace_command, stats))
            }
            Err(e) => Err(e.into()),
        }
    }

    /// Loads command environment for the given `workspace`.
    pub fn workspace_environment(
        &self,
        ui: &Ui,
        workspace: &Workspace,
    ) -> Result<WorkspaceCommandEnvironment, CommandError> {
        WorkspaceCommandEnvironment::new(ui, self, workspace)
    }

    /// Returns true if the working copy to be loaded is writable, and therefore
    /// should usually be snapshotted.
    pub fn is_working_copy_writable(&self) -> bool {
        self.is_at_head_operation() && !self.data.global_args.ignore_working_copy
    }

    /// Returns true if the current operation is considered to be the head.
    pub fn is_at_head_operation(&self) -> bool {
        // TODO: should we accept --at-op=<head_id> as the head op? or should we
        // make --at-op=@ imply --ignore-working-copy (i.e. not at the head.)
        matches!(
            self.data.global_args.at_operation.as_deref(),
            None | Some("@")
        )
    }

    /// Resolves the current operation from the command-line argument.
    ///
    /// If no `--at-operation` is specified, the head operations will be
    /// loaded. If there are multiple heads, they'll be merged.
    #[instrument(skip_all)]
    pub fn resolve_operation(
        &self,
        ui: &Ui,
        repo_loader: &RepoLoader,
        workspace_name: &WorkspaceName,
    ) -> Result<Operation, CommandError> {
        if let Some(op_str) = &self.data.global_args.at_operation {
            Ok(op_walk::resolve_op_for_load(repo_loader, op_str).block_on()?)
        } else {
            op_heads_store::resolve_op_heads(
                repo_loader.op_heads_store().as_ref(),
                repo_loader.op_store(),
                async |op_heads| {
                    writeln!(
                        ui.status(),
                        "Concurrent modification detected, resolving automatically.",
                    )?;
                    let base_repo = repo_loader.load_at(&op_heads[0]).block_on()?;
                    // TODO: It may be helpful to print each operation we're merging here
                    let mut tx =
                        start_repo_transaction(&base_repo, workspace_name, &self.data.string_args);
                    for other_op_head in op_heads.into_iter().skip(1) {
                        tx.merge_operation(other_op_head).await?;
                        let num_rebased = tx.repo_mut().rebase_descendants().await?;
                        if num_rebased > 0 {
                            writeln!(
                                ui.status(),
                                "Rebased {num_rebased} descendant commits onto commits rewritten \
                                 by other operation"
                            )?;
                        }
                    }
                    Ok(tx
                        .write("reconcile divergent operations")
                        .await?
                        .leave_unpublished()
                        .operation()
                        .clone())
                },
            )
            .block_on()
        }
    }

    /// Creates helper for the repo whose view is supposed to be in sync with
    /// the working copy. If `--ignore-working-copy` is not specified, the
    /// returned helper will attempt to update the working copy.
    #[instrument(skip_all)]
    pub fn for_workable_repo(
        &self,
        ui: &Ui,
        workspace: Workspace,
        repo: Arc<ReadonlyRepo>,
    ) -> Result<WorkspaceCommandHelper, CommandError> {
        let env = self.workspace_environment(ui, &workspace)?;
        let loaded_at_head = true;
        WorkspaceCommandHelper::new(ui, workspace, repo, env, loaded_at_head)
    }
}

/// A ReadonlyRepo along with user-config-dependent derived data. The derived
/// data is lazily loaded.
struct ReadonlyUserRepo {
    repo: Arc<ReadonlyRepo>,
    id_prefix_context: OnceCell<IdPrefixContext>,
}

impl ReadonlyUserRepo {
    fn new(repo: Arc<ReadonlyRepo>) -> Self {
        Self {
            repo,
            id_prefix_context: OnceCell::new(),
        }
    }
}

/// A advanceable bookmark to satisfy the "advance-bookmarks" feature.
///
/// This is a helper for `WorkspaceCommandTransaction`. It provides a
/// type-safe way to separate the work of checking whether a bookmark
/// can be advanced and actually advancing it. Advancing the bookmark
/// never fails, but can't be done until the new `CommitId` is
/// available. Splitting the work in this way also allows us to
/// identify eligible bookmarks without actually moving them and
/// return config errors to the user early.
pub struct AdvanceableBookmark {
    name: RefNameBuf,
    old_commit_id: CommitId,
}

/// Parses advance-bookmarks settings into matcher.
///
/// Settings are configured in the jj config.toml as lists of string matcher
/// expressions for enabled and disabled bookmarks. Example:
/// ```toml
/// [experimental-advance-branches]
/// # Enable the feature for all branches except "main".
/// enabled-branches = ["*"]
/// disabled-branches = ["main"]
/// ```
fn load_advance_bookmarks_matcher(
    ui: &Ui,
    settings: &UserSettings,
) -> Result<Option<StringMatcher>, CommandError> {
    let get_setting = |setting_key: &str| -> Result<Vec<String>, _> {
        let name = ConfigNamePathBuf::from_iter(["experimental-advance-branches", setting_key]);
        settings.get(&name)
    };
    // TODO: When we stabilize this feature, enabled/disabled patterns can be
    // combined into a single matcher expression.
    let enabled_names = get_setting("enabled-branches")?;
    let disabled_names = get_setting("disabled-branches")?;
    let enabled_expr = parse_union_name_patterns(ui, &enabled_names)?;
    let disabled_expr = parse_union_name_patterns(ui, &disabled_names)?;
    if enabled_names.is_empty() {
        Ok(None)
    } else {
        let expr = enabled_expr.intersection(disabled_expr.negated());
        Ok(Some(expr.to_matcher()))
    }
}

/// Metadata and configuration loaded for a specific workspace.
pub struct WorkspaceCommandEnvironment {
    command: CommandHelper,
    settings: UserSettings,
    fileset_aliases_map: FilesetAliasesMap,
    revset_aliases_map: RevsetAliasesMap,
    template_aliases_map: TemplateAliasesMap,
    default_ignored_remote: Option<&'static RemoteName>,
    revsets_use_glob_by_default: bool,
    path_converter: RepoPathUiConverter,
    workspace_name: WorkspaceNameBuf,
    immutable_heads_expression: Arc<UserRevsetExpression>,
    short_prefixes_expression: Option<Arc<UserRevsetExpression>>,
    conflict_marker_style: ConflictMarkerStyle,
}

impl WorkspaceCommandEnvironment {
    #[instrument(skip_all)]
    fn new(ui: &Ui, command: &CommandHelper, workspace: &Workspace) -> Result<Self, CommandError> {
        let settings = workspace.settings();
        let fileset_aliases_map = load_fileset_aliases(ui, settings.config())?;
        let revset_aliases_map = load_revset_aliases(ui, settings.config())?;
        let template_aliases_map = load_template_aliases(ui, settings.config())?;
        let default_ignored_remote = default_ignored_remote_name(workspace.repo_loader().store());
        let path_converter = RepoPathUiConverter::Fs {
            cwd: command.cwd().to_owned(),
            base: workspace.workspace_root().to_owned(),
        };
        let mut env = Self {
            command: command.clone(),
            settings: settings.clone(),
            fileset_aliases_map,
            revset_aliases_map,
            template_aliases_map,
            default_ignored_remote,
            revsets_use_glob_by_default: settings.get("ui.revsets-use-glob-by-default")?,
            path_converter,
            workspace_name: workspace.workspace_name().to_owned(),
            immutable_heads_expression: RevsetExpression::root(),
            short_prefixes_expression: None,
            conflict_marker_style: settings.get("ui.conflict-marker-style")?,
        };
        env.reload_revset_expressions(ui)?;
        Ok(env)
    }

    pub(crate) fn path_converter(&self) -> &RepoPathUiConverter {
        &self.path_converter
    }

    pub fn workspace_name(&self) -> &WorkspaceName {
        &self.workspace_name
    }

    /// Parsing context for fileset expressions specified by command arguments.
    pub(crate) fn fileset_parse_context(&self) -> FilesetParseContext<'_> {
        FilesetParseContext {
            aliases_map: &self.fileset_aliases_map,
            path_converter: &self.path_converter,
        }
    }

    /// Parsing context for fileset expressions loaded from config files.
    pub(crate) fn fileset_parse_context_for_config(&self) -> FilesetParseContext<'_> {
        // TODO: bump MSRV to 1.91.0 to leverage const PathBuf::new()
        static ROOT_PATH_CONVERTER: LazyLock<RepoPathUiConverter> =
            LazyLock::new(|| RepoPathUiConverter::Fs {
                cwd: PathBuf::new(),
                base: PathBuf::new(),
            });
        FilesetParseContext {
            aliases_map: &self.fileset_aliases_map,
            path_converter: &ROOT_PATH_CONVERTER,
        }
    }

    pub(crate) fn revset_parse_context(&self) -> RevsetParseContext<'_> {
        let workspace_context = RevsetWorkspaceContext {
            path_converter: &self.path_converter,
            workspace_name: &self.workspace_name,
        };
        let now = if let Some(timestamp) = self.settings.commit_timestamp() {
            chrono::Local
                .timestamp_millis_opt(timestamp.timestamp.0)
                .unwrap()
        } else {
            chrono::Local::now()
        };
        RevsetParseContext {
            aliases_map: &self.revset_aliases_map,
            local_variables: HashMap::new(),
            user_email: self.settings.user_email(),
            date_pattern_context: now.into(),
            default_ignored_remote: self.default_ignored_remote,
            fileset_aliases_map: &self.fileset_aliases_map,
            use_glob_by_default: self.revsets_use_glob_by_default,
            extensions: self.command.revset_extensions(),
            workspace: Some(workspace_context),
        }
    }

    /// Creates fresh new context which manages cache of short commit/change ID
    /// prefixes. New context should be created per repo view (or operation.)
    pub fn new_id_prefix_context(&self) -> IdPrefixContext {
        let context = IdPrefixContext::new(self.command.revset_extensions().clone());
        match &self.short_prefixes_expression {
            None => context,
            Some(expression) => context.disambiguate_within(expression.clone()),
        }
    }

    /// Updates parsed revset expressions.
    fn reload_revset_expressions(&mut self, ui: &Ui) -> Result<(), CommandError> {
        self.immutable_heads_expression = self.load_immutable_heads_expression(ui)?;
        self.short_prefixes_expression = self.load_short_prefixes_expression(ui)?;
        Ok(())
    }

    /// User-configured expression defining the immutable set.
    pub fn immutable_expression(&self) -> Arc<UserRevsetExpression> {
        // Negated ancestors expression `~::(<heads> | root())` is slightly
        // easier to optimize than negated union `~(::<heads> | root())`.
        self.immutable_heads_expression.ancestors()
    }

    /// User-configured expression defining the heads of the immutable set.
    pub fn immutable_heads_expression(&self) -> &Arc<UserRevsetExpression> {
        &self.immutable_heads_expression
    }

    /// User-configured conflict marker style for materializing conflicts
    pub fn conflict_marker_style(&self) -> ConflictMarkerStyle {
        self.conflict_marker_style
    }

    fn load_immutable_heads_expression(
        &self,
        ui: &Ui,
    ) -> Result<Arc<UserRevsetExpression>, CommandError> {
        let mut diagnostics = RevsetDiagnostics::new();
        let expression = revset_util::parse_immutable_heads_expression(
            &mut diagnostics,
            &self.revset_parse_context(),
        )
        .map_err(|e| config_error_with_message("Invalid `revset-aliases.immutable_heads()`", e))?;
        print_parse_diagnostics(ui, "In `revset-aliases.immutable_heads()`", &diagnostics)?;
        Ok(expression)
    }

    fn load_short_prefixes_expression(
        &self,
        ui: &Ui,
    ) -> Result<Option<Arc<UserRevsetExpression>>, CommandError> {
        let revset_string = self
            .settings
            .get_string("revsets.short-prefixes")
            .optional()?
            .map_or_else(|| self.settings.get_string("revsets.log"), Ok)?;
        if revset_string.is_empty() {
            Ok(None)
        } else {
            let mut diagnostics = RevsetDiagnostics::new();
            let expression = revset::parse(
                &mut diagnostics,
                &revset_string,
                &self.revset_parse_context(),
            )
            .map_err(|err| config_error_with_message("Invalid `revsets.short-prefixes`", err))?;
            print_parse_diagnostics(ui, "In `revsets.short-prefixes`", &diagnostics)?;
            Ok(Some(expression))
        }
    }

    /// Returns first immutable commit.
    async fn find_immutable_commit(
        &self,
        repo: &dyn Repo,
        to_rewrite_expr: &Arc<ResolvedRevsetExpression>,
    ) -> Result<Option<CommitId>, CommandError> {
        let immutable_expression = if self.command.global_args().ignore_immutable {
            UserRevsetExpression::root()
        } else {
            self.immutable_expression()
        };

        // Not using self.id_prefix_context() because the disambiguation data
        // must not be calculated and cached against arbitrary repo. It's also
        // unlikely that the immutable expression contains short hashes.
        let id_prefix_context = IdPrefixContext::new(self.command.revset_extensions().clone());
        let immutable_expr = RevsetExpressionEvaluator::new(
            repo,
            self.command.revset_extensions().clone(),
            &id_prefix_context,
            immutable_expression,
        )
        .resolve()
        .map_err(|e| config_error_with_message("Invalid `revset-aliases.immutable_heads()`", e))?;

        let mut commit_id_iter = immutable_expr
            .intersection(to_rewrite_expr)
            .evaluate(repo)?
            .stream();
        Ok(commit_id_iter.try_next().await?)
    }

    pub fn template_aliases_map(&self) -> &TemplateAliasesMap {
        &self.template_aliases_map
    }

    /// Parses template of the given language into evaluation tree.
    pub fn parse_template<'a, C, L>(
        &self,
        ui: &Ui,
        language: &L,
        template_text: &str,
    ) -> Result<TemplateRenderer<'a, C>, CommandError>
    where
        C: Clone + 'a,
        L: TemplateLanguage<'a> + ?Sized,
        L::Property: WrapTemplateProperty<'a, C>,
    {
        let mut diagnostics = TemplateDiagnostics::new();
        let template = template_builder::parse(
            language,
            &mut diagnostics,
            template_text,
            &self.template_aliases_map,
        )?;
        print_parse_diagnostics(ui, "In template expression", &diagnostics)?;
        Ok(template)
    }

    /// Creates commit template language environment for this workspace and the
    /// given `repo`.
    pub fn commit_template_language<'a>(
        &'a self,
        repo: &'a dyn Repo,
        id_prefix_context: &'a IdPrefixContext,
    ) -> CommitTemplateLanguage<'a> {
        CommitTemplateLanguage::new(
            repo,
            &self.path_converter,
            &self.workspace_name,
            self.revset_parse_context(),
            id_prefix_context,
            self.immutable_expression(),
            self.conflict_marker_style,
            &self.command.data.commit_template_extensions,
        )
    }

    pub fn operation_template_extensions(&self) -> &[Arc<dyn OperationTemplateLanguageExtension>] {
        &self.command.data.operation_template_extensions
    }
}

/// A token that holds a lock for git import/export operations in colocated
/// repositories. For non-colocated repos, this is an empty token (no actual
/// lock held). The lock is automatically released when this token is dropped.
pub struct GitImportExportLock {
    _lock: Option<FileLock>,
}

/// Provides utilities for writing a command that works on a [`Workspace`]
/// (which most commands do).
pub struct WorkspaceCommandHelper {
    workspace: Workspace,
    user_repo: ReadonlyUserRepo,
    env: WorkspaceCommandEnvironment,
    // TODO: Parsed template can be cached if it doesn't capture 'repo lifetime
    commit_summary_template_text: String,
    op_summary_template_text: String,
    may_snapshot_working_copy: bool,
    may_update_working_copy: bool,
    working_copy_shared_with_git: bool,
}

enum SnapshotWorkingCopyError {
    Command(CommandError),
    StaleWorkingCopy(CommandError),
}

impl SnapshotWorkingCopyError {
    fn into_command_error(self) -> CommandError {
        match self {
            Self::Command(err) => err,
            Self::StaleWorkingCopy(err) => err,
        }
    }
}

fn snapshot_command_error<E>(err: E) -> SnapshotWorkingCopyError
where
    E: Into<CommandError>,
{
    SnapshotWorkingCopyError::Command(err.into())
}

impl WorkspaceCommandHelper {
    #[instrument(skip_all)]
    fn new(
        ui: &Ui,
        workspace: Workspace,
        repo: Arc<ReadonlyRepo>,
        env: WorkspaceCommandEnvironment,
        loaded_at_head: bool,
    ) -> Result<Self, CommandError> {
        let settings = workspace.settings();
        let commit_summary_template_text = settings.get_string("templates.commit_summary")?;
        let op_summary_template_text = settings.get_string("templates.op_summary")?;
        let may_snapshot_working_copy =
            loaded_at_head && !env.command.global_args().ignore_working_copy;
        let may_update_working_copy =
            may_snapshot_working_copy && env.command.should_commit_transaction();
        let working_copy_shared_with_git =
            crate::git_util::is_colocated_git_workspace(&workspace, &repo);

        let helper = Self {
            workspace,
            user_repo: ReadonlyUserRepo::new(repo),
            env,
            commit_summary_template_text,
            op_summary_template_text,
            may_snapshot_working_copy,
            may_update_working_copy,
            working_copy_shared_with_git,
        };
        // Parse commit_summary template early to report error before starting
        // mutable operation.
        helper.parse_operation_template(ui, &helper.op_summary_template_text)?;
        helper.parse_commit_template(ui, &helper.commit_summary_template_text)?;
        helper.parse_commit_template(ui, SHORT_CHANGE_ID_TEMPLATE_TEXT)?;
        Ok(helper)
    }

    /// Settings for this workspace.
    pub fn settings(&self) -> &UserSettings {
        self.workspace.settings()
    }

    pub fn check_working_copy_writable(&self) -> Result<(), CommandError> {
        if self.may_update_working_copy {
            Ok(())
        } else {
            let hint = if self.env.command.global_args().ignore_working_copy {
                "Don't use --ignore-working-copy."
            } else if self.env.command.global_args().no_integrate_operation {
                "Don't use --no-integrate-operation."
            } else {
                "Don't use --at-op."
            };
            Err(user_error("This command must be able to update the working copy.").hinted(hint))
        }
    }

    /// Acquires a lock for git import/export operations if the workspace is
    /// colocated with Git. Returns a token that can be passed to functions
    /// that need to import from or export to Git. For non-colocated repos,
    /// returns a token with no lock inside.
    fn lock_git_import_export(&self) -> Result<GitImportExportLock, CommandError> {
        let lock = if self.working_copy_shared_with_git {
            let lock_path = self.workspace.repo_path().join("git_import_export.lock");
            Some(FileLock::lock(lock_path.clone()).map_err(|err| {
                user_error_with_message("Failed to take lock for Git import/export", err)
            })?)
        } else {
            None
        };
        Ok(GitImportExportLock { _lock: lock })
    }

    /// Note that unless you have a good reason not to do so, you should always
    /// call [`print_snapshot_stats`] with the [`SnapshotStats`] returned by
    /// this function to present possible untracked files to the user.
    #[instrument(skip_all)]
    async fn maybe_snapshot_impl(
        &mut self,
        ui: &Ui,
    ) -> Result<SnapshotStats, SnapshotWorkingCopyError> {
        if !self.may_snapshot_working_copy {
            return Ok(SnapshotStats::default());
        }

        // Acquire git import/export lock once for the entire import/snapshot/export
        // cycle. This prevents races with other processes during Git HEAD and
        // refs import/export.
        #[cfg_attr(not(feature = "git"), allow(unused_variables))]
        let git_import_export_lock = self
            .lock_git_import_export()
            .map_err(snapshot_command_error)?;

        // Reload at current head to avoid creating divergent operations if another
        // process committed an operation while we were waiting for the lock.
        if self.working_copy_shared_with_git {
            let repo = self.repo().clone();
            let op_heads_store = repo.loader().op_heads_store();
            let op_heads = op_heads_store
                .get_op_heads()
                .await
                .map_err(snapshot_command_error)?;
            if std::slice::from_ref(repo.op_id()) != op_heads {
                let op = self
                    .env
                    .command
                    .resolve_operation(ui, repo.loader(), self.workspace_name())
                    .map_err(snapshot_command_error)?;
                let current_repo = repo
                    .loader()
                    .load_at(&op)
                    .await
                    .map_err(snapshot_command_error)?;
                self.user_repo = ReadonlyUserRepo::new(current_repo);
            }
        }

        #[cfg(feature = "git")]
        if self.working_copy_shared_with_git {
            self.import_git_head(ui, &git_import_export_lock)
                .await
                .map_err(snapshot_command_error)?;
        }
        // Because the Git refs (except HEAD) aren't imported yet, the ref
        // pointing to the new working-copy commit might not be exported.
        // In that situation, the ref would be conflicted anyway, so export
        // failure is okay.
        let stats = self.snapshot_working_copy(ui).await?;

        // import_git_refs() can rebase the working-copy commit.
        #[cfg(feature = "git")]
        if self.working_copy_shared_with_git {
            self.import_git_refs(ui, &git_import_export_lock)
                .await
                .map_err(snapshot_command_error)?;
        }
        Ok(stats)
    }

    /// Snapshots the working copy if allowed, and imports Git refs if the
    /// working copy is collocated with Git.
    ///
    /// Returns whether a snapshot was taken.
    #[instrument(skip_all)]
    pub async fn maybe_snapshot(&mut self, ui: &Ui) -> Result<bool, CommandError> {
        let op_id_before = self.repo().op_id().clone();
        let stats = self
            .maybe_snapshot_impl(ui)
            .await
            .map_err(|err| err.into_command_error())?;
        print_snapshot_stats(ui, &stats, self.env().path_converter())?;
        let op_id_after = self.repo().op_id();
        Ok(op_id_before != *op_id_after)
    }

    /// Imports new HEAD from the colocated Git repo.
    ///
    /// If the Git HEAD has changed, this function checks out the new Git HEAD.
    /// The old working-copy commit will be abandoned if it's discardable. The
    /// working-copy state will be reset to point to the new Git HEAD. The
    /// working-copy contents won't be updated.
    #[cfg(feature = "git")]
    #[instrument(skip_all)]
    async fn import_git_head(
        &mut self,
        ui: &Ui,
        git_import_export_lock: &GitImportExportLock,
    ) -> Result<(), CommandError> {
        assert!(self.may_snapshot_working_copy);
        let mut tx = self.start_transaction();
        jj_lib::git::import_head(tx.repo_mut()).await?;
        if !tx.repo().has_changes() {
            return Ok(());
        }

        let mut tx = tx.into_inner();
        let old_git_head = self.repo().view().git_head().clone();
        let new_git_head = tx.repo().view().git_head().clone();
        if let Some(new_git_head_id) = new_git_head.as_normal() {
            let workspace_name = self.workspace_name().to_owned();
            let new_git_head_commit = tx.repo().store().get_commit_async(new_git_head_id).await?;
            let wc_commit = tx
                .repo_mut()
                .check_out(workspace_name, &new_git_head_commit)
                .await?;
            let mut locked_ws = self.workspace.start_working_copy_mutation().await?;
            // The working copy was presumably updated by the git command that updated
            // HEAD, so we just need to reset our working copy
            // state to it without updating working copy files.
            locked_ws.locked_wc().reset(&wc_commit).await?;
            tx.repo_mut().rebase_descendants().await?;
            self.user_repo = ReadonlyUserRepo::new(
                self.env
                    .command
                    .maybe_commit_transaction(tx, "import git head")
                    .await?,
            );
            if self.env.command.should_commit_transaction() {
                locked_ws
                    .finish(self.user_repo.repo.op_id().clone())
                    .await?;
            }
            if old_git_head.is_present() {
                writeln!(
                    ui.status(),
                    "Reset the working copy parent to the new Git HEAD."
                )?;
            } else {
                // Don't print verbose message on initial checkout.
            }
        } else {
            // Unlikely, but the HEAD ref got deleted by git?
            self.finish_transaction(ui, tx, "import git head", git_import_export_lock)
                .await?;
        }
        Ok(())
    }

    /// Imports branches and tags from the underlying Git repo, abandons old
    /// bookmarks.
    ///
    /// If the working-copy branch is rebased, and if update is allowed, the
    /// new working-copy commit will be checked out.
    ///
    /// This function does not import the Git HEAD, but the HEAD may be reset to
    /// the working copy parent if the repository is colocated.
    #[cfg(feature = "git")]
    #[instrument(skip_all)]
    async fn import_git_refs(
        &mut self,
        ui: &Ui,
        git_import_export_lock: &GitImportExportLock,
    ) -> Result<(), CommandError> {
        use jj_lib::git;
        let git_settings = git::GitSettings::from_settings(self.settings())?;
        let remote_settings = self.settings().remote_settings()?;
        let import_options =
            crate::git_util::load_git_import_options(ui, &git_settings, &remote_settings)?;
        let mut tx = self.start_transaction();
        let stats = git::import_refs(tx.repo_mut(), &import_options).await?;
        crate::git_util::print_git_import_stats_summary(ui, &stats)?;
        if !tx.repo().has_changes() {
            return Ok(());
        }

        let mut tx = tx.into_inner();
        // Rebase here to show slightly different status message.
        let num_rebased = tx.repo_mut().rebase_descendants().await?;
        if num_rebased > 0 {
            writeln!(
                ui.status(),
                "Rebased {num_rebased} descendant commits off of commits rewritten from git"
            )?;
        }
        self.finish_transaction(ui, tx, "import git refs", git_import_export_lock)
            .await?;
        writeln!(
            ui.status(),
            "Done importing changes from the underlying Git repo."
        )?;
        Ok(())
    }

    pub fn repo(&self) -> &Arc<ReadonlyRepo> {
        &self.user_repo.repo
    }

    pub fn repo_path(&self) -> &Path {
        self.workspace.repo_path()
    }

    pub fn workspace(&self) -> &Workspace {
        &self.workspace
    }

    pub fn working_copy(&self) -> &dyn WorkingCopy {
        self.workspace.working_copy()
    }

    pub fn env(&self) -> &WorkspaceCommandEnvironment {
        &self.env
    }

    pub async fn unchecked_start_working_copy_mutation(
        &mut self,
    ) -> Result<(LockedWorkspace<'_>, Commit), CommandError> {
        self.check_working_copy_writable()?;
        let wc_commit = if let Some(wc_commit_id) = self.get_wc_commit_id() {
            self.repo().store().get_commit_async(wc_commit_id).await?
        } else {
            return Err(user_error("Nothing checked out in this workspace"));
        };

        let locked_ws = self.workspace.start_working_copy_mutation().await?;

        Ok((locked_ws, wc_commit))
    }

    pub async fn start_working_copy_mutation(
        &mut self,
    ) -> Result<(LockedWorkspace<'_>, Commit), CommandError> {
        let (mut locked_ws, wc_commit) = self.unchecked_start_working_copy_mutation().await?;
        if wc_commit.tree().tree_ids_and_labels()
            != locked_ws.locked_wc().old_tree().tree_ids_and_labels()
        {
            return Err(user_error("Concurrent working copy operation. Try again."));
        }
        Ok((locked_ws, wc_commit))
    }

    async fn create_and_check_out_recovery_commit(
        &mut self,
        ui: &Ui,
    ) -> Result<SnapshotStats, CommandError> {
        self.check_working_copy_writable()?;

        let workspace_name = self.workspace_name().to_owned();
        let mut locked_ws = self.workspace.start_working_copy_mutation().await?;
        let (repo, new_commit) = working_copy::create_and_check_out_recovery_commit(
            locked_ws.locked_wc(),
            &self.user_repo.repo,
            workspace_name,
            "RECOVERY COMMIT FROM `jj workspace update-stale`

This commit contains changes that were written to the working copy by an
operation that was subsequently lost (or was at least unavailable when you ran
`jj workspace update-stale`). Because the operation was lost, we don't know
what the parent commits are supposed to be. That means that the diff compared
to the current parents may contain changes from multiple commits.
",
        )
        .await?;

        writeln!(
            ui.status(),
            "Created and checked out recovery commit {}",
            short_commit_hash(new_commit.id())
        )?;
        locked_ws.finish(repo.op_id().clone()).await?;
        self.user_repo = ReadonlyUserRepo::new(repo);

        self.maybe_snapshot_impl(ui)
            .await
            .map_err(|err| err.into_command_error())
    }

    pub fn workspace_root(&self) -> &Path {
        self.workspace.workspace_root()
    }

    pub fn workspace_name(&self) -> &WorkspaceName {
        self.workspace.workspace_name()
    }

    pub fn get_wc_commit_id(&self) -> Option<&CommitId> {
        self.repo().view().get_wc_commit_id(self.workspace_name())
    }

    pub fn working_copy_shared_with_git(&self) -> bool {
        self.working_copy_shared_with_git
    }

    pub fn format_file_path(&self, file: &RepoPath) -> String {
        self.path_converter().format_file_path(file)
    }

    /// Parses a path relative to cwd into a RepoPath, which is relative to the
    /// workspace root.
    pub fn parse_file_path(&self, input: &str) -> Result<RepoPathBuf, UiPathParseError> {
        self.path_converter().parse_file_path(input)
    }

    /// Parses the given strings as file patterns.
    pub fn parse_file_patterns(
        &self,
        ui: &Ui,
        values: &[String],
    ) -> Result<FilesetExpression, CommandError> {
        // TODO: This function might be superseded by parse_union_filesets(),
        // but it would be weird if parse_union_*() had a special case for the
        // empty arguments.
        if values.is_empty() {
            Ok(FilesetExpression::all())
        } else {
            self.parse_union_filesets(ui, values)
        }
    }

    /// Parses the given fileset expressions and concatenates them all.
    pub fn parse_union_filesets(
        &self,
        ui: &Ui,
        file_args: &[String], // TODO: introduce FileArg newtype?
    ) -> Result<FilesetExpression, CommandError> {
        let mut diagnostics = FilesetDiagnostics::new();
        let context = self.env.fileset_parse_context();
        let expressions: Vec<_> = file_args
            .iter()
            .map(|arg| fileset::parse_maybe_bare(&mut diagnostics, arg, &context))
            .try_collect()?;
        print_parse_diagnostics(ui, "In fileset expression", &diagnostics)?;
        Ok(FilesetExpression::union_all(expressions))
    }

    pub fn auto_tracking_matcher(&self, ui: &Ui) -> Result<Box<dyn Matcher>, CommandError> {
        let mut diagnostics = FilesetDiagnostics::new();
        let pattern = self.settings().get_string("snapshot.auto-track")?;
        let context = self.env.fileset_parse_context_for_config();
        let expression = fileset::parse(&mut diagnostics, &pattern, &context)?;
        print_parse_diagnostics(ui, "In `snapshot.auto-track`", &diagnostics)?;
        Ok(expression.to_matcher())
    }

    pub fn snapshot_options_with_start_tracking_matcher<'a>(
        &self,
        start_tracking_matcher: &'a dyn Matcher,
    ) -> Result<SnapshotOptions<'a>, CommandError> {
        let base_ignores = self.base_ignores()?;
        let HumanByteSize(mut max_new_file_size) = self
            .settings()
            .get_value_with("snapshot.max-new-file-size", TryInto::try_into)?;
        if max_new_file_size == 0 {
            max_new_file_size = u64::MAX;
        }
        Ok(SnapshotOptions {
            base_ignores,
            progress: None,
            start_tracking_matcher,
            force_tracking_matcher: &NothingMatcher,
            max_new_file_size,
        })
    }

    pub(crate) fn path_converter(&self) -> &RepoPathUiConverter {
        self.env.path_converter()
    }

    #[cfg(not(feature = "git"))]
    pub fn base_ignores(&self) -> Result<Arc<GitIgnoreFile>, GitIgnoreError> {
        Ok(GitIgnoreFile::empty())
    }

    #[cfg(feature = "git")]
    #[instrument(skip_all)]
    pub fn base_ignores(&self) -> Result<Arc<GitIgnoreFile>, GitIgnoreError> {
        let get_excludes_file_path = |config: &gix::config::File| -> Option<PathBuf> {
            // TODO: maybe use path() and interpolate(), which can process non-utf-8
            // path on Unix.
            if let Some(value) = config.string("core.excludesFile") {
                let path = str::from_utf8(&value)
                    .ok()
                    .map(jj_lib::file_util::expand_home_path)?;
                // The configured path is usually absolute, but if it's relative,
                // the "git" command would read the file at the work-tree directory.
                Some(self.workspace_root().join(path))
            } else {
                xdg_config_home().map(|x| x.join("git").join("ignore"))
            }
        };

        fn xdg_config_home() -> Option<PathBuf> {
            if let Ok(x) = std::env::var("XDG_CONFIG_HOME")
                && !x.is_empty()
            {
                return Some(PathBuf::from(x));
            }
            etcetera::home_dir().ok().map(|home| home.join(".config"))
        }

        let mut git_ignores = GitIgnoreFile::empty();
        if let Ok(git_backend) = jj_lib::git::get_git_backend(self.repo().store()) {
            let git_repo = git_backend.git_repo();
            if let Some(excludes_file_path) = get_excludes_file_path(&git_repo.config_snapshot()) {
                git_ignores = git_ignores.chain_with_file(RepoPath::root(), excludes_file_path)?;
            }
            git_ignores = git_ignores.chain_with_file(
                RepoPath::root(),
                git_backend.git_repo_path().join("info").join("exclude"),
            )?;
        } else if let Ok(git_config) = gix::config::File::from_globals()
            && let Some(excludes_file_path) = get_excludes_file_path(&git_config)
        {
            git_ignores = git_ignores.chain_with_file(RepoPath::root(), excludes_file_path)?;
        }
        Ok(git_ignores)
    }

    /// Creates textual diff renderer of the specified `formats`.
    pub fn diff_renderer(&self, formats: Vec<DiffFormat>) -> DiffRenderer<'_> {
        DiffRenderer::new(
            self.repo().as_ref(),
            self.path_converter(),
            self.env.conflict_marker_style(),
            formats,
        )
    }

    /// Loads textual diff renderer from the settings and command arguments.
    pub fn diff_renderer_for(
        &self,
        args: &DiffFormatArgs,
    ) -> Result<DiffRenderer<'_>, CommandError> {
        let formats = diff_util::diff_formats_for(self.settings(), args)?;
        Ok(self.diff_renderer(formats))
    }

    /// Loads textual diff renderer from the settings and log-like command
    /// arguments. Returns `Ok(None)` if there are no command arguments that
    /// enable patch output.
    pub fn diff_renderer_for_log(
        &self,
        args: &DiffFormatArgs,
        patch: bool,
    ) -> Result<Option<DiffRenderer<'_>>, CommandError> {
        let formats = diff_util::diff_formats_for_log(self.settings(), args, patch)?;
        Ok((!formats.is_empty()).then(|| self.diff_renderer(formats)))
    }

    /// Loads diff editor from the settings.
    ///
    /// If the `tool_name` isn't specified, the default editor will be returned.
    pub fn diff_editor(
        &self,
        ui: &Ui,
        tool_name: Option<&str>,
    ) -> Result<DiffEditor, CommandError> {
        let base_ignores = self.base_ignores()?;
        let conflict_marker_style = self.env.conflict_marker_style();
        if let Some(name) = tool_name {
            Ok(DiffEditor::with_name(
                name,
                self.settings(),
                base_ignores,
                conflict_marker_style,
            )?)
        } else {
            Ok(DiffEditor::from_settings(
                ui,
                self.settings(),
                base_ignores,
                conflict_marker_style,
            )?)
        }
    }

    /// Conditionally loads diff editor from the settings.
    ///
    /// If the `tool_name` is specified, interactive session is implied.
    pub fn diff_selector(
        &self,
        ui: &Ui,
        tool_name: Option<&str>,
        force_interactive: bool,
    ) -> Result<DiffSelector, CommandError> {
        if tool_name.is_some() || force_interactive {
            Ok(DiffSelector::Interactive(self.diff_editor(ui, tool_name)?))
        } else {
            Ok(DiffSelector::NonInteractive)
        }
    }

    /// Loads 3-way merge editor from the settings.
    ///
    /// If the `tool_name` isn't specified, the default editor will be returned.
    pub fn merge_editor(
        &self,
        ui: &Ui,
        tool_name: Option<&str>,
    ) -> Result<MergeEditor, MergeToolConfigError> {
        let conflict_marker_style = self.env.conflict_marker_style();
        if let Some(name) = tool_name {
            MergeEditor::with_name(
                name,
                self.settings(),
                self.path_converter().clone(),
                conflict_marker_style,
            )
        } else {
            MergeEditor::from_settings(
                ui,
                self.settings(),
                self.path_converter().clone(),
                conflict_marker_style,
            )
        }
    }

    /// Loads text editor from the settings.
    pub fn text_editor(&self) -> Result<TextEditor, ConfigGetError> {
        TextEditor::from_settings(self.settings())
    }

    pub fn resolve_single_op(&self, op_str: &str) -> Result<Operation, OpsetEvaluationError> {
        op_walk::resolve_op_with_repo(self.repo(), op_str).block_on()
    }

    /// Resolve a revset to a single revision. Return an error if the revset is
    /// empty or has multiple revisions.
    pub async fn resolve_single_rev(
        &self,
        ui: &Ui,
        revision_arg: &RevisionArg,
    ) -> Result<Commit, CommandError> {
        let expression = self.parse_revset(ui, revision_arg)?;
        revset_util::evaluate_revset_to_single_commit(revision_arg.as_ref(), &expression, || {
            self.commit_summary_template()
        })
        .await
    }

    /// Evaluates revset expressions to set of commit IDs. The
    /// returned set preserves the order of the input expressions.
    pub async fn resolve_revsets_ordered(
        &self,
        ui: &Ui,
        revision_args: &[RevisionArg],
    ) -> Result<IndexSet<CommitId>, CommandError> {
        let mut all_commits = IndexSet::new();
        for revision_arg in revision_args {
            let expression = self.parse_revset(ui, revision_arg)?;
            let mut stream = expression.evaluate_to_commit_ids()?;
            while let Some(commit_id) = stream.try_next().await? {
                all_commits.insert(commit_id);
            }
        }
        Ok(all_commits)
    }

    /// Evaluates revset expressions to non-empty set of commit IDs. The
    /// returned set preserves the order of the input expressions.
    pub async fn resolve_some_revsets(
        &self,
        ui: &Ui,
        revision_args: &[RevisionArg],
    ) -> Result<IndexSet<CommitId>, CommandError> {
        let all_commits = self.resolve_revsets_ordered(ui, revision_args).await?;
        if all_commits.is_empty() {
            Err(user_error("Empty revision set"))
        } else {
            Ok(all_commits)
        }
    }

    pub fn parse_revset(
        &self,
        ui: &Ui,
        revision_arg: &RevisionArg,
    ) -> Result<RevsetExpressionEvaluator<'_>, CommandError> {
        let mut diagnostics = RevsetDiagnostics::new();
        let context = self.env.revset_parse_context();
        let expression = revset::parse(&mut diagnostics, revision_arg.as_ref(), &context)?;
        print_parse_diagnostics(ui, "In revset expression", &diagnostics)?;
        Ok(self.attach_revset_evaluator(expression))
    }

    /// Parses the given revset expressions and concatenates them all.
    pub fn parse_union_revsets(
        &self,
        ui: &Ui,
        revision_args: &[RevisionArg],
    ) -> Result<RevsetExpressionEvaluator<'_>, CommandError> {
        let mut diagnostics = RevsetDiagnostics::new();
        let context = self.env.revset_parse_context();
        let expressions: Vec<_> = revision_args
            .iter()
            .map(|arg| revset::parse(&mut diagnostics, arg.as_ref(), &context))
            .try_collect()?;
        print_parse_diagnostics(ui, "In revset expression", &diagnostics)?;
        let expression = RevsetExpression::union_all(&expressions);
        Ok(self.attach_revset_evaluator(expression))
    }

    pub fn attach_revset_evaluator(
        &self,
        expression: Arc<UserRevsetExpression>,
    ) -> RevsetExpressionEvaluator<'_> {
        RevsetExpressionEvaluator::new(
            self.repo().as_ref(),
            self.env.command.revset_extensions().clone(),
            self.id_prefix_context(),
            expression,
        )
    }

    pub fn id_prefix_context(&self) -> &IdPrefixContext {
        self.user_repo
            .id_prefix_context
            .get_or_init(|| self.env.new_id_prefix_context())
    }

    /// Parses template of the given language into evaluation tree.
    pub fn parse_template<'a, C, L>(
        &self,
        ui: &Ui,
        language: &L,
        template_text: &str,
    ) -> Result<TemplateRenderer<'a, C>, CommandError>
    where
        C: Clone + 'a,
        L: TemplateLanguage<'a> + ?Sized,
        L::Property: WrapTemplateProperty<'a, C>,
    {
        self.env.parse_template(ui, language, template_text)
    }

    /// Parses template that is validated by `Self::new()`.
    fn reparse_valid_template<'a, C, L>(
        &self,
        language: &L,
        template_text: &str,
    ) -> TemplateRenderer<'a, C>
    where
        C: Clone + 'a,
        L: TemplateLanguage<'a> + ?Sized,
        L::Property: WrapTemplateProperty<'a, C>,
    {
        template_builder::parse(
            language,
            &mut TemplateDiagnostics::new(),
            template_text,
            &self.env.template_aliases_map,
        )
        .expect("parse error should be confined by WorkspaceCommandHelper::new()")
    }

    /// Parses commit template into evaluation tree.
    pub fn parse_commit_template(
        &self,
        ui: &Ui,
        template_text: &str,
    ) -> Result<TemplateRenderer<'_, Commit>, CommandError> {
        let language = self.commit_template_language();
        self.parse_template(ui, &language, template_text)
    }

    /// Parses commit template into evaluation tree.
    pub fn parse_operation_template(
        &self,
        ui: &Ui,
        template_text: &str,
    ) -> Result<TemplateRenderer<'_, Operation>, CommandError> {
        let language = self.operation_template_language();
        self.parse_template(ui, &language, template_text)
    }

    /// Creates commit template language environment for this workspace.
    pub fn commit_template_language(&self) -> CommitTemplateLanguage<'_> {
        self.env
            .commit_template_language(self.repo().as_ref(), self.id_prefix_context())
    }

    /// Creates operation template language environment for this workspace.
    pub fn operation_template_language(&self) -> OperationTemplateLanguage {
        OperationTemplateLanguage::new(
            self.workspace.repo_loader(),
            Some(self.repo().op_id()),
            self.env.operation_template_extensions(),
        )
    }

    /// Template for one-line summary of a commit.
    pub fn commit_summary_template(&self) -> TemplateRenderer<'_, Commit> {
        let language = self.commit_template_language();
        self.reparse_valid_template(&language, &self.commit_summary_template_text)
            .labeled(["commit"])
    }

    /// Template for one-line summary of an operation.
    pub fn operation_summary_template(&self) -> TemplateRenderer<'_, Operation> {
        let language = self.operation_template_language();
        self.reparse_valid_template(&language, &self.op_summary_template_text)
            .labeled(["operation"])
    }

    pub fn short_change_id_template(&self) -> TemplateRenderer<'_, Commit> {
        let language = self.commit_template_language();
        self.reparse_valid_template(&language, SHORT_CHANGE_ID_TEMPLATE_TEXT)
            .labeled(["commit"])
    }

    /// Returns one-line summary of the given `commit`.
    ///
    /// Use `write_commit_summary()` to get colorized output. Use
    /// `commit_summary_template()` if you have many commits to process.
    pub fn format_commit_summary(&self, commit: &Commit) -> String {
        let output = self.commit_summary_template().format_plain_text(commit);
        output.into_string_lossy()
    }

    /// Writes one-line summary of the given `commit`.
    ///
    /// Use `commit_summary_template()` if you have many commits to process.
    #[instrument(skip_all)]
    pub fn write_commit_summary(
        &self,
        formatter: &mut dyn Formatter,
        commit: &Commit,
    ) -> std::io::Result<()> {
        self.commit_summary_template().format(commit, formatter)
    }

    pub async fn check_rewritable<'a>(
        &self,
        commits: impl IntoIterator<Item = &'a CommitId>,
    ) -> Result<(), CommandError> {
        let commit_ids = commits.into_iter().cloned().collect_vec();
        let to_rewrite_expr = RevsetExpression::commits(commit_ids);
        self.check_rewritable_expr(&to_rewrite_expr).await
    }

    pub async fn check_rewritable_expr(
        &self,
        to_rewrite_expr: &Arc<ResolvedRevsetExpression>,
    ) -> Result<(), CommandError> {
        let repo = self.repo().as_ref();
        let Some(commit_id) = self
            .env
            .find_immutable_commit(repo, to_rewrite_expr)
            .await?
        else {
            return Ok(());
        };
        let error = if &commit_id == repo.store().root_commit_id() {
            user_error(format!("The root commit {commit_id:.12} is immutable"))
        } else {
            let mut error = user_error(format!("Commit {commit_id:.12} is immutable"));
            let commit = repo.store().get_commit_async(&commit_id).await?;
            error.add_formatted_hint_with(|formatter| {
                write!(formatter, "Could not modify commit: ")?;
                self.write_commit_summary(formatter, &commit)?;
                Ok(())
            });
            error.add_hint("Immutable commits are used to protect shared history.");
            error.add_hint(indoc::indoc! {"
                For more information, see:
                      - https://docs.jj-vcs.dev/latest/config/#set-of-immutable-commits
                      - `jj help -k config`, \"Set of immutable commits\""});

            // Not using self.id_prefix_context() for consistency with
            // find_immutable_commit().
            let id_prefix_context =
                IdPrefixContext::new(self.env.command.revset_extensions().clone());
            let (lower_bound, upper_bound) = RevsetExpressionEvaluator::new(
                repo,
                self.env.command.revset_extensions().clone(),
                &id_prefix_context,
                self.env.immutable_expression(),
            )
            .resolve()?
            .intersection(&to_rewrite_expr.descendants())
            .evaluate(repo)?
            .count_estimate()?;
            let exact = upper_bound == Some(lower_bound);
            let or_more = if exact { "" } else { " or more" };
            error.add_hint(format!(
                "This operation would rewrite {lower_bound}{or_more} immutable commits."
            ));

            error
        };
        Err(error)
    }

    #[instrument(skip_all)]
    async fn snapshot_working_copy(
        &mut self,
        ui: &Ui,
    ) -> Result<SnapshotStats, SnapshotWorkingCopyError> {
        let workspace_name = self.workspace_name().to_owned();
        let repo = self.repo().clone();
        let auto_tracking_matcher = self
            .auto_tracking_matcher(ui)
            .map_err(snapshot_command_error)?;
        let options = self
            .snapshot_options_with_start_tracking_matcher(&auto_tracking_matcher)
            .map_err(snapshot_command_error)?;

        // Compare working-copy tree and operation with repo's, and reload as needed.
        let mut locked_ws = self
            .workspace
            .start_working_copy_mutation()
            .await
            .map_err(snapshot_command_error)?;

        let Some((repo, wc_commit)) =
            handle_stale_working_copy(locked_ws.locked_wc(), repo, &workspace_name).await?
        else {
            // If the workspace has been deleted, it's unclear what to do, so we just skip
            // committing the working copy.
            return Ok(SnapshotStats::default());
        };

        self.user_repo = ReadonlyUserRepo::new(repo);
        let (new_tree, stats) = {
            let mut options = options;
            let progress = crate::progress::snapshot_progress(ui);
            options.progress = progress.as_ref().map(|x| x as _);
            locked_ws
                .locked_wc()
                .snapshot(&options)
                .await
                .map_err(snapshot_command_error)?
        };
        if new_tree.tree_ids_and_labels() != wc_commit.tree().tree_ids_and_labels() {
            let mut tx = start_repo_transaction(
                &self.user_repo.repo,
                &workspace_name,
                self.env.command.string_args(),
            );
            tx.set_is_snapshot(true);
            let mut_repo = tx.repo_mut();
            let commit = mut_repo
                .rewrite_commit(&wc_commit)
                .set_tree(new_tree.clone())
                .write()
                .await
                .map_err(snapshot_command_error)?;
            mut_repo
                .set_wc_commit(workspace_name, commit.id().clone())
                .map_err(snapshot_command_error)?;

            // Rebase descendants
            let num_rebased = mut_repo
                .rebase_descendants()
                .await
                .map_err(snapshot_command_error)?;
            if num_rebased > 0 {
                writeln!(
                    ui.status(),
                    "Rebased {num_rebased} descendant commits onto updated working copy"
                )
                .map_err(snapshot_command_error)?;
            }

            #[cfg(feature = "git")]
            if self.working_copy_shared_with_git && self.env.command.should_commit_transaction() {
                let old_tree = wc_commit.tree();
                let new_tree = commit.tree();
                export_working_copy_changes_to_git(ui, mut_repo, &old_tree, &new_tree)
                    .await
                    .map_err(snapshot_command_error)?;
            }

            let repo = self
                .env
                .command
                .maybe_commit_transaction(tx, "snapshot working copy")
                .await
                .map_err(snapshot_command_error)?;
            self.user_repo = ReadonlyUserRepo::new(repo);
        }

        #[cfg(feature = "git")]
        if self.working_copy_shared_with_git
            && let Ok(resolved_tree) = new_tree
                .trees()
                .await
                .map_err(snapshot_command_error)?
                .into_resolved()
            && resolved_tree
                .entries_non_recursive()
                .any(|entry| entry.name().as_internal_str().starts_with(".jjconflict"))
        {
            writeln!(
                ui.warning_default(),
                "The working copy contains '.jjconflict' files. These files are used by `jj` \
                 internally and should not be present in the working copy."
            )
            .map_err(snapshot_command_error)?;
            writeln!(
                ui.hint_default(),
                "You may have used a regular `git` command to check out a conflicted commit."
            )
            .map_err(snapshot_command_error)?;
            writeln!(
                ui.hint_default(),
                "You can use `jj abandon` to discard the working copy changes."
            )
            .map_err(snapshot_command_error)?;
        }

        if self.env.command.should_commit_transaction() {
            locked_ws
                .finish(self.user_repo.repo.op_id().clone())
                .await
                .map_err(snapshot_command_error)?;
        }
        Ok(stats)
    }

    async fn update_working_copy(
        &mut self,
        ui: &Ui,
        maybe_old_commit: Option<&Commit>,
        new_commit: &Commit,
    ) -> Result<(), CommandError> {
        assert!(self.may_update_working_copy);
        let stats = update_working_copy(
            &self.user_repo.repo,
            &mut self.workspace,
            maybe_old_commit,
            new_commit,
        )
        .await?;
        self.print_updated_working_copy_stats(ui, maybe_old_commit, new_commit, &stats)
    }

    fn print_updated_working_copy_stats(
        &self,
        ui: &Ui,
        maybe_old_commit: Option<&Commit>,
        new_commit: &Commit,
        stats: &CheckoutStats,
    ) -> Result<(), CommandError> {
        if Some(new_commit) != maybe_old_commit
            && let Some(mut formatter) = ui.status_formatter()
        {
            let template = self.commit_summary_template();
            write!(formatter, "Working copy  (@) now at: ")?;
            template.format(new_commit, formatter.as_mut())?;
            writeln!(formatter)?;
            for parent in new_commit.parents().block_on()? {
                //                "Working copy  (@) now at: "
                write!(formatter, "Parent commit (@-)      : ")?;
                template.format(&parent, formatter.as_mut())?;
                writeln!(formatter)?;
            }
        }
        print_checkout_stats(ui, stats, new_commit)?;
        if Some(new_commit) != maybe_old_commit
            && let Some(mut formatter) = ui.status_formatter()
            && new_commit.has_conflict()
        {
            let conflicts = new_commit.tree().conflicts().collect_vec();
            writeln!(
                formatter.labeled("warning").with_heading("Warning: "),
                "There are unresolved conflicts at these paths:"
            )?;
            print_conflicted_paths(conflicts, formatter.as_mut(), self)?;
        }
        Ok(())
    }

    pub fn start_transaction(&mut self) -> WorkspaceCommandTransaction<'_> {
        let tx = start_repo_transaction(
            self.repo(),
            self.workspace_name(),
            self.env.command.string_args(),
        );
        let id_prefix_context = mem::take(&mut self.user_repo.id_prefix_context);
        WorkspaceCommandTransaction {
            helper: self,
            tx,
            id_prefix_context,
        }
    }

    async fn finish_transaction(
        &mut self,
        ui: &Ui,
        mut tx: Transaction,
        description: impl Into<String>,
        _git_import_export_lock: &GitImportExportLock,
    ) -> Result<(), CommandError> {
        let num_rebased = tx.repo_mut().rebase_descendants().await?;
        if num_rebased > 0 {
            writeln!(ui.status(), "Rebased {num_rebased} descendant commits")?;
        }

        for (name, wc_commit_id) in &tx.repo().view().wc_commit_ids().clone() {
            // This can fail if trunk() bookmark gets deleted or conflicted. If
            // the unresolvable trunk() issue gets addressed differently, it
            // should be okay to propagate the error.
            let wc_expr = RevsetExpression::commit(wc_commit_id.clone());
            let is_immutable = match self.env.find_immutable_commit(tx.repo(), &wc_expr).await {
                Ok(commit_id) => commit_id.is_some(),
                Err(CommandError { error, .. }) => {
                    writeln!(
                        ui.warning_default(),
                        "Failed to check mutability of the new working-copy revision."
                    )?;
                    print_error_sources(ui, Some(&error))?;
                    // Give up because the same error would occur repeatedly.
                    break;
                }
            };
            if is_immutable {
                let wc_commit = tx.repo().store().get_commit_async(wc_commit_id).await?;
                tx.repo_mut().check_out(name.clone(), &wc_commit).await?;
                writeln!(
                    ui.warning_default(),
                    "The working-copy commit in workspace '{name}' became immutable, so a new \
                     commit has been created on top of it.",
                    name = name.as_symbol()
                )?;
            }
        }
        if let Err(err) =
            revset_util::try_resolve_trunk_alias(tx.repo(), &self.env.revset_parse_context())
        {
            // The warning would be printed above if working copies exist.
            if tx.repo().view().wc_commit_ids().is_empty() {
                writeln!(
                    ui.warning_default(),
                    "Failed to resolve `revset-aliases.trunk()`: {err}"
                )?;
            }
            writeln!(
                ui.hint_default(),
                "Use `jj config edit --repo` to adjust the `trunk()` alias."
            )?;
        }

        let old_repo = tx.base_repo().clone();

        let maybe_old_wc_commit = old_repo
            .view()
            .get_wc_commit_id(self.workspace_name())
            .map(|commit_id| tx.base_repo().store().get_commit(commit_id))
            .transpose()?;
        let maybe_new_wc_commit = tx
            .repo()
            .view()
            .get_wc_commit_id(self.workspace_name())
            .map(|commit_id| tx.repo().store().get_commit(commit_id))
            .transpose()?;

        #[cfg(feature = "git")]
        if self.working_copy_shared_with_git && self.env.command.should_commit_transaction() {
            use std::error::Error as _;
            if let Some(wc_commit) = &maybe_new_wc_commit {
                // Export Git HEAD while holding the git-head lock to prevent races:
                // - Between two finish_transaction calls updating HEAD
                // - With import_git_head importing HEAD concurrently
                // This can still fail if HEAD was updated concurrently by another JJ process
                // (overlapping transaction) or a non-JJ process (e.g., git checkout). In that
                // case, the actual state will be imported on the next snapshot.
                match jj_lib::git::reset_head(tx.repo_mut(), wc_commit).await {
                    Ok(()) => {}
                    Err(err @ jj_lib::git::GitResetHeadError::UpdateHeadRef(_)) => {
                        writeln!(ui.warning_default(), "{err}")?;
                        print_error_sources(ui, err.source())?;
                    }
                    Err(err) => return Err(err.into()),
                }
            }
            let stats = jj_lib::git::export_refs(tx.repo_mut())?;
            crate::git_util::print_git_export_stats(ui, &stats)?;
        }

        self.user_repo = ReadonlyUserRepo::new(
            self.env
                .command
                .maybe_commit_transaction(tx, description)
                .await?,
        );

        // Update working copy before reporting repo changes, so that
        // potential errors while reporting changes (broken pipe, etc)
        // don't leave the working copy in a stale state.
        if self.may_update_working_copy {
            if let Some(new_commit) = &maybe_new_wc_commit {
                self.update_working_copy(ui, maybe_old_wc_commit.as_ref(), new_commit)
                    .await?;
            } else {
                // It seems the workspace was deleted, so we shouldn't try to
                // update it.
            }
        }

        self.report_repo_changes(ui, &old_repo).await?;

        if !self.env.command.should_commit_transaction() {
            writeln!(
                ui.status(),
                "Operation left uncommitted because --no-integrate-operation was requested: {}",
                short_operation_hash(self.repo().op_id())
            )?;
        }

        let settings = self.settings();
        let missing_user_name = settings.user_name().is_empty();
        let missing_user_mail = settings.user_email().is_empty();
        if missing_user_name || missing_user_mail {
            let not_configured_msg = match (missing_user_name, missing_user_mail) {
                (true, true) => "Name and email not configured.",
                (true, false) => "Name not configured.",
                (false, true) => "Email not configured.",
                _ => unreachable!(),
            };
            writeln!(
                ui.warning_default(),
                "{not_configured_msg} Until configured, your commits will be created with the \
                 empty identity, and can't be pushed to remotes."
            )?;
            writeln!(ui.hint_default(), "To configure, run:")?;
            if missing_user_name {
                writeln!(
                    ui.hint_no_heading(),
                    r#"  jj config set --user user.name "Some One""#
                )?;
            }
            if missing_user_mail {
                writeln!(
                    ui.hint_no_heading(),
                    r#"  jj config set --user user.email "someone@example.com""#
                )?;
            }
        }
        Ok(())
    }

    /// Inform the user about important changes to the repo since the previous
    /// operation (when `old_repo` was loaded).
    async fn report_repo_changes(
        &self,
        ui: &Ui,
        old_repo: &Arc<ReadonlyRepo>,
    ) -> Result<(), CommandError> {
        let Some(mut fmt) = ui.status_formatter() else {
            return Ok(());
        };
        let old_view = old_repo.view();
        let new_repo = self.repo().as_ref();
        let new_view = new_repo.view();

        let workspace_name = self.workspace_name();
        if old_view.wc_commit_ids().contains_key(workspace_name)
            && !new_view.wc_commit_ids().contains_key(workspace_name)
        {
            writeln!(
                fmt.labeled("warning").with_heading("Warning: "),
                "The current workspace '{}' no longer exists after this operation. The working \
                 copy was left untouched.",
                workspace_name.as_symbol(),
            )?;
            writeln!(
                fmt.labeled("hint").with_heading("Hint: "),
                "Restore to an operation that contains the workspace (e.g. `jj undo` or `jj \
                 redo`).",
            )?;
        }

        let old_heads = RevsetExpression::commits(old_view.heads().iter().cloned().collect());
        let new_heads = RevsetExpression::commits(new_view.heads().iter().cloned().collect());
        // Filter the revsets by conflicts instead of reading all commits and doing the
        // filtering here. That way, we can afford to evaluate the revset even if there
        // are millions of commits added to the repo, assuming the revset engine can
        // efficiently skip non-conflicting commits. Filter out empty commits mostly so
        // `jj new <conflicted commit>` doesn't result in a message about new conflicts.
        let conflicts = RevsetExpression::filter(RevsetFilterPredicate::HasConflict)
            .filtered(RevsetFilterPredicate::File(FilesetExpression::all()));
        let removed_conflicts_expr = new_heads.range(&old_heads).intersection(&conflicts);
        let added_conflicts_expr = old_heads.range(&new_heads).intersection(&conflicts);

        let get_commits =
            async |expr: Arc<ResolvedRevsetExpression>| -> Result<Vec<Commit>, CommandError> {
                let commits = expr
                    .evaluate(new_repo)?
                    .stream()
                    .commits(new_repo.store())
                    .try_collect()
                    .await?;
                Ok(commits)
            };
        let removed_conflict_commits = get_commits(removed_conflicts_expr).await?;
        let added_conflict_commits = get_commits(added_conflicts_expr).await?;

        fn commits_by_change_id(commits: &[Commit]) -> IndexMap<&ChangeId, Vec<&Commit>> {
            let mut result: IndexMap<&ChangeId, Vec<&Commit>> = IndexMap::new();
            for commit in commits {
                result.entry(commit.change_id()).or_default().push(commit);
            }
            result
        }
        let removed_conflicts_by_change_id = commits_by_change_id(&removed_conflict_commits);
        let added_conflicts_by_change_id = commits_by_change_id(&added_conflict_commits);
        let mut resolved_conflicts_by_change_id = removed_conflicts_by_change_id.clone();
        resolved_conflicts_by_change_id
            .retain(|change_id, _commits| !added_conflicts_by_change_id.contains_key(change_id));
        let mut new_conflicts_by_change_id = added_conflicts_by_change_id.clone();
        new_conflicts_by_change_id
            .retain(|change_id, _commits| !removed_conflicts_by_change_id.contains_key(change_id));

        // TODO: Also report new divergence and maybe resolved divergence
        if !resolved_conflicts_by_change_id.is_empty() {
            // TODO: Report resolved and abandoned numbers separately. However,
            // that involves resolving the change_id among the visible commits in the new
            // repo, which isn't currently supported by Google's revset engine.
            let num_resolved: usize = resolved_conflicts_by_change_id
                .values()
                .map(|commits| commits.len())
                .sum();
            writeln!(
                fmt,
                "Existing conflicts were resolved or abandoned from {num_resolved} commits."
            )?;
        }
        if !new_conflicts_by_change_id.is_empty() {
            let num_conflicted: usize = new_conflicts_by_change_id
                .values()
                .map(|commits| commits.len())
                .sum();
            writeln!(fmt, "New conflicts appeared in {num_conflicted} commits:")?;
            print_updated_commits(
                fmt.as_mut(),
                &self.commit_summary_template(),
                new_conflicts_by_change_id.values().flatten().copied(),
            )?;
        }

        // Hint that the user might want to `jj new` to the first conflict commit to
        // resolve conflicts. Only show the hints if there were any new or resolved
        // conflicts, and only if there are still some conflicts.
        if !(added_conflict_commits.is_empty()
            || resolved_conflicts_by_change_id.is_empty() && new_conflicts_by_change_id.is_empty())
        {
            // If the user just resolved some conflict and squashed them in, there won't be
            // any new conflicts. Clarify to them that there are still some other conflicts
            // to resolve. (We don't mention conflicts in commits that weren't affected by
            // the operation, however.)
            if new_conflicts_by_change_id.is_empty() {
                writeln!(
                    fmt,
                    "There are still unresolved conflicts in rebased descendants.",
                )?;
            }

            self.report_repo_conflicts(
                fmt.as_mut(),
                new_repo,
                added_conflict_commits
                    .iter()
                    .map(|commit| commit.id().clone())
                    .collect(),
            )
            .await?;
        }

        Ok(())
    }

    pub async fn report_repo_conflicts(
        &self,
        fmt: &mut dyn Formatter,
        repo: &ReadonlyRepo,
        conflicted_commits: Vec<CommitId>,
    ) -> Result<(), CommandError> {
        if !self.settings().get_bool("hints.resolving-conflicts")? || conflicted_commits.is_empty()
        {
            return Ok(());
        }

        let only_one_conflicted_commit = conflicted_commits.len() == 1;
        let root_conflicts_revset = RevsetExpression::commits(conflicted_commits)
            .roots()
            .evaluate(repo)?;

        let root_conflict_commits: Vec<_> = root_conflicts_revset
            .stream()
            .commits(repo.store())
            .try_collect()
            .await?;

        // The common part of these strings is not extracted, to avoid i18n issues.
        let instruction = if only_one_conflicted_commit {
            indoc! {"
            To resolve the conflicts, start by creating a commit on top of
            the conflicted commit:
            "}
        } else if root_conflict_commits.len() == 1 {
            indoc! {"
            To resolve the conflicts, start by creating a commit on top of
            the first conflicted commit:
            "}
        } else {
            indoc! {"
            To resolve the conflicts, start by creating a commit on top of
            one of the first conflicted commits:
            "}
        };
        write!(fmt.labeled("hint").with_heading("Hint: "), "{instruction}")?;
        let format_short_change_id = self.short_change_id_template();
        {
            let mut fmt = fmt.labeled("hint");
            for commit in &root_conflict_commits {
                write!(fmt, "  jj new ")?;
                format_short_change_id.format(commit, *fmt)?;
                writeln!(fmt)?;
            }
        }
        writedoc!(
            fmt.labeled("hint"),
            "
            Then use `jj resolve`, or edit the conflict markers in the file directly.
            Once the conflicts are resolved, you can inspect the result with `jj diff`.
            Then run `jj squash` to move the resolution into the conflicted commit.
            ",
        )?;
        Ok(())
    }

    /// Identifies bookmarks which are eligible to be moved automatically
    /// during `jj commit` and `jj new`. Whether a bookmark is eligible is
    /// determined by its target and the user and repo config for
    /// "advance-bookmarks".
    ///
    /// Returns a Vec of bookmarks in `repo` that point to any of the `from`
    /// commits and that are eligible to advance. The `from` commits are
    /// typically the parents of the target commit of `jj commit` or `jj new`.
    ///
    /// Bookmarks are not moved until
    /// `WorkspaceCommandTransaction::advance_bookmarks()` is called with the
    /// `AdvanceableBookmark`s returned by this function.
    ///
    /// Returns an empty `std::Vec` if no bookmarks are eligible to advance.
    pub fn get_advanceable_bookmarks<'a>(
        &self,
        ui: &Ui,
        from: impl IntoIterator<Item = &'a CommitId>,
    ) -> Result<Vec<AdvanceableBookmark>, CommandError> {
        let Some(ab_matcher) = load_advance_bookmarks_matcher(ui, self.settings())? else {
            // Return early if we know that there's no work to do.
            return Ok(Vec::new());
        };

        let mut advanceable_bookmarks = Vec::new();
        for from_commit in from {
            for (name, _) in self.repo().view().local_bookmarks_for_commit(from_commit) {
                if ab_matcher.is_match(name.as_str()) {
                    advanceable_bookmarks.push(AdvanceableBookmark {
                        name: name.to_owned(),
                        old_commit_id: from_commit.clone(),
                    });
                }
            }
        }

        Ok(advanceable_bookmarks)
    }
}

#[cfg(feature = "git")]
pub async fn export_working_copy_changes_to_git(
    ui: &Ui,
    mut_repo: &mut MutableRepo,
    old_tree: &MergedTree,
    new_tree: &MergedTree,
) -> Result<(), CommandError> {
    let repo = mut_repo.base_repo().as_ref();
    jj_lib::git::update_intent_to_add(repo, old_tree, new_tree).await?;
    let stats = jj_lib::git::export_refs(mut_repo)?;
    crate::git_util::print_git_export_stats(ui, &stats)?;
    Ok(())
}
#[cfg(not(feature = "git"))]
pub async fn export_working_copy_changes_to_git(
    _ui: &Ui,
    _mut_repo: &mut MutableRepo,
    _old_tree: &MergedTree,
    _new_tree: &MergedTree,
) -> Result<(), CommandError> {
    Ok(())
}

/// An ongoing [`Transaction`] tied to a particular workspace.
///
/// `WorkspaceCommandTransaction`s are created with
/// [`WorkspaceCommandHelper::start_transaction`] and committed with
/// [`WorkspaceCommandTransaction::finish`]. The inner `Transaction` can also be
/// extracted using [`WorkspaceCommandTransaction::into_inner`] in situations
/// where finer-grained control over the `Transaction` is necessary.
#[must_use]
pub struct WorkspaceCommandTransaction<'a> {
    helper: &'a mut WorkspaceCommandHelper,
    tx: Transaction,
    /// Cache of index built against the current MutableRepo state.
    id_prefix_context: OnceCell<IdPrefixContext>,
}

impl WorkspaceCommandTransaction<'_> {
    /// Workspace helper that may use the base repo.
    pub fn base_workspace_helper(&self) -> &WorkspaceCommandHelper {
        self.helper
    }

    /// Settings for this workspace.
    pub fn settings(&self) -> &UserSettings {
        self.helper.settings()
    }

    pub fn base_repo(&self) -> &Arc<ReadonlyRepo> {
        self.tx.base_repo()
    }

    pub fn repo(&self) -> &MutableRepo {
        self.tx.repo()
    }

    pub fn repo_mut(&mut self) -> &mut MutableRepo {
        self.id_prefix_context.take(); // invalidate
        self.tx.repo_mut()
    }

    pub fn check_out(&mut self, commit: &Commit) -> Result<Commit, CheckOutCommitError> {
        let name = self.helper.workspace_name().to_owned();
        self.id_prefix_context.take(); // invalidate
        self.tx.repo_mut().check_out(name, commit).block_on()
    }

    pub fn edit(&mut self, commit: &Commit) -> Result<(), EditCommitError> {
        let name = self.helper.workspace_name().to_owned();
        self.id_prefix_context.take(); // invalidate
        self.tx.repo_mut().edit(name, commit).block_on()
    }

    pub fn format_commit_summary(&self, commit: &Commit) -> String {
        let output = self.commit_summary_template().format_plain_text(commit);
        output.into_string_lossy()
    }

    pub fn write_commit_summary(
        &self,
        formatter: &mut dyn Formatter,
        commit: &Commit,
    ) -> std::io::Result<()> {
        self.commit_summary_template().format(commit, formatter)
    }

    /// Template for one-line summary of a commit within transaction.
    pub fn commit_summary_template(&self) -> TemplateRenderer<'_, Commit> {
        let language = self.commit_template_language();
        self.helper
            .reparse_valid_template(&language, &self.helper.commit_summary_template_text)
            .labeled(["commit"])
    }

    /// Creates commit template language environment capturing the current
    /// transaction state.
    pub fn commit_template_language(&self) -> CommitTemplateLanguage<'_> {
        let id_prefix_context = self
            .id_prefix_context
            .get_or_init(|| self.helper.env.new_id_prefix_context());
        self.helper
            .env
            .commit_template_language(self.tx.repo(), id_prefix_context)
    }

    /// Parses commit template with the current transaction state.
    pub fn parse_commit_template(
        &self,
        ui: &Ui,
        template_text: &str,
    ) -> Result<TemplateRenderer<'_, Commit>, CommandError> {
        let language = self.commit_template_language();
        self.helper.env.parse_template(ui, &language, template_text)
    }

    pub async fn finish(self, ui: &Ui, description: impl Into<String>) -> Result<(), CommandError> {
        if !self.tx.repo().has_changes() {
            writeln!(ui.status(), "Nothing changed.")?;
            return Ok(());
        }
        // Acquire git import/export lock before finishing the transaction to ensure
        // Git HEAD export happens atomically with the transaction commit.
        let git_import_export_lock = self.helper.lock_git_import_export()?;
        self.helper
            .finish_transaction(ui, self.tx, description, &git_import_export_lock)
            .await
    }

    /// Returns the wrapped [`Transaction`] for circumstances where
    /// finer-grained control is needed. The caller becomes responsible for
    /// finishing the `Transaction`, including rebasing descendants and updating
    /// the working copy, if applicable.
    pub fn into_inner(self) -> Transaction {
        self.tx
    }

    /// Moves each bookmark in `bookmarks` from an old commit it's associated
    /// with (configured by `get_advanceable_bookmarks`) to the `move_to`
    /// commit. If the bookmark is conflicted before the update, it will
    /// remain conflicted after the update, but the conflict will involve
    /// the `move_to` commit instead of the old commit.
    pub fn advance_bookmarks(
        &mut self,
        bookmarks: Vec<AdvanceableBookmark>,
        move_to: &CommitId,
    ) -> Result<(), CommandError> {
        for bookmark in bookmarks {
            // This removes the old commit ID from the bookmark's RefTarget and
            // replaces it with the `move_to` ID.
            self.repo_mut().merge_local_bookmark(
                &bookmark.name,
                &RefTarget::normal(bookmark.old_commit_id),
                &RefTarget::normal(move_to.clone()),
            )?;
        }
        Ok(())
    }
}

pub fn find_workspace_dir(cwd: &Path) -> &Path {
    cwd.ancestors()
        .find(|path| path.join(".jj").is_dir())
        .unwrap_or(cwd)
}

fn map_workspace_load_error(err: WorkspaceLoadError, user_wc_path: Option<&str>) -> CommandError {
    match err {
        WorkspaceLoadError::NoWorkspaceHere(wc_path) => {
            // Prefer user-specified path instead of absolute wc_path if any.
            let short_wc_path = user_wc_path.map_or(wc_path.as_ref(), Path::new);
            let message = format!(r#"There is no jj repo in "{}""#, short_wc_path.display());
            let git_dir = wc_path.join(".git");
            if git_dir.is_dir() {
                user_error(message).hinted(
                    "It looks like this is a git repo. You can create a jj repo backed by it by \
                     running this:
jj git init",
                )
            } else {
                user_error(message)
            }
        }
        WorkspaceLoadError::RepoDoesNotExist(repo_dir) => user_error(format!(
            "The repository directory at {} is missing. Was it moved?",
            repo_dir.display(),
        )),
        WorkspaceLoadError::StoreLoadError(err @ StoreLoadError::UnsupportedType { .. }) => {
            internal_error_with_message(
                "This version of the jj binary doesn't support this type of repo",
                err,
            )
        }
        WorkspaceLoadError::StoreLoadError(
            err @ (StoreLoadError::ReadError { .. } | StoreLoadError::Backend(_)),
        ) => internal_error_with_message("The repository appears broken or inaccessible", err),
        WorkspaceLoadError::StoreLoadError(StoreLoadError::Signing(err)) => user_error(err),
        WorkspaceLoadError::WorkingCopyState(err) => internal_error(err),
        WorkspaceLoadError::DecodeRepoPath(_) | WorkspaceLoadError::Path(_) => user_error(err),
    }
}

pub fn start_repo_transaction(
    repo: &Arc<ReadonlyRepo>,
    workspace_name: &WorkspaceName,
    string_args: &[String],
) -> Transaction {
    let mut tx = repo.start_transaction();
    tx.set_workspace_name(workspace_name);
    // TODO: Either do better shell-escaping here or store the values in some list
    // type (which we currently don't have).
    let shell_escape = |arg: &String| {
        if arg.as_bytes().iter().all(|b| {
            matches!(b,
                b'A'..=b'Z'
                | b'a'..=b'z'
                | b'0'..=b'9'
                | b','
                | b'-'
                | b'.'
                | b'/'
                | b':'
                | b'@'
                | b'_'
            )
        }) {
            arg.clone()
        } else {
            format!("'{}'", arg.replace('\'', "\\'"))
        }
    };
    let mut quoted_strings = vec!["jj".to_string()];
    quoted_strings.extend(string_args.iter().skip(1).map(shell_escape));
    tx.set_attribute("args".to_string(), quoted_strings.join(" "));
    tx
}

/// Check if the working copy is stale and reload the repo if the repo is ahead
/// of the working copy.
///
/// Returns Ok(None) if the workspace doesn't exist in the repo (presumably
/// because it was deleted).
async fn handle_stale_working_copy(
    locked_wc: &mut dyn LockedWorkingCopy,
    repo: Arc<ReadonlyRepo>,
    workspace_name: &WorkspaceName,
) -> Result<Option<(Arc<ReadonlyRepo>, Commit)>, SnapshotWorkingCopyError> {
    let get_wc_commit = |repo: &ReadonlyRepo| -> Result<Option<_>, _> {
        repo.view()
            .get_wc_commit_id(workspace_name)
            .map(|id| repo.store().get_commit(id))
            .transpose()
            .map_err(snapshot_command_error)
    };
    let Some(wc_commit) = get_wc_commit(&repo)? else {
        return Ok(None);
    };
    let old_op_id = locked_wc.old_operation_id().clone();
    match WorkingCopyFreshness::check_stale(locked_wc, &wc_commit, &repo).await {
        Ok(WorkingCopyFreshness::Fresh) => Ok(Some((repo, wc_commit))),
        Ok(WorkingCopyFreshness::Updated(wc_operation)) => {
            let repo = repo
                .reload_at(&wc_operation)
                .await
                .map_err(snapshot_command_error)?;
            if let Some(wc_commit) = get_wc_commit(&repo)? {
                Ok(Some((repo, wc_commit)))
            } else {
                Ok(None)
            }
        }
        Ok(WorkingCopyFreshness::WorkingCopyStale) => {
            Err(SnapshotWorkingCopyError::StaleWorkingCopy(
                user_error(format!(
                    "The working copy is stale (not updated since operation {}).",
                    short_operation_hash(&old_op_id)
                ))
                .hinted(
                    "Run `jj workspace update-stale` to update it.
See https://docs.jj-vcs.dev/latest/working-copy/#stale-working-copy \
                     for more information.",
                ),
            ))
        }
        Ok(WorkingCopyFreshness::SiblingOperation) => {
            Err(SnapshotWorkingCopyError::StaleWorkingCopy(
                internal_error(format!(
                    "The repo was loaded at operation {}, which seems to be a sibling of the \
                     working copy's operation {}",
                    short_operation_hash(repo.op_id()),
                    short_operation_hash(&old_op_id)
                ))
                .hinted(format!(
                    "Run `jj op integrate {}` to add the working copy's operation to the \
                     operation log.",
                    short_operation_hash(&old_op_id)
                )),
            ))
        }
        Err(OpStoreError::ObjectNotFound { .. }) => {
            Err(SnapshotWorkingCopyError::StaleWorkingCopy(
                user_error("Could not read working copy's operation.").hinted(
                    "Run `jj workspace update-stale` to recover.
See https://docs.jj-vcs.dev/latest/working-copy/#stale-working-copy \
                     for more information.",
                ),
            ))
        }
        Err(e) => Err(snapshot_command_error(e)),
    }
}

async fn update_stale_working_copy(
    mut locked_ws: LockedWorkspace<'_>,
    op_id: OperationId,
    stale_commit: &Commit,
    new_commit: &Commit,
) -> Result<CheckoutStats, CommandError> {
    // The same check as start_working_copy_mutation(), but with the stale
    // working-copy commit.
    if stale_commit.tree().tree_ids_and_labels()
        != locked_ws.locked_wc().old_tree().tree_ids_and_labels()
    {
        return Err(user_error("Concurrent working copy operation. Try again."));
    }
    let stats = locked_ws
        .locked_wc()
        .check_out(new_commit)
        .await
        .map_err(|err| {
            internal_error_with_message(
                format!("Failed to check out commit {}", new_commit.id().hex()),
                err,
            )
        })?;
    locked_ws.finish(op_id).await?;

    Ok(stats)
}

/// Prints a list of commits by the given summary template. The list may be
/// elided. Use this to show created, rewritten, or abandoned commits.
pub fn print_updated_commits<'a>(
    formatter: &mut dyn Formatter,
    template: &TemplateRenderer<Commit>,
    commits: impl IntoIterator<Item = &'a Commit>,
) -> io::Result<()> {
    let mut commits = commits.into_iter().fuse();
    for commit in commits.by_ref().take(10) {
        write!(formatter, "  ")?;
        template.format(commit, formatter)?;
        writeln!(formatter)?;
    }
    if commits.next().is_some() {
        writeln!(formatter, "  ...")?;
    }
    Ok(())
}

#[instrument(skip_all)]
pub fn print_conflicted_paths(
    conflicts: Vec<(RepoPathBuf, BackendResult<MergedTreeValue>)>,
    formatter: &mut dyn Formatter,
    workspace_command: &WorkspaceCommandHelper,
) -> Result<(), CommandError> {
    let formatted_paths = conflicts
        .iter()
        .map(|(path, _conflict)| workspace_command.format_file_path(path))
        .collect_vec();
    let max_path_len = formatted_paths.iter().map(|p| p.len()).max().unwrap_or(0);
    let formatted_paths = formatted_paths
        .into_iter()
        .map(|p| format!("{:width$}", p, width = max_path_len.min(32) + 3));

    for ((_, conflict), formatted_path) in std::iter::zip(conflicts, formatted_paths) {
        // TODO: Display the error for the path instead of failing the whole command if
        // `conflict` is an error?
        let conflict = conflict?.simplify();
        let sides = conflict.num_sides();
        let n_adds = conflict.adds().flatten().count();
        let deletions = sides - n_adds;

        let mut seen_objects = BTreeMap::new(); // Sort for consistency and easier testing
        if deletions > 0 {
            seen_objects.insert(
                format!(
                    // Starting with a number sorts this first
                    "{deletions} deletion{}",
                    if deletions > 1 { "s" } else { "" }
                ),
                "normal", // Deletions don't interfere with `jj resolve` or diff display
            );
        }
        // TODO: We might decide it's OK for `jj resolve` to ignore special files in the
        // `removes` of a conflict (see e.g. https://github.com/jj-vcs/jj/pull/978). In
        // that case, `conflict.removes` should be removed below.
        for term in itertools::chain(conflict.removes(), conflict.adds()).flatten() {
            seen_objects.insert(
                match term {
                    TreeValue::File {
                        executable: false, ..
                    } => continue,
                    TreeValue::File {
                        executable: true, ..
                    } => "an executable",
                    TreeValue::Symlink(_) => "a symlink",
                    TreeValue::Tree(_) => "a directory",
                    TreeValue::GitSubmodule(_) => "a git submodule",
                }
                .to_string(),
                "difficult",
            );
        }

        write!(formatter, "{formatted_path} ")?;
        {
            let mut formatter = formatter.labeled("conflict_description");
            let print_pair = |formatter: &mut dyn Formatter, (text, label): &(String, &str)| {
                write!(formatter.labeled(label), "{text}")
            };
            print_pair(
                *formatter,
                &(
                    format!("{sides}-sided"),
                    if sides > 2 { "difficult" } else { "normal" },
                ),
            )?;
            write!(formatter, " conflict")?;

            if !seen_objects.is_empty() {
                write!(formatter, " including ")?;
                let seen_objects = seen_objects.into_iter().collect_vec();
                match &seen_objects[..] {
                    [] => unreachable!(),
                    [only] => print_pair(*formatter, only)?,
                    [first, middle @ .., last] => {
                        print_pair(*formatter, first)?;
                        for pair in middle {
                            write!(formatter, ", ")?;
                            print_pair(*formatter, pair)?;
                        }
                        write!(formatter, " and ")?;
                        print_pair(*formatter, last)?;
                    }
                }
            }
        }
        writeln!(formatter)?;
    }
    Ok(())
}

/// Build human-readable messages explaining why the file was not tracked
fn build_untracked_reason_message(reason: &UntrackedReason) -> Option<String> {
    match reason {
        UntrackedReason::FileTooLarge { size, max_size } => {
            // Show both exact and human bytes sizes to avoid something
            // like '1.0MiB, maximum size allowed is ~1.0MiB'
            let size_approx = HumanByteSize(*size);
            let max_size_approx = HumanByteSize(*max_size);
            Some(format!(
                "{size_approx} ({size} bytes); the maximum size allowed is {max_size_approx} \
                 ({max_size} bytes)",
            ))
        }
        // Paths with UntrackedReason::FileNotAutoTracked shouldn't be warned about
        // every time we make a snapshot. These paths will be printed by
        // "jj status" instead.
        UntrackedReason::FileNotAutoTracked => None,
    }
}

/// Print a warning to the user, listing untracked files that he may care about
pub fn print_untracked_files(
    ui: &Ui,
    untracked_paths: &BTreeMap<RepoPathBuf, UntrackedReason>,
    path_converter: &RepoPathUiConverter,
) -> io::Result<()> {
    let mut untracked_paths = untracked_paths
        .iter()
        .filter_map(|(path, reason)| build_untracked_reason_message(reason).map(|m| (path, m)))
        .peekable();

    if untracked_paths.peek().is_some() {
        writeln!(ui.warning_default(), "Refused to snapshot some files:")?;
        let mut formatter = ui.stderr_formatter();
        for (path, message) in untracked_paths {
            let ui_path = path_converter.format_file_path(path);
            writeln!(formatter, "  {ui_path}: {message}")?;
        }
    }

    Ok(())
}

pub fn print_snapshot_stats(
    ui: &Ui,
    stats: &SnapshotStats,
    path_converter: &RepoPathUiConverter,
) -> io::Result<()> {
    print_untracked_files(ui, &stats.untracked_paths, path_converter)?;

    let large_files_sizes = stats
        .untracked_paths
        .values()
        .filter_map(|reason| match reason {
            UntrackedReason::FileTooLarge { size, .. } => Some(size),
            UntrackedReason::FileNotAutoTracked => None,
        });
    if let Some(size) = large_files_sizes.max() {
        print_large_file_hint(ui, *size, None)?;
    }
    Ok(())
}

/// Prints a hint about how to handle large files that were refused during
/// snapshot.
///
/// If `large_files` is provided, the hint will include file-track-specific
/// options like `--include-ignored`. Otherwise, it shows a simpler hint
/// suitable for general snapshot operations.
pub fn print_large_file_hint(
    ui: &Ui,
    max_size: u64,
    large_files: Option<&[String]>,
) -> io::Result<()> {
    let (command, extra) = large_files
        .map(|files| {
            // shlex::try_quote fails if the string contains a nul byte, which
            // shouldn't happen for file paths. Fall back to unquoted on error.
            let files_list = files
                .iter()
                .map(|s| shlex::try_quote(s).unwrap_or(s.into()))
                .join(" ");
            let command = format!("file track {files_list}");
            let extra = format!(
                r"
  * Run `jj file track --include-ignored {files_list}`
    This will track the file(s) regardless of size."
            );
            (command, extra)
        })
        .unwrap_or(("status".to_string(), String::new()));

    writedoc!(
        ui.hint_default(),
        r"
        This is to prevent large files from being added by accident. To fix this:
          * Add the file(s) to `.gitignore`
          * Run `jj config set --repo snapshot.max-new-file-size {max_size}`
            This will increase the maximum file size allowed for new files, in this repository only.
          * Run `jj --config snapshot.max-new-file-size={max_size} {command}`
            This will increase the maximum file size allowed for new files, for this command only.{extra}
        "
    )?;
    Ok(())
}

pub fn print_checkout_stats(
    ui: &Ui,
    stats: &CheckoutStats,
    new_commit: &Commit,
) -> Result<(), std::io::Error> {
    if stats.added_files > 0 || stats.updated_files > 0 || stats.removed_files > 0 {
        writeln!(
            ui.status(),
            "Added {} files, modified {} files, removed {} files",
            stats.added_files,
            stats.updated_files,
            stats.removed_files
        )?;
    }
    if stats.skipped_files != 0 {
        writeln!(
            ui.warning_default(),
            "{} of those updates were skipped because there were conflicting changes in the \
             working copy.",
            stats.skipped_files
        )?;
        writeln!(
            ui.hint_default(),
            "Inspect the changes compared to the intended target with `jj diff --from {}`.
Discard the conflicting changes with `jj restore --from {}`.",
            short_commit_hash(new_commit.id()),
            short_commit_hash(new_commit.id())
        )?;
    }
    Ok(())
}

/// Prints warning about explicit paths that don't match any of the tree
/// entries.
pub fn print_unmatched_explicit_paths<'a>(
    ui: &Ui,
    workspace_command: &WorkspaceCommandHelper,
    expression: &FilesetExpression,
    trees: impl IntoIterator<Item = &'a MergedTree>,
) -> io::Result<()> {
    let mut explicit_paths = expression.explicit_paths().collect_vec();
    for tree in trees {
        // TODO: propagate errors
        explicit_paths.retain(|&path| tree.path_value(path).block_on().unwrap().is_absent());
    }

    if !explicit_paths.is_empty() {
        let ui_paths = explicit_paths
            .iter()
            .map(|&path| workspace_command.format_file_path(path))
            .join(", ");
        writeln!(
            ui.warning_default(),
            "No matching entries for paths: {ui_paths}"
        )?;
    }

    Ok(())
}

pub async fn update_working_copy(
    repo: &Arc<ReadonlyRepo>,
    workspace: &mut Workspace,
    old_commit: Option<&Commit>,
    new_commit: &Commit,
) -> Result<CheckoutStats, CommandError> {
    let old_tree = old_commit.map(|commit| commit.tree());
    // TODO: CheckoutError::ConcurrentCheckout should probably just result in a
    // warning for most commands (but be an error for the checkout command)
    let stats = workspace
        .check_out(repo.op_id().clone(), old_tree.as_ref(), new_commit)
        .await
        .map_err(|err| {
            internal_error_with_message(
                format!("Failed to check out commit {}", new_commit.id().hex()),
                err,
            )
        })?;
    Ok(stats)
}

/// Returns the special remote name that should be ignored by default.
#[cfg_attr(not(feature = "git"), expect(unused_variables))]
pub fn default_ignored_remote_name(store: &Store) -> Option<&'static RemoteName> {
    #[cfg(feature = "git")]
    {
        use jj_lib::git;
        if git::get_git_backend(store).is_ok() {
            return Some(git::REMOTE_NAME_FOR_LOCAL_GIT_REPO);
        }
    }
    None
}

/// Whether or not the `bookmark` has any tracked remotes (i.e. is a tracking
/// local bookmark.)
pub fn has_tracked_remote_bookmarks(repo: &dyn Repo, bookmark: &RefName) -> bool {
    let remote_matcher = match default_ignored_remote_name(repo.store()) {
        Some(remote) => StringExpression::exact(remote).negated().to_matcher(),
        None => StringMatcher::all(),
    };
    repo.view()
        .remote_bookmarks_matching(&StringMatcher::exact(bookmark), &remote_matcher)
        .any(|(_, remote_ref)| remote_ref.is_tracked())
}

/// Whether or not the `tag` has any tracked remotes (i.e. is a tracking local
/// tag.)
pub fn has_tracked_remote_tags(repo: &dyn Repo, tag: &RefName) -> bool {
    let remote_matcher = match default_ignored_remote_name(repo.store()) {
        Some(remote) => StringExpression::exact(remote).negated().to_matcher(),
        None => StringMatcher::all(),
    };
    repo.view()
        .remote_tags_matching(&StringMatcher::exact(tag), &remote_matcher)
        .any(|(_, remote_ref)| remote_ref.is_tracked())
}

pub fn load_fileset_aliases(
    ui: &Ui,
    config: &StackedConfig,
) -> Result<FilesetAliasesMap, CommandError> {
    let table_name = ConfigNamePathBuf::from_iter(["fileset-aliases"]);
    load_aliases_map(ui, config, &table_name)
}

pub fn load_revset_aliases(
    ui: &Ui,
    config: &StackedConfig,
) -> Result<RevsetAliasesMap, CommandError> {
    let table_name = ConfigNamePathBuf::from_iter(["revset-aliases"]);
    let aliases_map = load_aliases_map(ui, config, &table_name)?;
    revset_util::warn_user_redefined_builtin(ui, config, &table_name)?;
    Ok(aliases_map)
}

pub fn load_template_aliases(
    ui: &Ui,
    config: &StackedConfig,
) -> Result<TemplateAliasesMap, CommandError> {
    let table_name = ConfigNamePathBuf::from_iter(["template-aliases"]);
    load_aliases_map(ui, config, &table_name)
}

/// Helper to reformat content of log-like commands.
#[derive(Clone, Debug)]
pub struct LogContentFormat {
    width: usize,
    word_wrap: bool,
}

impl LogContentFormat {
    /// Creates new formatting helper for the terminal.
    pub fn new(ui: &Ui, settings: &UserSettings) -> Result<Self, ConfigGetError> {
        Ok(Self {
            width: ui.term_width(),
            word_wrap: settings.get_bool("ui.log-word-wrap")?,
        })
    }

    /// Subtracts the given `width` and returns new formatting helper.
    #[must_use]
    pub fn sub_width(&self, width: usize) -> Self {
        Self {
            width: self.width.saturating_sub(width),
            word_wrap: self.word_wrap,
        }
    }

    /// Current width available to content.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Writes content which will optionally be wrapped at the current width.
    pub async fn write<E: From<io::Error>>(
        &self,
        formatter: &mut dyn Formatter,
        content_fn: impl AsyncFnOnce(&mut dyn Formatter) -> Result<(), E>,
    ) -> Result<(), E> {
        if self.word_wrap {
            let mut recorder = FormatRecorder::new(formatter.maybe_color());
            content_fn(&mut recorder).await?;
            text_util::write_wrapped(formatter, &recorder, self.width)?;
        } else {
            content_fn(formatter).await?;
        }
        Ok(())
    }
}

pub fn short_commit_hash(commit_id: &CommitId) -> String {
    format!("{commit_id:.12}")
}

pub fn short_change_hash(change_id: &ChangeId) -> String {
    format!("{change_id:.12}")
}

pub fn short_operation_hash(operation_id: &OperationId) -> String {
    format!("{operation_id:.12}")
}

/// Wrapper around a `DiffEditor` to conditionally start interactive session.
#[derive(Clone, Debug)]
pub enum DiffSelector {
    NonInteractive,
    Interactive(DiffEditor),
}

impl DiffSelector {
    pub fn is_interactive(&self) -> bool {
        matches!(self, Self::Interactive(_))
    }

    /// Restores diffs from the `right_tree` to the `left_tree` by using an
    /// interactive editor if enabled.
    ///
    /// Only files matching the `matcher` will be copied to the new tree.
    pub async fn select(
        &self,
        ui: &Ui,
        trees: Diff<&MergedTree>,
        tree_labels: Diff<String>,
        matcher: &dyn Matcher,
        format_instructions: impl FnOnce() -> String,
    ) -> Result<MergedTree, CommandError> {
        let selected_tree = restore_tree(
            trees.after,
            trees.before,
            tree_labels.after,
            tree_labels.before,
            matcher,
        )
        .await?;
        match self {
            Self::NonInteractive => Ok(selected_tree),
            Self::Interactive(editor) => {
                if selected_tree.tree_ids() == trees.before.tree_ids() {
                    writeln!(ui.warning_default(), "Empty diff - won't run diff editor.")?;
                    Ok(selected_tree)
                } else {
                    // edit_diff_external() is designed to edit the right tree,
                    // whereas we want to update the left tree. Unmatched paths
                    // shouldn't be based off the right tree.
                    Ok(editor
                        .edit(
                            Diff::new(trees.before, &selected_tree),
                            matcher,
                            format_instructions,
                        )
                        .await?)
                }
            }
        }
    }
}

// TODO: Delete in jj 0.43+
#[derive(Clone, Debug)]
pub(crate) struct RemoteBookmarkNamePattern {
    pub bookmark: StringPattern,
    pub remote: StringPattern,
}

impl FromStr for RemoteBookmarkNamePattern {
    type Err = String;

    fn from_str(src: &str) -> Result<Self, Self::Err> {
        // The kind prefix applies to both bookmark and remote fragments. It's
        // weird that unanchored patterns like substring:bookmark@remote is split
        // into two, but I can't think of a better syntax.
        // TODO: should we disable substring pattern? what if we added regex?
        let (maybe_kind, pat) = src
            .split_once(':')
            .map_or((None, src), |(kind, pat)| (Some(kind), pat));
        let to_pattern = |pat: &str| {
            if let Some(kind) = maybe_kind {
                StringPattern::from_str_kind(pat, kind).map_err(|err| err.to_string())
            } else {
                StringPattern::glob(pat).map_err(|err| err.to_string())
            }
        };
        // TODO: maybe reuse revset parser to handle bookmark/remote name containing @
        let (bookmark, remote) = pat.rsplit_once('@').ok_or_else(|| {
            "remote bookmark must be specified in bookmark@remote form".to_owned()
        })?;
        Ok(Self {
            bookmark: to_pattern(bookmark)?,
            remote: to_pattern(remote)?,
        })
    }
}

impl RemoteBookmarkNamePattern {
    pub fn as_exact(&self) -> Option<RemoteRefSymbol<'_>> {
        let bookmark = RefName::new(self.bookmark.as_exact()?);
        let remote = RemoteName::new(self.remote.as_exact()?);
        Some(bookmark.to_remote_symbol(remote))
    }
}

impl fmt::Display for RemoteBookmarkNamePattern {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // TODO: use revset::format_remote_symbol() if FromStr is migrated to
        // the revset parser.
        let Self { bookmark, remote } = self;
        write!(f, "{bookmark}@{remote}")
    }
}

/// Computes the location (new parents and new children) to place commits.
///
/// The `destination` argument is mutually exclusive to the `insert_after` and
/// `insert_before` arguments.
pub async fn compute_commit_location(
    ui: &Ui,
    workspace_command: &WorkspaceCommandHelper,
    destination: Option<&[RevisionArg]>,
    insert_after: Option<&[RevisionArg]>,
    insert_before: Option<&[RevisionArg]>,
    commit_type: &str,
) -> Result<(Vec<CommitId>, Vec<CommitId>), CommandError> {
    let resolve_revisions =
        async |revisions: Option<&[RevisionArg]>| -> Result<Option<Vec<CommitId>>, CommandError> {
            if let Some(revisions) = revisions {
                Ok(Some(
                    workspace_command
                        .resolve_revsets_ordered(ui, revisions)
                        .await?
                        .into_iter()
                        .collect_vec(),
                ))
            } else {
                Ok(None)
            }
        };
    let destination_commit_ids = resolve_revisions(destination).await?;
    let after_commit_ids = resolve_revisions(insert_after).await?;
    let before_commit_ids = resolve_revisions(insert_before).await?;

    let (new_parent_ids, new_child_ids) =
        match (destination_commit_ids, after_commit_ids, before_commit_ids) {
            (Some(destination_commit_ids), None, None) => (destination_commit_ids, vec![]),
            (None, Some(after_commit_ids), Some(before_commit_ids)) => {
                (after_commit_ids, before_commit_ids)
            }
            (None, Some(after_commit_ids), None) => {
                let new_child_ids = RevsetExpression::commits(after_commit_ids.clone())
                    .children()
                    .evaluate(workspace_command.repo().as_ref())?
                    .stream()
                    .try_collect()
                    .await?;

                (after_commit_ids, new_child_ids)
            }
            (None, None, Some(before_commit_ids)) => {
                let before_commits = try_join_all(
                    before_commit_ids
                        .iter()
                        .map(|id| workspace_command.repo().store().get_commit_async(id)),
                )
                .await?;
                // Not using `RevsetExpression::parents` here to persist the order of parents
                // specified in `before_commits`.
                let new_parent_ids = before_commits
                    .iter()
                    .flat_map(|commit| commit.parent_ids())
                    .unique()
                    .cloned()
                    .collect_vec();

                (new_parent_ids, before_commit_ids)
            }
            (Some(_), Some(_), _) | (Some(_), _, Some(_)) => {
                panic!("destination cannot be used with insert_after/insert_before")
            }
            (None, None, None) => {
                panic!("expected at least one of destination or insert_after/insert_before")
            }
        };

    if !new_child_ids.is_empty() {
        workspace_command
            .check_rewritable(new_child_ids.iter())
            .await?;
        ensure_no_commit_loop(
            workspace_command.repo().as_ref(),
            &RevsetExpression::commits(new_child_ids.clone()),
            &RevsetExpression::commits(new_parent_ids.clone()),
            commit_type,
        )
        .await?;
    }

    if new_parent_ids.is_empty() {
        return Err(user_error("No revisions found to use as parent"));
    }

    Ok((new_parent_ids, new_child_ids))
}

/// Ensure that there is no possible cycle between the potential children and
/// parents of the given commits.
async fn ensure_no_commit_loop(
    repo: &ReadonlyRepo,
    children_expression: &Arc<ResolvedRevsetExpression>,
    parents_expression: &Arc<ResolvedRevsetExpression>,
    commit_type: &str,
) -> Result<(), CommandError> {
    if let Some(commit_id) = children_expression
        .dag_range_to(parents_expression)
        .evaluate(repo)?
        .stream()
        .try_next()
        .await?
    {
        return Err(user_error(format!(
            "Refusing to create a loop: commit {} would be both an ancestor and a descendant of \
             the {commit_type}",
            short_commit_hash(&commit_id),
        )));
    }
    Ok(())
}

/// Jujutsu (An experimental VCS)
///
/// To get started, see the tutorial [`jj help -k tutorial`].
///
/// [`jj help -k tutorial`]:
///     https://docs.jj-vcs.dev/latest/tutorial/
#[derive(clap::Parser, Clone, Debug)]
#[command(name = "jj")]
pub struct Args {
    #[command(flatten)]
    pub global_args: GlobalArgs,
}

#[derive(clap::Args, Clone, Debug)]
#[command(next_help_heading = "Global Options")]
pub struct GlobalArgs {
    /// Path to repository to operate on
    ///
    /// By default, Jujutsu searches for the closest .jj/ directory in an
    /// ancestor of the current working directory.
    #[arg(long, short = 'R', global = true, value_hint = clap::ValueHint::DirPath)]
    pub repository: Option<String>,

    /// Don't snapshot the working copy, and don't update it
    ///
    /// By default, Jujutsu snapshots the working copy at the beginning of every
    /// command. The working copy is also updated at the end of the command,
    /// if the command modified the working-copy commit (`@`). If you want
    /// to avoid snapshotting the working copy and instead see a possibly
    /// stale working-copy commit, you can use `--ignore-working-copy`.
    /// This may be useful e.g. in a command prompt, especially if you have
    /// another process that commits the working copy.
    ///
    /// Loading the repository at a specific operation with `--at-operation`
    /// implies `--ignore-working-copy`.
    #[arg(long, global = true)]
    pub ignore_working_copy: bool,

    /// Run the command as usual but don't integrate any operations
    ///
    /// When this option is given, the operations will still be created as usual
    /// but they will not be integrated to the operation log. The working copy
    /// will also not be updated.
    ///
    /// The command will print the resulting operation ID. You can pass that to
    /// e.g. `jj --at-op` to inspect the resulting repo state, or you can pass
    /// it to `jj op restore` to restore the repo to that state. You can also
    /// pass the ID to `jj op integrate` to integrate the operation.
    ///
    /// Note that this does *not* prevent side effects outside the repo. For
    /// example, `jj git push --no-integrate-operation` will still perform the
    /// push.
    #[arg(long, global = true)]
    pub no_integrate_operation: bool,

    /// Allow rewriting immutable commits
    ///
    /// By default, Jujutsu prevents rewriting commits in the configured set of
    /// immutable commits. This option disables that check and lets you rewrite
    /// any commit but the root commit.
    ///
    /// This option only affects the check. It does not affect the
    /// `immutable_heads()` revset or the `immutable` template keyword.
    #[arg(long, global = true)]
    pub ignore_immutable: bool,

    /// Operation to load the repo at
    ///
    /// Operation to load the repo at. By default, Jujutsu loads the repo at the
    /// most recent operation, or at the merge of the divergent operations if
    /// any.
    ///
    /// You can use `--at-op=<operation ID>` to see what the repo looked like at
    /// an earlier operation. For example `jj --at-op=<operation ID> st` will
    /// show you what `jj st` would have shown you when the given operation had
    /// just finished. `--at-op=@` is pretty much the same as the default except
    /// that divergent operations will never be merged.
    ///
    /// Use `jj op log` to find the operation ID you want. Any unambiguous
    /// prefix of the operation ID is enough.
    ///
    /// When loading the repo at an earlier operation, the working copy will be
    /// ignored, as if `--ignore-working-copy` had been specified.
    ///
    /// It is possible to run mutating commands when loading the repo at an
    /// earlier operation. Doing that is equivalent to having run concurrent
    /// commands starting at the earlier operation. There's rarely a reason to
    /// do that, but it is possible.
    #[arg(long, visible_alias = "at-op", global = true)]
    #[arg(add = ArgValueCandidates::new(complete::operations))]
    pub at_operation: Option<String>,

    /// Enable debug logging
    #[arg(long, global = true)]
    pub debug: bool,

    #[command(flatten)]
    pub early_args: EarlyArgs,
}

#[derive(clap::Args, Clone, Debug)]
pub struct EarlyArgs {
    /// When to colorize output
    #[arg(long, value_name = "WHEN", global = true)]
    pub color: Option<ColorChoice>,

    /// Silence non-primary command output
    ///
    /// For example, `jj file list` will still list files, but it won't tell
    /// you if the working copy was snapshotted or if descendants were rebased.
    ///
    /// Warnings and errors will still be printed.
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    // Parsing with ignore_errors will crash if this is bool, so use
    // Option<bool>.
    pub quiet: Option<bool>,

    /// Disable the pager
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    // Parsing with ignore_errors will crash if this is bool, so use
    // Option<bool>.
    pub no_pager: Option<bool>,

    /// Additional configuration options (can be repeated)
    ///
    /// The name should be specified as TOML dotted keys. The value should be
    /// specified as a TOML expression. If string value isn't enclosed by any
    /// TOML constructs (such as array notation), quotes can be omitted.
    #[arg(long, value_name = "NAME=VALUE", global = true)]
    #[arg(add = ArgValueCompleter::new(complete::leaf_config_key_value))]
    pub config: Vec<String>,

    /// Additional configuration files (can be repeated)
    #[arg(long, value_name = "PATH", global = true, value_hint = clap::ValueHint::FilePath)]
    pub config_file: Vec<String>,
}

impl EarlyArgs {
    pub(crate) fn merged_config_args(&self, matches: &ArgMatches) -> Vec<(ConfigArgKind, &str)> {
        merge_args_with(
            matches,
            &[("config", &self.config), ("config_file", &self.config_file)],
            |id, value| match id {
                "config" => (ConfigArgKind::Item, value.as_ref()),
                "config_file" => (ConfigArgKind::File, value.as_ref()),
                _ => unreachable!("unexpected id {id:?}"),
            },
        )
    }

    fn has_config_args(&self) -> bool {
        !self.config.is_empty() || !self.config_file.is_empty()
    }
}

/// Wrapper around revset expression argument.
///
/// An empty string is rejected early by the CLI value parser, but it's still
/// allowed to construct an empty `RevisionArg` from a config value for
/// example. An empty expression will be rejected by the revset parser.
#[derive(Clone, Debug)]
pub struct RevisionArg(Cow<'static, str>);

impl RevisionArg {
    /// The working-copy symbol, which is the default of the most commands.
    pub const AT: Self = Self(Cow::Borrowed("@"));
}

impl From<String> for RevisionArg {
    fn from(s: String) -> Self {
        Self(s.into())
    }
}

impl AsRef<str> for RevisionArg {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for RevisionArg {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl ValueParserFactory for RevisionArg {
    type Parser = MapValueParser<NonEmptyStringValueParser, fn(String) -> Self>;

    fn value_parser() -> Self::Parser {
        NonEmptyStringValueParser::new().map(Self::from)
    }
}

/// Merges multiple clap args in order of appearance.
///
/// The `id_values` is a list of `(id, values)` pairs, where `id` is the name of
/// the clap `Arg`, and `values` are the parsed values for that arg. The
/// `convert` function transforms each `(id, value)` pair to e.g. an enum.
///
/// This is a workaround for <https://github.com/clap-rs/clap/issues/3146>.
pub fn merge_args_with<'k, 'v, T, U>(
    matches: &ArgMatches,
    id_values: &[(&'k str, &'v [T])],
    mut convert: impl FnMut(&'k str, &'v T) -> U,
) -> Vec<U> {
    let mut pos_values: Vec<(usize, U)> = Vec::new();
    for (id, values) in id_values {
        pos_values.extend(itertools::zip_eq(
            matches.indices_of(id).into_iter().flatten(),
            values.iter().map(|v| convert(id, v)),
        ));
    }
    pos_values.sort_unstable_by_key(|&(pos, _)| pos);
    pos_values.into_iter().map(|(_, value)| value).collect()
}

fn resolve_default_command(
    ui: &Ui,
    config: &StackedConfig,
    app: &Command,
    mut string_args: Vec<String>,
) -> Result<Vec<String>, CommandError> {
    const PRIORITY_FLAGS: &[&str] = &["--help", "-h", "--version", "-V"];

    let has_priority_flag = string_args
        .iter()
        .any(|arg| PRIORITY_FLAGS.contains(&arg.as_str()));
    if has_priority_flag {
        return Ok(string_args);
    }

    let app_clone = app
        .clone()
        .allow_external_subcommands(true)
        .ignore_errors(true);
    let matches = app_clone.try_get_matches_from(&string_args).ok();

    if let Some(matches) = matches
        && matches.subcommand_name().is_none()
    {
        // Try loading as either a string or an array.
        // Only use `.optional()?` on the latter call to `config.get` - if it
        // was used on both, the type error from the first check would return
        // early.
        let default_command = if let Ok(string) = config.get::<String>("ui.default-command") {
            // Warn when the user has misconfigured their default command as
            // "log -n 5" instead of ["log", "-n", "5"]
            if string.contains(' ') {
                let elements: ConfigValue = string.split_whitespace().collect();
                writeln!(
                    ui.warning_default(),
                    "To include flags/arguments in `ui.default-command`, use an array instead of \
                     a string: `ui.default-command = {elements}`"
                )?;
            }

            vec![string]
        } else if let Some(array) = config.get::<Vec<String>>("ui.default-command").optional()? {
            array
        } else {
            writeln!(
                ui.hint_default(),
                "Use `jj -h` for a list of available commands."
            )?;
            writeln!(
                ui.hint_no_heading(),
                "Run `jj config set --user ui.default-command log` to disable this message."
            )?;

            vec!["log".to_string()]
        };

        // Insert the default command directly after the path to the binary.
        string_args.splice(1..1, default_command);
    }
    Ok(string_args)
}

fn resolve_aliases(
    ui: &Ui,
    config: &StackedConfig,
    app: &Command,
    mut string_args: Vec<String>,
) -> Result<Vec<String>, CommandError> {
    let defined_aliases: HashSet<_> = config.table_keys("aliases").collect();
    let mut resolved_aliases = HashSet::new();
    let mut real_commands = HashSet::new();
    for command in app.get_subcommands() {
        real_commands.insert(command.get_name());
        for alias in command.get_all_aliases() {
            real_commands.insert(alias);
        }
    }
    for alias in defined_aliases.intersection(&real_commands).sorted() {
        writeln!(
            ui.warning_default(),
            "Cannot define an alias that overrides the built-in command '{alias}'"
        )?;
    }

    loop {
        let app_clone = app.clone().allow_external_subcommands(true);
        let matches = app_clone.try_get_matches_from(&string_args).ok();
        if let Some((command_name, submatches)) = matches.as_ref().and_then(|m| m.subcommand())
            && !real_commands.contains(command_name)
        {
            let alias_name = command_name.to_string();
            let alias_args = submatches
                .get_many::<OsString>("")
                .unwrap_or_default()
                .map(|arg| arg.to_str().unwrap().to_string())
                .collect_vec();
            if resolved_aliases.contains(&*alias_name) {
                return Err(user_error(format!(
                    "Recursive alias definition involving `{alias_name}`"
                )));
            }
            if let Some(&alias_name) = defined_aliases.get(&*alias_name) {
                let alias_definition: Vec<String> = config.get(["aliases", alias_name])?;
                assert!(string_args.ends_with(&alias_args));
                string_args.truncate(string_args.len() - 1 - alias_args.len());
                string_args.extend(alias_definition);
                string_args.extend_from_slice(&alias_args);
                resolved_aliases.insert(alias_name);
                continue;
            } else {
                // Not a real command and not an alias, so return what we've resolved so far
                return Ok(string_args);
            }
        }
        // No more alias commands, or hit unknown option
        return Ok(string_args);
    }
}

/// Parse args that must be interpreted early, e.g. before printing help.
fn parse_early_args(
    app: &Command,
    args: &[String],
) -> Result<(EarlyArgs, Vec<ConfigLayer>), CommandError> {
    // ignore_errors() bypasses errors like missing subcommand
    let early_matches = app
        .clone()
        .disable_version_flag(true)
        // Do not emit DisplayHelp error
        .disable_help_flag(true)
        // Do not stop parsing at -h/--help
        .arg(
            clap::Arg::new("help")
                .short('h')
                .long("help")
                .global(true)
                .action(ArgAction::Count),
        )
        .ignore_errors(true)
        .try_get_matches_from(args)?;
    let args = EarlyArgs::from_arg_matches(&early_matches).unwrap();

    let mut config_layers = parse_config_args(&args.merged_config_args(&early_matches))?;
    // Command arguments overrides any other configuration including the
    // variables loaded from --config* arguments.
    let mut layer = ConfigLayer::empty(ConfigSource::CommandArg);
    if let Some(choice) = args.color {
        layer.set_value("ui.color", choice.to_string()).unwrap();
    }
    if args.quiet.unwrap_or_default() {
        layer.set_value("ui.quiet", true).unwrap();
    }
    if args.no_pager.unwrap_or_default() {
        layer.set_value("ui.paginate", "never").unwrap();
    }
    if !layer.is_empty() {
        config_layers.push(layer);
    }
    Ok((args, config_layers))
}

fn handle_shell_completion(
    ui: &Ui,
    app: &Command,
    config: &StackedConfig,
    cwd: &Path,
) -> Result<(), CommandError> {
    let mut orig_args = env::args_os();

    let mut args = vec![];
    // Take the first two arguments as is, they must be passed to clap_complete
    // without any changes. They are usually "jj --".
    args.extend(orig_args.by_ref().take(2));

    // Make sure aliases are expanded before passing them to clap_complete. We
    // skip the first two args ("jj" and "--") for alias resolution, then we
    // stitch the args back together, like clap_complete expects them.
    if orig_args.len() > 0 {
        let complete_index: Option<usize> = env::var("_CLAP_COMPLETE_INDEX")
            .ok()
            .and_then(|s| s.parse().ok());
        let resolved_aliases = if let Some(index) = complete_index {
            // As of clap_complete 4.5.38, zsh completion script doesn't pad an
            // empty arg at the complete position. If the args doesn't include a
            // command name, the default command would be expanded at that
            // position. Therefore, no other command names would be suggested.
            let pad_len = usize::saturating_sub(index + 1, orig_args.len());
            let padded_args = orig_args
                .by_ref()
                .chain(std::iter::repeat_n(OsString::new(), pad_len));

            // Expand aliases left of the completion index.
            let mut expanded_args =
                expand_args_for_completion(ui, app, padded_args.take(index + 1), config)?;

            // Adjust env var to compensate for shift of the completion point in the
            // expanded command line.
            // SAFETY: Program is running single-threaded at this point.
            unsafe {
                env::set_var(
                    "_CLAP_COMPLETE_INDEX",
                    (expanded_args.len() - 1).to_string(),
                );
            }

            // Remove extra padding again to align with clap_complete's expectations for
            // zsh.
            let split_off_padding = expanded_args.split_off(expanded_args.len() - pad_len);
            assert!(
                split_off_padding.iter().all(|s| s.is_empty()),
                "split-off padding should only consist of empty strings but was \
                 {split_off_padding:?}",
            );

            // Append the remaining arguments to the right of the completion point.
            expanded_args.extend(to_string_args(orig_args)?);
            expanded_args
        } else {
            expand_args_for_completion(ui, app, orig_args, config)?
        };
        args.extend(resolved_aliases.into_iter().map(OsString::from));
    }
    let ran_completion = clap_complete::CompleteEnv::with_factory(|| {
        let mut app = app.clone();
        // Dynamic completer can produce completion for hidden aliases, so we
        // can remove short subcommand names from the completion candidates.
        hide_short_subcommand_aliases(&mut app);
        // for completing aliases
        app.allow_external_subcommands(true)
    })
    .try_complete(args.iter(), Some(cwd))?;
    assert!(
        ran_completion,
        "This function should not be called without the COMPLETE variable set."
    );
    Ok(())
}

/// Removes prefix command names (e.g. "c" for "create") from visible aliases,
/// and adds them to (hidden) aliases.
fn hide_short_subcommand_aliases(cmd: &mut Command) {
    for cmd in cmd.get_subcommands_mut() {
        hide_short_subcommand_aliases(cmd);
    }
    let (short_aliases, new_visible_aliases) = cmd
        .get_visible_aliases()
        .map(|name| name.to_owned())
        .partition::<Vec<_>, _>(|name| cmd.get_name().starts_with(name));
    if short_aliases.is_empty() {
        return;
    }
    *cmd = mem::take(cmd)
        // clear existing visible aliases and add new
        .visible_alias(None)
        .visible_aliases(new_visible_aliases)
        // add to hidden aliases
        .aliases(short_aliases);
}

pub fn expand_args(
    ui: &Ui,
    app: &Command,
    args_os: impl IntoIterator<Item = OsString>,
    config: &StackedConfig,
) -> Result<Vec<String>, CommandError> {
    let string_args = to_string_args(args_os)?;
    let string_args = resolve_default_command(ui, config, app, string_args)?;
    resolve_aliases(ui, config, app, string_args)
}

fn expand_args_for_completion(
    ui: &Ui,
    app: &Command,
    args_os: impl IntoIterator<Item = OsString>,
    config: &StackedConfig,
) -> Result<Vec<String>, CommandError> {
    let string_args = to_string_args(args_os)?;

    // If a subcommand has been given, including the potentially incomplete argument
    // that is being completed, the default command is not resolved and the
    // completion candidates for the subcommand are prioritized.
    let mut string_args = resolve_default_command(ui, config, app, string_args)?;

    // Resolution of subcommand aliases must not consider the argument that is being
    // completed.
    let cursor_arg = string_args.pop();
    let mut resolved_args = resolve_aliases(ui, config, app, string_args)?;
    resolved_args.extend(cursor_arg);
    Ok(resolved_args)
}

fn to_string_args(
    args_os: impl IntoIterator<Item = OsString>,
) -> Result<Vec<String>, CommandError> {
    args_os
        .into_iter()
        .map(|arg_os| {
            arg_os
                .into_string()
                .map_err(|_| cli_error("Non-UTF-8 argument"))
        })
        .collect()
}

fn parse_args(app: &Command, string_args: &[String]) -> Result<(ArgMatches, Args), clap::Error> {
    let matches = app
        .clone()
        .arg_required_else_help(true)
        .subcommand_required(true)
        .try_get_matches_from(string_args)?;
    let args = Args::from_arg_matches(&matches).unwrap();
    Ok((matches, args))
}

fn command_name(mut matches: &ArgMatches) -> String {
    let mut command = String::new();
    while let Some((subcommand, new_matches)) = matches.subcommand() {
        if !command.is_empty() {
            command.push(' ');
        }
        command.push_str(subcommand);
        matches = new_matches;
    }
    command
}

pub fn format_template<C: Clone>(ui: &Ui, arg: &C, template: &TemplateRenderer<C>) -> String {
    let mut output = vec![];
    template
        .format(arg, ui.new_formatter(&mut output).as_mut())
        .expect("write() to vec backed formatter should never fail");
    // Template output is usually UTF-8, but it can contain file content.
    output.into_string_lossy()
}

// Like `BoxFuture<_>`, but doesn't require `Send`.
type BoxedCliDispatchFuture<'a> = Pin<Box<dyn Future<Output = Result<(), CommandError>> + 'a>>;
pub type BoxedAsyncCliDispatch<'a> = Box<dyn AsyncCliDispatch + 'a>;
type BoxedAsyncCliDispatchHook<'a> = Box<dyn AsyncCliDispatchHook + 'a>;

/// Object-safe trait for async command dispatch function.
pub trait AsyncCliDispatch {
    fn call<'a>(
        self: Box<Self>,
        ui: &'a mut Ui,
        command_helper: &'a CommandHelper,
    ) -> BoxedCliDispatchFuture<'a>
    where
        Self: 'a;
}

/// Object-safe trait for async command dispatch hook function.
trait AsyncCliDispatchHook {
    fn call<'a>(
        self: Box<Self>,
        ui: &'a mut Ui,
        command_helper: &'a CommandHelper,
        old_dispatch: BoxedAsyncCliDispatch<'a>,
    ) -> BoxedCliDispatchFuture<'a>
    where
        Self: 'a;
}

/// Object-safe wrapper for async command dispatch function.
struct AsyncCliDispatchFn<F>(F);

impl<F> AsyncCliDispatch for AsyncCliDispatchFn<F>
where
    F: AsyncFnOnce(&mut Ui, &CommandHelper) -> Result<(), CommandError>,
{
    fn call<'a>(
        self: Box<Self>,
        ui: &'a mut Ui,
        command_helper: &'a CommandHelper,
    ) -> BoxedCliDispatchFuture<'a>
    where
        Self: 'a,
    {
        Box::pin((self.0)(ui, command_helper))
    }
}

/// Object-safe wrapper for async command dispatch hook function.
struct AsyncCliDispatchHookFn<F>(F);

impl<F> AsyncCliDispatchHook for AsyncCliDispatchHookFn<F>
where
    F: AsyncFnOnce(&mut Ui, &CommandHelper, BoxedAsyncCliDispatch<'_>) -> Result<(), CommandError>,
{
    fn call<'a>(
        self: Box<Self>,
        ui: &'a mut Ui,
        command_helper: &'a CommandHelper,
        old_dispatch: BoxedAsyncCliDispatch<'a>,
    ) -> BoxedCliDispatchFuture<'a>
    where
        Self: 'a,
    {
        Box::pin((self.0)(ui, command_helper, old_dispatch))
    }
}

/// CLI command builder and runner.
#[must_use]
pub struct CliRunner<'a> {
    tracing_subscription: TracingSubscription,
    app: Command,
    config_layers: Vec<ConfigLayer>,
    config_migrations: Vec<ConfigMigrationRule>,
    store_factories: StoreFactories,
    working_copy_factories: WorkingCopyFactories,
    workspace_loader_factory: Box<dyn WorkspaceLoaderFactory>,
    revset_extensions: RevsetExtensions,
    commit_template_extensions: Vec<Arc<dyn CommitTemplateLanguageExtension>>,
    operation_template_extensions: Vec<Arc<dyn OperationTemplateLanguageExtension>>,
    dispatch: BoxedAsyncCliDispatch<'a>,
    dispatch_hooks: Vec<BoxedAsyncCliDispatchHook<'a>>,
    process_global_args_fns: Vec<ProcessGlobalArgsFn<'a>>,
}

type ProcessGlobalArgsFn<'a> =
    Box<dyn FnOnce(&mut Ui, &ArgMatches) -> Result<(), CommandError> + 'a>;

impl<'a> CliRunner<'a> {
    /// Initializes CLI environment and returns a builder. This should be called
    /// as early as possible.
    pub fn init() -> Self {
        let tracing_subscription = TracingSubscription::init();
        crate::cleanup_guard::init();
        Self {
            tracing_subscription,
            app: crate::commands::default_app(),
            config_layers: crate::config::default_config_layers(),
            config_migrations: crate::config::default_config_migrations(),
            store_factories: StoreFactories::default(),
            working_copy_factories: default_working_copy_factories(),
            workspace_loader_factory: Box::new(DefaultWorkspaceLoaderFactory),
            revset_extensions: Default::default(),
            commit_template_extensions: vec![],
            operation_template_extensions: vec![],
            dispatch: Box::new(AsyncCliDispatchFn(crate::commands::run_command)),
            dispatch_hooks: vec![],
            process_global_args_fns: vec![],
        }
    }

    /// Set the name of the CLI application to be displayed in help messages.
    pub fn name(mut self, name: &str) -> Self {
        self.app = self.app.name(name.to_string());
        self
    }

    /// Set the about message to be displayed in help messages.
    pub fn about(mut self, about: &str) -> Self {
        self.app = self.app.about(about.to_string());
        self
    }

    /// Set the version to be displayed by `jj version`.
    pub fn version(mut self, version: &str) -> Self {
        self.app = self.app.version(version.to_string());
        self
    }

    /// Adds default configs in addition to the normal defaults.
    ///
    /// The `layer.source` must be `Default`. Other sources such as `User` would
    /// be replaced by loaded configuration.
    pub fn add_extra_config(mut self, layer: ConfigLayer) -> Self {
        assert_eq!(layer.source, ConfigSource::Default);
        self.config_layers.push(layer);
        self
    }

    /// Adds config migration rule in addition to the default rules.
    pub fn add_extra_config_migration(mut self, rule: ConfigMigrationRule) -> Self {
        self.config_migrations.push(rule);
        self
    }

    /// Adds `StoreFactories` to be used.
    pub fn add_store_factories(mut self, store_factories: StoreFactories) -> Self {
        self.store_factories.merge(store_factories);
        self
    }

    /// Adds working copy factories to be used.
    pub fn add_working_copy_factories(
        mut self,
        working_copy_factories: WorkingCopyFactories,
    ) -> Self {
        merge_factories_map(&mut self.working_copy_factories, working_copy_factories);
        self
    }

    pub fn set_workspace_loader_factory(
        mut self,
        workspace_loader_factory: Box<dyn WorkspaceLoaderFactory>,
    ) -> Self {
        self.workspace_loader_factory = workspace_loader_factory;
        self
    }

    pub fn add_symbol_resolver_extension(
        mut self,
        symbol_resolver: Box<dyn SymbolResolverExtension>,
    ) -> Self {
        self.revset_extensions.add_symbol_resolver(symbol_resolver);
        self
    }

    pub fn add_revset_function_extension(
        mut self,
        name: &'static str,
        func: RevsetFunction,
    ) -> Self {
        self.revset_extensions.add_custom_function(name, func);
        self
    }

    pub fn add_commit_template_extension(
        mut self,
        commit_template_extension: Box<dyn CommitTemplateLanguageExtension>,
    ) -> Self {
        self.commit_template_extensions
            .push(commit_template_extension.into());
        self
    }

    pub fn add_operation_template_extension(
        mut self,
        operation_template_extension: Box<dyn OperationTemplateLanguageExtension>,
    ) -> Self {
        self.operation_template_extensions
            .push(operation_template_extension.into());
        self
    }

    /// Add a hook that gets called when it's time to run the command. It is
    /// the hook's responsibility to call the given inner dispatch function to
    /// run the command.
    pub fn add_dispatch_hook<F>(mut self, dispatch_hook_fn: F) -> Self
    where
        F: AsyncFnOnce(&mut Ui, &CommandHelper, BoxedAsyncCliDispatch) -> Result<(), CommandError>
            + 'a,
    {
        self.dispatch_hooks
            .push(Box::new(AsyncCliDispatchHookFn(dispatch_hook_fn)));
        self
    }

    /// Registers new subcommands in addition to the default ones.
    pub fn add_subcommand<C, F>(mut self, custom_dispatch_fn: F) -> Self
    where
        C: clap::Subcommand,
        F: AsyncFnOnce(&mut Ui, &CommandHelper, C) -> Result<(), CommandError> + 'a,
    {
        let old_dispatch = self.dispatch;
        let new_dispatch_fn =
            async move |ui: &mut Ui, command_helper: &CommandHelper| match C::from_arg_matches(
                command_helper.matches(),
            ) {
                Ok(command) => custom_dispatch_fn(ui, command_helper, command).await,
                Err(_) => old_dispatch.call(ui, command_helper).await,
            };
        self.app = C::augment_subcommands(self.app);
        self.dispatch = Box::new(AsyncCliDispatchFn(new_dispatch_fn));
        self
    }

    /// Registers new global arguments in addition to the default ones.
    pub fn add_global_args<A, F>(mut self, process_before: F) -> Self
    where
        A: clap::Args,
        F: FnOnce(&mut Ui, A) -> Result<(), CommandError> + 'a,
    {
        let process_global_args_fn = move |ui: &mut Ui, matches: &ArgMatches| {
            let custom_args = A::from_arg_matches(matches).unwrap();
            process_before(ui, custom_args)
        };
        self.app = A::augment_args(self.app);
        self.process_global_args_fns
            .push(Box::new(process_global_args_fn));
        self
    }

    #[instrument(skip_all)]
    async fn run_internal(
        self,
        ui: &mut Ui,
        mut raw_config: RawConfig,
    ) -> Result<(), CommandError> {
        // `cwd` is canonicalized for consistency with `Workspace::workspace_root()` and
        // to easily compute relative paths between them.
        let cwd = env::current_dir()
            .and_then(dunce::canonicalize)
            .map_err(|_| {
                user_error("Could not determine current directory").hinted(
                    "Did you update to a commit where the directory doesn't exist or can't be \
                     accessed?",
                )
            })?;
        let mut config_env = ConfigEnv::from_environment();
        let mut last_config_migration_descriptions = Vec::new();
        let mut migrate_config = |config: &mut StackedConfig| -> Result<(), CommandError> {
            last_config_migration_descriptions =
                jj_lib::config::migrate(config, &self.config_migrations)?;
            Ok(())
        };

        // Initial load: user, repo, and workspace-level configs for
        // alias/default-command resolution
        // Use cwd-relative workspace configs to resolve default command and
        // aliases. WorkspaceLoader::init() won't do any heavy lifting other
        // than the path resolution.
        let maybe_cwd_workspace_loader = self
            .workspace_loader_factory
            .create(find_workspace_dir(&cwd))
            .map_err(|err| map_workspace_load_error(err, Some(".")));
        config_env.reload_user_config(&mut raw_config)?;
        if let Ok(loader) = &maybe_cwd_workspace_loader {
            config_env.reset_repo_path(loader.repo_path());
            config_env.reload_repo_config(ui, &mut raw_config)?;
            config_env.reset_workspace_path(loader.workspace_root());
            config_env.reload_workspace_config(ui, &mut raw_config)?;
        }
        let mut config = config_env.resolve_config(&raw_config)?;
        migrate_config(&mut config)?;
        ui.reset(&config)?;

        if env::var_os("COMPLETE").is_some_and(|v| !v.is_empty() && v != "0") {
            return handle_shell_completion(&Ui::null(), &self.app, &config, &cwd);
        }

        let string_args = expand_args(ui, &self.app, env::args_os(), &config)?;
        let (args, config_layers) = parse_early_args(&self.app, &string_args)?;
        if !config_layers.is_empty() {
            raw_config.as_mut().extend_layers(config_layers);
            config = config_env.resolve_config(&raw_config)?;
            migrate_config(&mut config)?;
            ui.reset(&config)?;
        }

        if args.has_config_args() {
            warn_if_args_mismatch(ui, &self.app, &config, &string_args)?;
        }

        let (matches, args) = parse_args(&self.app, &string_args)
            .map_err(|err| map_clap_cli_error(err, ui, &config))?;
        if args.global_args.debug {
            // TODO: set up debug logging as early as possible
            self.tracing_subscription.enable_debug_logging()?;
        }
        for process_global_args_fn in self.process_global_args_fns {
            process_global_args_fn(ui, &matches)?;
        }
        config_env.set_command_name(command_name(&matches));

        let maybe_workspace_loader = if let Some(path) = &args.global_args.repository {
            // TODO: maybe path should be canonicalized by WorkspaceLoader?
            let abs_path = cwd.join(path);
            let abs_path = dunce::canonicalize(&abs_path).unwrap_or(abs_path);
            // Invalid -R path is an error. No need to proceed.
            let loader = self
                .workspace_loader_factory
                .create(&abs_path)
                .map_err(|err| map_workspace_load_error(err, Some(path)))?;
            config_env.reset_repo_path(loader.repo_path());
            config_env.reload_repo_config(ui, &mut raw_config)?;
            config_env.reset_workspace_path(loader.workspace_root());
            config_env.reload_workspace_config(ui, &mut raw_config)?;
            Ok(loader)
        } else {
            maybe_cwd_workspace_loader
        };

        // Apply workspace configs, --config arguments, and --when.commands.
        config = config_env.resolve_config(&raw_config)?;
        migrate_config(&mut config)?;
        ui.reset(&config)?;

        // Print only the last migration messages to omit duplicates.
        for (source, desc) in &last_config_migration_descriptions {
            let source_str = match source {
                ConfigSource::Default => "default-provided",
                ConfigSource::EnvBase | ConfigSource::EnvOverrides => "environment-provided",
                ConfigSource::User => "user-level",
                ConfigSource::Repo => "repo-level",
                ConfigSource::Workspace => "workspace-level",
                ConfigSource::CommandArg => "CLI-provided",
            };
            writeln!(
                ui.warning_default(),
                "Deprecated {source_str} config: {desc}"
            )?;
        }

        if args.global_args.repository.is_some() {
            warn_if_args_mismatch(ui, &self.app, &config, &string_args)?;
        }

        let settings = UserSettings::from_config(config)?;
        let command_helper_data = CommandHelperData {
            app: self.app,
            cwd,
            string_args,
            matches,
            global_args: args.global_args,
            config_env,
            config_migrations: self.config_migrations,
            raw_config,
            settings,
            revset_extensions: self.revset_extensions.into(),
            commit_template_extensions: self.commit_template_extensions,
            operation_template_extensions: self.operation_template_extensions,
            maybe_workspace_loader,
            store_factories: self.store_factories,
            working_copy_factories: self.working_copy_factories,
            workspace_loader_factory: self.workspace_loader_factory,
        };
        let command_helper = CommandHelper {
            data: Rc::new(command_helper_data),
        };
        let dispatch =
            self.dispatch_hooks
                .into_iter()
                .fold(self.dispatch, |old_dispatch, dispatch_hook| {
                    let f = async move |ui: &mut Ui, command_helper: &CommandHelper| {
                        dispatch_hook.call(ui, command_helper, old_dispatch).await
                    };
                    Box::new(AsyncCliDispatchFn(f))
                });
        dispatch.call(ui, &command_helper).await
    }

    #[must_use]
    #[instrument(skip(self))]
    pub fn run(mut self) -> u8 {
        // Tell crossterm to ignore NO_COLOR (we check it ourselves)
        crossterm::style::force_color_output(true);
        let config = config_from_environment(self.config_layers.drain(..));
        // Set up ui assuming the default config has no conditional variables.
        // If it had, the configuration will be fixed by the next ui.reset().
        let mut ui = Ui::with_config(config.as_ref())
            .expect("default config should be valid, env vars are stringly typed");
        let result = self.run_internal(&mut ui, config).block_on();
        let exit_code = handle_command_result(&mut ui, result);
        ui.finalize_pager();
        exit_code
    }
}

fn map_clap_cli_error(err: clap::Error, ui: &Ui, config: &StackedConfig) -> CommandError {
    if let Some(ContextValue::String(cmd)) = err.get(ContextKind::InvalidSubcommand) {
        let remove_useless_error_context = |mut err: clap::Error| {
            // Clap suggests unhelpful subcommands, e.g. `config` for `clone`.
            // We don't want suggestions when we know this isn't a misspelling.
            err.remove(ContextKind::SuggestedSubcommand);
            err.remove(ContextKind::Suggested); // Remove an empty line
            err.remove(ContextKind::Usage); // Also unhelpful for these errors.
            err
        };
        match cmd.as_str() {
            // git commands that a brand-new user might type during their first
            // experiments with `jj`
            "clone" | "init" => {
                let cmd = cmd.clone();
                return CommandError::from(remove_useless_error_context(err))
                    .hinted(format!(
                        "You probably want `jj git {cmd}`. See also `jj help git`."
                    ))
                    .hinted(format!(
                        r#"You can configure `aliases.{cmd} = ["git", "{cmd}"]` if you want `jj {cmd}` to work and always use the Git backend."#
                    ));
            }
            "amend" => {
                return CommandError::from(remove_useless_error_context(err))
                    .hinted(
                        r#"You probably want `jj squash`. You can configure `aliases.amend = ["squash"]` if you want `jj amend` to work."#);
            }
            _ => {}
        }
    }
    if let (Some(ContextValue::String(arg)), Some(ContextValue::String(value))) = (
        err.get(ContextKind::InvalidArg),
        err.get(ContextKind::InvalidValue),
    ) && arg.as_str() == "--template <TEMPLATE>"
        && value.is_empty()
    {
        // Suppress the error, it's less important than the original error.
        if let Ok(template_aliases) = load_template_aliases(ui, config) {
            return CommandError::from(err).hinted(format_template_aliases_hint(&template_aliases));
        }
    }
    CommandError::from(err)
}

fn format_template_aliases_hint(template_aliases: &TemplateAliasesMap) -> String {
    let mut hint = String::from("The following template aliases are defined:\n");
    hint.push_str(
        &template_aliases
            .symbol_names()
            .sorted_unstable()
            .map(|name| format!("- {name}"))
            .join("\n"),
    );
    hint
}

// If -R or --config* is specified, check if the expanded arguments differ.
fn warn_if_args_mismatch(
    ui: &Ui,
    app: &Command,
    config: &StackedConfig,
    expected_args: &[String],
) -> Result<(), CommandError> {
    let new_string_args = expand_args(ui, app, env::args_os(), config).ok();
    if new_string_args.as_deref() != Some(expected_args) {
        writeln!(
            ui.warning_default(),
            "Command aliases cannot be loaded from -R/--repository path or --config/--config-file \
             arguments."
        )?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use clap::CommandFactory as _;

    use super::*;

    #[derive(clap::Parser, Clone, Debug)]
    pub struct TestArgs {
        #[arg(long)]
        pub foo: Vec<u32>,
        #[arg(long)]
        pub bar: Vec<u32>,
        #[arg(long)]
        pub baz: bool,
    }

    #[test]
    fn test_merge_args_with() {
        let command = TestArgs::command();
        let parse = |args: &[&str]| -> Vec<(&'static str, u32)> {
            let matches = command.clone().try_get_matches_from(args).unwrap();
            let args = TestArgs::from_arg_matches(&matches).unwrap();
            merge_args_with(
                &matches,
                &[("foo", &args.foo), ("bar", &args.bar)],
                |id, value| (id, *value),
            )
        };

        assert_eq!(parse(&["jj"]), vec![]);
        assert_eq!(parse(&["jj", "--foo=1"]), vec![("foo", 1)]);
        assert_eq!(
            parse(&["jj", "--foo=1", "--bar=2"]),
            vec![("foo", 1), ("bar", 2)]
        );
        assert_eq!(
            parse(&["jj", "--foo=1", "--baz", "--bar=2", "--foo", "3"]),
            vec![("foo", 1), ("bar", 2), ("foo", 3)]
        );
    }
}