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
use clap::{Parser, Subcommand};
use anyhow::Result;
use std::path::PathBuf;
use dirs;
use crate::config::ToriiConfig;
use crate::core::GitRepo;
use crate::remote::{get_platform_client, Visibility, RepoSettings, RepoFeatures};
use crate::snapshot::SnapshotManager;
use crate::mirror::{MirrorManager, AccountType, Protocol};
use crate::ssh::SshHelper;
use crate::duration::parse_duration;
use crate::versioning::AutoTagger;
use crate::scanner;
use crate::issue::{get_issue_client, CreateIssueOptions};
use crate::pr::detect_platform_from_remote;
/// Template `policies/commits.toml` written by `torii init`. Conservative
/// defaults so a fresh repo doesn't fail every save out of the box — users
/// uncomment / extend rules they want enforced.
const DEFAULT_COMMITS_POLICY: &str = r#"# torii commit policy — written by `torii init`.
# Edit / extend; run `torii scan --commits` to evaluate.
# Docs: https://gitorii.com/docs/policies/commits
# Block AI-tooling co-author trailers from leaking into history.
forbid_trailers = [
"Co-Authored-By:.*Claude",
"Co-Authored-By:.*Copilot",
"Co-Authored-By:.*GPT",
]
# Reject lazy / temp subjects.
forbid_subjects = ["^(wip|tmp|temp|misc|asdf|update|fix)$"]
# Subject sanity.
subject_min_length = 8
subject_max_length = 72
# Conventional Commits — uncomment to enforce.
# require_conventional = true
# Pin commits to your domain (uncomment + adjust):
# author_email_matches = ".*@example\\.com$"
# DCO sign-off (uncomment to require):
# require_trailers = ["Signed-off-by:"]
"#;
/// True when the string looks like something `git clone` would accept as
/// a URL or local path, distinguishing it from a platform shorthand
/// (`github`, `gitlab`, …) used in `torii clone <plat> <user/repo>`.
///
/// Accepted shapes:
/// http://… https://… git://… ssh://… ftp(s)://… file://…
/// git@host:owner/repo.git (scp-like SSH)
/// user@host:owner/repo.git (any scp-like)
/// /absolute/path/to/repo (Unix abs)
/// ./relative/path ../sibling (relative explicit)
/// C:\… or C:/… (Windows abs)
fn looks_like_clone_url(s: &str) -> bool {
// Explicit scheme — anything before `://` and at least one alphanum.
if let Some(idx) = s.find("://") {
if idx > 0 && s[..idx].chars().all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.') {
return true;
}
}
// Local paths.
if s.starts_with('/') || s.starts_with("./") || s.starts_with("../") {
return true;
}
// Windows drive (C:\ or C:/).
let bytes = s.as_bytes();
if bytes.len() >= 3
&& bytes[0].is_ascii_alphabetic()
&& bytes[1] == b':'
&& (bytes[2] == b'/' || bytes[2] == b'\\')
{
return true;
}
// scp-like: <user>@<host>:<path>. Requires '@' before ':' with both
// sides non-empty. Excludes IPv6-ish patterns.
if let Some(at) = s.find('@') {
if at > 0 {
if let Some(colon) = s[at + 1..].find(':') {
let host = &s[at + 1..at + 1 + colon];
let path = &s[at + 1 + colon + 1..];
if !host.is_empty() && !path.is_empty()
&& !host.contains('/') && !host.contains('\\')
{
return true;
}
}
}
}
false
}
fn parse_account_type(s: &str) -> Result<AccountType> {
match s.to_lowercase().as_str() {
"user" | "u" => Ok(AccountType::User),
"org" | "organization" | "o" => Ok(AccountType::Organization),
_ => Err(anyhow::anyhow!("Invalid account type. Use 'user' or 'org'")),
}
}
fn parse_protocol(s: Option<&String>) -> Protocol {
match s.map(|s| s.to_lowercase()) {
Some(p) if p == "https" || p == "http" => Protocol::HTTPS,
Some(p) if p == "ssh" => Protocol::SSH,
None => {
// Auto-detect: use SSH if keys available, otherwise HTTPS
if SshHelper::has_ssh_keys() {
Protocol::SSH
} else {
println!("⚠️ No SSH keys detected. Using HTTPS protocol.");
println!(" Run 'torii config check-ssh' for SSH setup instructions.\n");
Protocol::HTTPS
}
}
_ => Protocol::SSH,
}
}
#[derive(Parser)]
#[command(name = "torii")]
#[command(version, about = "A modern git client with simplified commands")]
#[command(after_help = "Examples — daily flow:
torii status Show current state
torii save -am \"feat: add login\" Stage all and commit
torii sync Pull and push
torii sync main Integrate main into current branch
torii diff --staged Review what will be committed
Branch & history:
torii branch feature/auth -c Create and switch to branch
torii log --oneline --graph Compact history graph
torii history rebase main Rebase current branch onto main
torii history scan Scan staged files for secrets
Repos, remotes & identity:
torii init Initialize a new repo
torii clone github user/repo Clone from GitHub
torii mirror sync Push to all configured mirrors
torii config set user.name \"Alice\" Set git identity (name)
torii auth login github Authenticate with GitHub
Release & collaboration:
torii tag create v1.0.0 -m \"Release\" Create annotated tag
torii pr create Open a pull request
torii snapshot stash Stash work in progress
torii workspace status Status across all workspace repos
torii worktree add -b hotfix Spin up a sibling worktree on a new branch
torii submodule add <url> vendor/lib Embed another repo at a pinned commit
torii subtree pull --prefix=vendor/x Fetch upstream into a vendored subtree
Interactive UI:
torii tui Launch terminal UI
Run 'torii <command> --help' for detailed usage of any command.")]
pub struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Initialize a new repository
#[command(after_help = "Examples:
torii init Initialize in current directory
torii init --path ~/projects/myrepo Initialize in specific path")]
Init {
/// Path to initialize (defaults to current directory)
#[arg(short, long)]
path: Option<String>,
},
/// Save current work (simplified commit)
#[command(after_help = "Examples:
torii save -m \"fix: null check\" Commit staged changes
torii save -am \"feat: add login\" Stage all and commit
torii save src/auth.rs -m \"fix: token\" Stage specific file and commit
torii save --amend -m \"fix: typo\" Amend last commit message
torii save --revert abc1234 -m \"revert\" Revert a specific commit
torii save --reset HEAD~1 --reset-mode soft Undo last commit, keep changes
torii save --unstage src/secret.rs Remove a path from the index
torii save --unstage --all Unstage everything")]
Save {
/// Commit message (required for commit/amend; ignored with --reset/--revert/--unstage)
#[arg(short, long, required_unless_present_any = ["reset", "revert", "unstage"])]
message: Option<String>,
/// Stage all changes before committing (or, with --unstage, unstage all paths)
#[arg(short, long)]
all: bool,
/// Specific files to stage before committing (or unstage with --unstage)
#[arg(value_name = "FILES")]
files: Vec<PathBuf>,
/// Amend the previous commit
#[arg(long)]
amend: bool,
/// Revert a specific commit by hash
#[arg(long, value_name = "HASH")]
revert: Option<String>,
/// Reset to a specific commit (no commit message needed)
#[arg(long, value_name = "HASH")]
reset: Option<String>,
/// Reset mode (default: mixed):
/// soft — keep changes staged
/// mixed — keep changes in working tree, unstaged
/// hard — discard all changes
#[arg(long, default_value = "mixed", verbatim_doc_comment)]
reset_mode: String,
/// Unstage paths instead of committing (kept on disk). Use with FILES or --all.
#[arg(long, conflicts_with_all = ["amend", "revert", "reset"])]
unstage: bool,
/// Skip pre-save / post-save hooks defined in .toriignore
#[arg(long)]
skip_hooks: bool,
},
/// Sync with remote (pull+push) or integrate a branch
#[command(after_help = "Examples:
torii sync Pull from remote then push
torii sync --pull Pull only
torii sync --push Push only
torii sync --force Force push (rewrites remote history)
torii sync --fetch Fetch remote refs without merging
torii sync main Integrate main into current branch (smart merge/rebase)
torii sync main --merge Force merge strategy
torii sync main --rebase Force rebase strategy
torii sync main --preview Preview what would happen without executing")]
Sync {
/// Branch to integrate (smart merge/rebase). If omitted, syncs with remote
branch: Option<String>,
/// Pull only
#[arg(short, long)]
pull: bool,
/// Push only
#[arg(short = 'P', long)]
push: bool,
/// Force push (rewrites remote history — use with caution)
#[arg(short, long)]
force: bool,
/// Fetch remote refs without merging
#[arg(long)]
fetch: bool,
/// Force merge strategy when integrating a branch
#[arg(long)]
merge: bool,
/// Force rebase strategy when integrating a branch
#[arg(long)]
rebase: bool,
/// Preview integration without executing
#[arg(long)]
preview: bool,
/// Verify local vs remote head without pulling/pushing
#[arg(long)]
verify: bool,
/// Skip pre-sync / post-sync hooks defined in .toriignore
#[arg(long)]
skip_hooks: bool,
},
/// Show repository status
#[command(after_help = "Examples:
torii status Show staged, unstaged, and untracked files
torii status --tracked List every tracked file (≡ git ls-files)
torii status --tracked -z Null-separated output (scripting)")]
Status {
/// Instead of the normal status, print every tracked file in the
/// index, one per line. Equivalent to `git ls-files`. Useful for
/// piping into other tools.
#[arg(long)]
tracked: bool,
/// With --tracked, separate entries by NUL instead of newline.
/// Same semantics as `git ls-files -z`. Safe for paths with
/// embedded newlines.
#[arg(short = 'z', long, requires = "tracked")]
null: bool,
},
/// Show commit history
#[command(after_help = "Examples:
torii log Last 10 commits
torii log -n 50 Last 50 commits
torii log --oneline One line per commit
torii log --graph Branch graph
torii log --oneline --graph Compact graph view
torii log --author \"Alice\" Filter by author
torii log --since 2024-01-01 Commits after date
torii log --until 2024-12-31 Commits before date
torii log --grep \"feat\" Filter by message pattern
torii log --stat Show file change stats per commit")]
Log {
/// Number of commits to show (default: 10)
#[arg(short = 'n', long)]
count: Option<usize>,
/// Show one line per commit
#[arg(long)]
oneline: bool,
/// Show branch graph
#[arg(long)]
graph: bool,
/// Filter by author name or email
#[arg(long)]
author: Option<String>,
/// Show commits after this date (YYYY-MM-DD)
#[arg(long)]
since: Option<String>,
/// Show commits before this date (YYYY-MM-DD)
#[arg(long)]
until: Option<String>,
/// Filter commits whose message matches this pattern
#[arg(long)]
grep: Option<String>,
/// Show file change statistics per commit
#[arg(long)]
stat: bool,
/// Show reflog (HEAD movement history) instead of commit log
#[arg(long)]
reflog: bool,
},
/// Show unstaged or staged changes
#[command(after_help = "Examples:
torii diff Show unstaged changes
torii diff --staged Show staged changes (ready to commit)
torii diff --last Show changes in last commit")]
Diff {
/// Show staged changes
#[arg(long)]
staged: bool,
/// Show last commit diff
#[arg(long)]
last: bool,
},
/// **Deprecated** alias — use `torii show <file> --blame` instead.
/// Will be removed in 0.8.
#[command(hide = true)]
Blame {
/// File to blame
file: String,
/// Line range (e.g., 10,20)
#[arg(short = 'L', long)]
lines: Option<String>,
},
/// Scan for sensitive data (secrets, tokens, keys)
#[command(after_help = "Examples:
torii scan Scan staged files for secrets
torii scan --history Scan entire git history for secrets
torii scan --commits Scan commits against policies/commits.toml
torii scan --commits --limit 50 Limit how many commits to evaluate
torii scan --commits --policy-file path/to/commits.toml")]
Scan {
/// Scan the entire git history instead of only staged files
#[arg(long)]
history: bool,
/// Evaluate commits against policies/commits.toml by default
#[arg(long)]
commits: bool,
/// Path to the policy file (default: <repo>/policies/commits.toml)
#[arg(long, value_name = "PATH")]
policy_file: Option<PathBuf>,
/// Max commits to scan when --commits is set (default: 200)
#[arg(long, default_value = "200")]
limit: usize,
},
/// Apply a commit from another branch to the current branch
#[command(name = "cherry-pick", after_help = "Examples:
torii cherry-pick abc1234 Apply a commit
torii cherry-pick --continue Resume after resolving conflicts
torii cherry-pick --abort Abort an in-progress cherry-pick")]
CherryPick {
/// Commit hash to cherry-pick
commit: Option<String>,
/// Continue after resolving conflicts
#[arg(long)]
r#continue: bool,
/// Abort cherry-pick
#[arg(long)]
abort: bool,
},
/// Manage branches
#[command(after_help = "Examples:
torii branch List local branches
torii branch --all List local and remote branches
torii branch feature/auth -c Create and switch to branch
torii branch gh-pages -c --orphan Create orphan branch (no history)
torii branch main Switch to existing branch
torii branch -d feature/auth Delete local branch
torii branch -d feature/auth --force Force delete (not merged)
torii branch --delete-remote feature/auth Delete branch on all remotes
torii branch --rename new-name Rename current branch")]
Branch {
/// Branch name to switch to or create with -c
name: Option<String>,
/// Create new branch and switch to it
#[arg(short, long)]
create: bool,
/// Create the branch with no parents/history (requires -c)
#[arg(long)]
orphan: bool,
/// Delete local branch by name
#[arg(short, long)]
delete: Option<String>,
/// Force delete local branch even if not merged
#[arg(long)]
force: bool,
/// Delete branch on all configured remotes
#[arg(long)]
delete_remote: Option<String>,
/// List local branches
#[arg(short, long)]
list: bool,
/// Rename current branch to this name
#[arg(short, long)]
rename: Option<String>,
/// Show all branches including remote
#[arg(short, long)]
all: bool,
},
/// Clone a repository
#[command(after_help = "Examples:
torii clone github user/repo Clone from GitHub (auto SSH/HTTPS)
torii clone gitlab user/repo Clone from GitLab
torii clone github user/repo /tmp/foo Clone into /tmp/foo (positional dest)
torii clone github user/repo -d my-dir Same, with -d flag
torii clone github user/repo --protocol https Force HTTPS
torii clone https://github.com/user/repo.git Clone from full URL
torii clone https://github.com/user/repo.git -d /tmp/foo
torii clone git@github.com:user/repo.git Clone via SSH URL
Supported platforms: github, gitlab, codeberg, bitbucket, gitea, forgejo
Protocol is auto-detected: SSH if keys are configured, HTTPS otherwise.
Override with --protocol or set default: torii config set mirror.default_protocol https")]
Clone {
/// Platform (github, gitlab, ...) or full URL (https://... / git@...)
source: String,
/// Repository as user/repo (when using platform shorthand)
args: Vec<String>,
/// Target directory name
#[arg(short = 'd', long)]
directory: Option<String>,
/// Protocol to use: ssh or https (default: auto-detect)
#[arg(long)]
protocol: Option<String>,
},
/// Manage tags and releases
#[command(after_help = "Examples:
torii tag list List all tags
torii tag create v1.2.0 -m \"Release\" Create annotated tag
torii tag delete v1.0.0 Delete a tag
torii tag push v1.2.0 Push specific tag to remote
torii tag push Push all tags to remote
torii tag show v1.2.0 Show tag details
torii tag release Auto-bump version from conventional commits
torii tag release --bump minor Force minor bump
torii tag release --dry-run Preview without creating tag
Auto-bump rules (Conventional Commits):
feat: → minor bump (0.1.0 → 0.2.0)
fix: / perf: → patch bump (0.1.0 → 0.1.1)
feat!: → major bump (0.1.0 → 1.0.0)")]
Tag {
#[command(subcommand)]
action: TagCommands,
},
/// Save and restore work-in-progress snapshots
#[command(after_help = "Examples:
torii snapshot create -n \"before-refactor\" Create named snapshot
torii snapshot list List all snapshots
torii snapshot restore <id> Restore a snapshot
torii snapshot delete <id> Delete a snapshot
torii snapshot stash Stash current work
torii snapshot stash -u Stash including untracked files
torii snapshot unstash Restore latest stash
torii snapshot unstash <id> --keep Restore stash but keep it
torii snapshot undo Undo last operation")]
Snapshot {
#[command(subcommand)]
action: SnapshotCommands,
},
/// Mirror repository across multiple platforms
#[command(after_help = "Examples:
torii mirror add gitlab user paskidev myrepo --primary Set GitLab as primary (source of truth)
torii mirror add github user paskidev myrepo Add GitHub as a replica mirror
torii mirror promote github paskidev Promote a mirror to primary
torii mirror sync Push to all replica mirrors
torii mirror sync --force Force push to all mirrors
torii mirror list List configured mirrors
torii mirror remove github paskidev Remove a mirror
torii mirror autofetch --enable --interval 30m Auto-fetch every 30 min
torii mirror autofetch --disable Disable auto-fetch
torii mirror autofetch --status Show autofetch status
Supported platforms: github, gitlab, codeberg, bitbucket, gitea, forgejo")]
Mirror {
#[command(subcommand)]
action: MirrorCommands,
},
/// Show commit, tag, or file details
#[command(after_help = "Examples:
torii show Show HEAD commit with diff
torii show abc1234 Show specific commit
torii show v1.0.0 Show tag details
torii show src/main.rs --blame Show line-by-line change history
torii show src/main.rs --blame -L 10,20 Blame specific line range")]
Show {
/// Commit hash, tag name, ref, or file path (defaults to HEAD)
object: Option<String>,
/// Show blame for a file (who changed each line)
#[arg(long)]
blame: bool,
/// Line range for blame (e.g., 10,20)
#[arg(short = 'L', long, requires = "blame")]
lines: Option<String>,
},
/// Manage commit history (rebase, cherry-pick, blame, scan)
#[command(after_help = "Examples:
torii history reflog Show HEAD movement history
torii history rebase main Rebase current branch onto main
torii history rebase -i HEAD~5 Interactive rebase last 5 commits
torii history rebase --continue Continue after resolving conflicts
torii history rebase --abort Abort current rebase
torii history cherry-pick abc1234 Apply a commit to current branch
torii history blame src/main.rs Line-by-line change history
torii history blame src/main.rs -L 10,20 Specific line range
torii history scan Scan staged files for secrets
torii history scan --history Scan entire git history for secrets
torii history remove-file secrets.txt Purge file from all commits
torii history rewrite \"2024-01-01\" \"2024-12-31\" Rewrite commit dates
torii history clean GC and expire reflog")]
History {
#[command(subcommand)]
action: HistoryCommands,
},
/// Manage Torii configuration
#[command(after_help = "Examples:
torii config list Show all config values
torii config list --local Show local repo config
torii config get user.name Get a value
torii config set user.name \"Alice\" Set a global value
torii config set user.email \"a@b.com\" --local Set a local value
torii config set auth.github_token ghp_xxx Set GitHub token
torii config set auth.gitlab_token glpat-xxx Set GitLab token
torii config set mirror.default_protocol https Use HTTPS by default
torii config edit Open config in editor
torii config reset Reset to defaults
Available keys:
user.name, user.email, user.editor
auth.github_token, auth.gitlab_token, auth.gitea_token
auth.forgejo_token, auth.codeberg_token
git.default_branch, git.sign_commits, git.pull_rebase
mirror.default_protocol, mirror.autofetch_enabled
snapshot.auto_enabled, snapshot.auto_interval_minutes
ui.colors, ui.emoji, ui.verbose, ui.date_format")]
Config {
#[command(subcommand)]
action: ConfigCommands,
},
/// Manage gitorii.com API key (cloud features: CI transpile, etc.)
#[command(after_help = "Examples:
torii auth login Prompt for an API key and save it
torii auth login --key gitorii_sk_… Save a key non-interactively
torii auth status Show org / plan tied to the key
torii auth logout Forget the local key
Generate a key in the dashboard: https://gitorii.com/dashboard/api-keys
Override per-process via env: TORII_API_KEY=gitorii_sk_…")]
Auth {
#[command(subcommand)]
action: AuthCommands,
},
/// Manage remote repositories (create, delete, configure)
#[command(after_help = "Examples:
torii remote create github myrepo --public Create public repo on GitHub
torii remote create gitlab myrepo --private Create private repo on GitLab
torii remote create github myrepo --private --push Create and push current branch
torii remote delete github owner myrepo --yes Delete repo (no confirmation)
torii remote visibility github owner myrepo --public Make repo public
torii remote visibility github owner myrepo --private Make repo private
torii remote configure github owner myrepo --default-branch main
torii remote info github owner myrepo Show repo details
torii remote list github List all your GitHub repos
Supported platforms: github, gitlab, codeberg, bitbucket, gitea, forgejo")]
Remote {
#[command(subcommand)]
action: RemoteCommands,
},
/// Manage multi-repo workspaces
#[command(after_help = "Examples:
torii workspace add work ~/repos/api Add repo to workspace
torii workspace list List all workspaces
torii workspace status work Show status of all repos
torii workspace save work -m \"wip\" Commit across all repos
torii workspace sync work Pull+push all repos")]
Workspace {
#[command(subcommand)]
action: WorkspaceCommands,
},
/// Manage pull requests / merge requests
#[command(after_help = "Examples:
torii pr list List open PRs
torii pr list --state closed List closed PRs
torii pr create -t \"feat: login\" -b main
torii pr merge 42 Merge PR #42
torii pr merge 42 --method squash Squash merge
torii pr close 42 Close PR #42
torii pr checkout 42 Checkout PR branch
torii pr open 42 Open PR in browser")]
Pr {
#[command(subcommand)]
action: PrCommands,
},
/// Manage issues
#[command(after_help = "Examples:
torii issue list List open issues
torii issue list --state closed List closed issues
torii issue create -t \"bug: crash\" Create issue
torii issue create -t \"title\" -d \"desc\" Create with description
torii issue close 42 Close issue #42
torii issue comment 42 -m \"Fixed in v2\" Add a comment")]
Issue {
#[command(subcommand)]
action: IssueCommands,
},
/// Manage .toriignore rules (paths, secrets, size, hooks)
#[command(after_help = "Examples:
torii ignore add 'build/' Add path to public .toriignore
torii ignore add --local 'internal/billing/' Add path to .toriignore.local (not committed)
torii ignore secret 'AKIA[0-9A-Z]{16}' --name AWS Add secret regex to .local (private by default)
torii ignore list Show effective rules (public + local merged)
The .toriignore.local file is machine-private — it is auto-excluded from git
and never committed. Use it for rules whose existence would aid recon if the
public repo leaked (proprietary secret formats, internal paths, etc).")]
Ignore {
#[command(subcommand)]
action: IgnoreCommands,
},
/// Open the interactive TUI dashboard
#[command(after_help = "Examples:
torii tui Open dashboard (status, log, file navigation)")]
Tui,
/// Manage worktrees — multiple working copies of the same repo, each on
/// its own branch, sharing the underlying objects.
#[command(after_help = "Examples:
torii worktree add -b feature/auth Create branch + worktree at ../<repo>-feature-auth/
torii worktree add ../hotfix -b release/0.7 Create branch at explicit path
torii worktree add ../hotfix release/0.7 Check out existing branch in worktree
torii worktree list Show every worktree + status
torii worktree remove ../hotfix Remove worktree (snapshot taken automatically)
torii worktree remove ../hotfix --force Remove even if dirty
torii worktree prune Clean up metadata of deleted worktrees
torii worktree open ../hotfix Launch $SHELL in that worktree
The default path (when omitted) is derived from worktree.base_dir config:
torii config set worktree.base_dir ~/worktrees # default is '..' (sibling dirs)
torii config set worktree.base_dir .. # restore default")]
Worktree {
#[command(subcommand)]
action: Option<WorktreeCommands>,
},
/// Manage submodules — embed another git repo at a path and commit
/// inside this one. The embedded repo's history stays separate.
#[command(after_help = "Examples:
torii submodule add git@github.com:owner/lib.git vendor/lib Add at vendor/lib
torii submodule add git@.../lib.git vendor/lib --branch main Pin a tracked branch
torii submodule status List submodules + state
torii submodule init Copy .gitmodules URLs to .git/config
torii submodule update --init Init missing + fetch+checkout pinned commit
torii submodule sync Re-copy URLs (after upstream URL change)
torii submodule foreach 'cargo build' Run a command in each submodule
torii submodule remove vendor/lib Deregister + clean up
Recursion (--recursive) is not yet implemented; nested submodules need a
manual loop for now.")]
Submodule {
#[command(subcommand)]
action: Option<SubmoduleCommands>,
},
/// Manage subtrees — merge another project's history into a
/// subdirectory of this repo, no second clone, no .gitmodules. Thin
/// wrapper over `git subtree` (which must be installed).
#[command(after_help = "Examples:
torii subtree add --prefix=vendor/lib git@... main --squash Initial import
torii subtree pull --prefix=vendor/lib git@... main --squash Fetch upstream changes
torii subtree push --prefix=vendor/lib git@... main Push subtree back
torii subtree split --prefix=vendor/lib -b lib-split Extract history to a branch
torii subtree merge --prefix=vendor/lib some-ref Finish a manual merge
Pass --squash on add/pull/merge to flatten upstream history into a single
merge commit. Without it the full upstream graph is brought in.")]
Subtree {
#[command(subcommand)]
action: SubtreeCommands,
},
/// Binary search for the commit that introduced a regression.
/// State-machine wrapper over `git bisect`.
#[command(after_help = "Examples:
torii bisect start Enter bisect mode
torii bisect bad Current HEAD is bad
torii bisect good v0.6.0 v0.6.0 was good
torii bisect skip Current commit unbuildable, skip
torii bisect run cargo test Auto-run test on each candidate
torii bisect log Print the search log
torii bisect reset Exit bisect mode, restore HEAD")]
Bisect {
#[command(subcommand)]
action: BisectCommands,
},
/// Pretty name for HEAD based on the nearest tag (≡ git describe).
/// Format: `<tag>-<n>-g<short>` or just `<tag>` if HEAD is on a tag.
Describe {
/// Include lightweight tags (default: annotated only).
#[arg(long)]
tags: bool,
/// Always use the long format even if HEAD is on a tag.
#[arg(long)]
long: bool,
/// Append `-dirty` if the working tree has uncommitted changes.
#[arg(long)]
dirty: bool,
/// How many candidate tags to consider (default: 10).
#[arg(long, default_value = "10")]
candidates: u32,
},
/// Export a tree or commit as a tarball/zip (wrapper over `git archive`).
#[command(after_help = "Examples:
torii archive HEAD -o release.tar.gz
torii archive v0.6.9 --prefix=gitorii-0.6.9/ -o gitorii-0.6.9.tar.gz
torii archive HEAD --format=zip -o release.zip")]
Archive {
/// Revision (HEAD, tag, branch, commit) to archive.
revision: String,
/// Output file path. Without it, writes to stdout.
#[arg(short = 'o', long)]
output: Option<String>,
/// Force format (tar/zip/tar.gz/tgz). Otherwise inferred from extension.
#[arg(long)]
format: Option<String>,
/// Prepend each entry with this prefix (e.g. `myproj-1.0/`).
#[arg(long)]
prefix: Option<String>,
},
/// Remove tracked files from index and working tree.
#[command(alias = "rm", after_help = "Examples:
torii remove src/old.rs Remove + untrack
torii remove src/old.rs --cached Untrack only (keep on disk)
torii remove -r vendor/legacy/ Recursive
torii remove --force src/dirty.rs Drop local changes
`torii rm` works too — alias kept for users coming from git.")]
Remove {
/// One or more paths to remove.
#[arg(required = true)]
paths: Vec<PathBuf>,
/// Don't delete from disk, just untrack.
#[arg(long)]
cached: bool,
/// Allow removing directories recursively.
#[arg(short = 'r', long)]
recursive: bool,
/// Proceed even if the file has uncommitted modifications.
#[arg(short = 'f', long)]
force: bool,
},
/// Rename (or move) a tracked file/directory.
#[command(alias = "mv", after_help = "Examples:
torii rename old.rs new.rs Stage a rename
torii rename src/a.rs src/b.rs --force Overwrite if target exists
`torii mv` works too — alias kept for users coming from git.")]
Rename {
/// Source path.
from: PathBuf,
/// Destination path.
to: PathBuf,
/// Overwrite target if it already exists.
#[arg(short = 'f', long)]
force: bool,
},
/// Search tracked content for a pattern (wrapper over `git grep`).
#[command(after_help = "Examples:
torii grep TODO Search for TODO in tracked files
torii grep -i \"fix me\" Case-insensitive
torii grep -l unsafe List files containing 'unsafe'
torii grep -w main src/ Word-boundary match, in src/ only")]
Grep {
/// Pattern (regex by default — pass --fixed-string for literal).
pattern: String,
/// Restrict search to these paths.
#[arg(value_name = "PATH")]
paths: Vec<String>,
/// Case-insensitive.
#[arg(short = 'i', long)]
ignore_case: bool,
/// Match whole words only.
#[arg(short = 'w', long)]
word_regexp: bool,
/// Print only file names that contain a match.
#[arg(short = 'l', long)]
files_with_matches: bool,
/// Suppress line numbers (which are on by default in torii).
#[arg(long)]
no_line_number: bool,
},
/// Annotations attached to commits (wrapper over `git notes`).
/// Stored in `refs/notes/commits` so commit OIDs stay stable.
#[command(after_help = "Examples:
torii notes List commits with notes
torii notes add HEAD -m \"reviewed by X\" Add a note to HEAD
torii notes append HEAD -m \"and also Y\" Append to an existing note
torii notes show HEAD Show the note attached to HEAD
torii notes edit HEAD Open $EDITOR on it
torii notes copy v0.6.8 v0.6.9 Copy notes between commits
torii notes remove HEAD Drop the note")]
Notes {
#[command(subcommand)]
action: Option<NotesCommands>,
},
/// Export commits as patch files / apply patches as new commits.
/// Wrapper over `git format-patch` and `git am`.
#[command(after_help = "Examples:
torii patch export HEAD~3..HEAD Export last 3 commits
torii patch export v0.6.8..HEAD -o /tmp/p/ Into a directory
torii patch export HEAD~1..HEAD --stdout To stdout
torii patch apply 0001-fix.patch Apply a single patch
torii patch apply *.patch Apply a series
torii patch apply --continue After resolving conflicts")]
Patch {
#[command(subcommand)]
action: PatchCommands,
},
/// Remove untracked files from the working tree (≡ `git clean`).
/// Defaults to a dry-run for safety; pass -f to actually delete.
#[command(after_help = "Examples:
torii clean Dry-run, list what would go
torii clean -f Actually delete untracked files
torii clean -f -d Include untracked directories
torii clean -f -x Also remove .gitignore-matched files
torii clean -f -X ONLY remove .gitignore-matched files")]
Clean {
/// Actually delete (otherwise dry-run).
#[arg(short = 'f', long)]
force: bool,
/// Recurse into untracked directories.
#[arg(short = 'd', long)]
dirs: bool,
/// Also remove ignored files.
#[arg(short = 'x', long)]
include_ignored: bool,
/// Only remove ignored files.
#[arg(short = 'X', long)]
only_ignored: bool,
},
}
#[derive(Subcommand)]
enum BisectCommands {
/// Enter bisect mode. Optionally pass `<bad> [<good>...]` to seed it.
Start {
/// Known-bad commit (defaults to HEAD when seeding inline later).
bad: Option<String>,
/// One or more known-good commits.
good: Vec<String>,
},
/// Mark the given (or current) commit as bad.
Bad { commit: Option<String> },
/// Mark the given (or current) commit as good.
Good { commit: Option<String> },
/// Skip the current commit (unbuildable/untestable).
Skip { commit: Option<String> },
/// Exit bisect mode and restore HEAD.
Reset,
/// Print the bisect log so far.
Log,
/// Run `<cmd>` for every candidate; exit 0 = good, non-zero = bad, 125 = skip.
Run {
#[arg(trailing_var_arg = true, required = true)]
cmd: Vec<String>,
},
}
#[derive(Subcommand)]
enum NotesCommands {
/// List commits that have notes attached.
List,
/// Add a note to a commit. Opens $EDITOR if -m not given.
Add {
commit: String,
#[arg(short = 'm', long)]
message: Option<String>,
/// Overwrite an existing note.
#[arg(short = 'f', long)]
force: bool,
},
/// Append to the commit's existing note.
Append {
commit: String,
#[arg(short = 'm', long)]
message: String,
},
/// Print the note attached to a commit.
Show { commit: String },
/// Open the note in $EDITOR for changes.
Edit { commit: String },
/// Copy notes from one commit to another.
Copy {
from: String,
to: String,
#[arg(short = 'f', long)]
force: bool,
},
/// Remove a commit's note.
Remove { commit: String },
}
#[derive(Subcommand)]
enum PatchCommands {
/// Export a commit range as one `.patch` per commit.
Export {
/// Revision range, e.g. `v0.6.8..HEAD` or `HEAD~3..`.
range: String,
/// Output directory (default: cwd).
#[arg(short = 'o', long)]
output_dir: Option<PathBuf>,
/// Write patches to stdout instead of files.
#[arg(long)]
stdout: bool,
/// Include a cover letter as `0000-cover-letter.patch`.
#[arg(long)]
cover_letter: bool,
},
/// Apply one or more patch files as new commits.
Apply {
/// Patch files (use `--continue`/`--abort`/`--skip` for ongoing ops).
files: Vec<PathBuf>,
/// Fall back to 3-way merge on conflicts.
#[arg(long)]
three_way: bool,
/// Resume after manual conflict resolution.
#[arg(long = "continue")]
continue_: bool,
/// Drop the current patch and move on.
#[arg(long)]
skip: bool,
/// Bail out of an in-progress apply session.
#[arg(long)]
abort: bool,
},
}
#[derive(Subcommand)]
enum SubmoduleCommands {
/// Register and clone a new submodule.
Add {
/// Source URL of the submodule (git@host:owner/repo.git, https://…, etc.).
url: String,
/// Where in this repo to place it (e.g. vendor/lib).
path: PathBuf,
/// Track a specific branch (writes submodule.<n>.branch in .gitmodules).
#[arg(long)]
branch: Option<String>,
/// Override the submodule name (defaults to the path).
#[arg(long)]
name: Option<String>,
/// After cloning the top-level submodule, recursively init+update
/// any nested submodules it contains.
#[arg(long)]
recursive: bool,
},
/// List submodules with HEAD, working-tree id and state.
Status,
/// Copy URLs from `.gitmodules` into `.git/config`.
Init {
/// Overwrite existing entries in `.git/config`.
#[arg(long)]
force: bool,
},
/// Fetch and checkout the commit each submodule is pinned at.
Update {
/// Also run `init` first for submodules that aren't initialised.
#[arg(long)]
init: bool,
/// Recurse into nested submodules after each top-level update.
#[arg(long)]
recursive: bool,
},
/// Re-copy URLs from `.gitmodules` into `.git/config`.
Sync,
/// Run a shell command in each submodule's working directory.
Foreach {
/// Command to run via $SHELL -c. Stops at the first non-zero exit.
#[arg(trailing_var_arg = true)]
cmd: Vec<String>,
},
/// Deregister a submodule cleanly (.gitmodules, .git/config, .git/modules, working tree).
Remove {
/// Path of the submodule to remove (must match `path` in .gitmodules).
path: PathBuf,
},
}
#[derive(Subcommand)]
enum SubtreeCommands {
/// Initial import of `<url>:<ref>` at `--prefix=<dir>`.
Add {
/// Subdirectory inside the super-repo (e.g. vendor/lib).
#[arg(long)]
prefix: String,
/// Source URL or local path.
url: String,
/// Ref (branch, tag, commit) on the source side.
#[arg(value_name = "REF")]
refname: String,
/// Flatten upstream history into one merge commit.
#[arg(long)]
squash: bool,
},
/// Fetch and merge upstream updates into the subtree.
Pull {
#[arg(long)]
prefix: String,
url: String,
#[arg(value_name = "REF")]
refname: String,
#[arg(long)]
squash: bool,
},
/// Extract the subtree and push it back to its source.
Push {
#[arg(long)]
prefix: String,
url: String,
#[arg(value_name = "REF")]
refname: String,
},
/// Extract the subtree's history into a new branch without pushing.
Split {
#[arg(long)]
prefix: String,
/// Create a local branch at the split commit.
#[arg(short = 'b', long)]
branch: Option<String>,
/// Annotate cherry-picked commits with this prefix.
#[arg(long)]
annotate: Option<String>,
},
/// Finish a manual conflict resolution after `pull`.
Merge {
#[arg(long)]
prefix: String,
#[arg(value_name = "REF")]
refname: String,
#[arg(long)]
squash: bool,
},
}
#[derive(Subcommand)]
enum WorktreeCommands {
/// Create a new worktree.
///
/// One of `-b <new-branch>` or a positional `<existing-branch>` is
/// required. If `<path>` is omitted, it's derived from
/// `worktree.base_dir` + repo name + branch name.
Add {
/// Path for the new worktree. Defaults to <worktree.base_dir>/<repo>-<branch>.
path: Option<PathBuf>,
/// Create a new branch with this name (off the current HEAD).
#[arg(short = 'b', long = "branch", value_name = "NEW_BRANCH")]
new_branch: Option<String>,
/// Check out this existing local branch in the worktree.
#[arg(value_name = "EXISTING_BRANCH")]
existing_branch: Option<String>,
},
/// List all worktrees with branch and clean/dirty status.
List,
/// Remove a worktree and its directory (always takes a snapshot first).
Remove {
/// Path to the worktree to remove.
path: PathBuf,
/// Remove even if the working tree has uncommitted changes.
#[arg(long)]
force: bool,
/// Skip the safety snapshot taken before removing.
#[arg(long)]
no_snapshot: bool,
},
/// Clean up metadata of worktrees whose directory has been deleted.
Prune,
/// Launch $SHELL inside a worktree directory; returns when the shell exits.
Open {
/// Path to the worktree to open.
path: PathBuf,
},
/// Lock a worktree against `prune` (and accidental cleanup tools).
Lock {
/// Path to the worktree to lock.
path: PathBuf,
/// Optional reason saved alongside the lock; surfaces in `list`.
#[arg(short = 'r', long)]
reason: Option<String>,
},
/// Release a previously locked worktree.
Unlock {
/// Path to the worktree to unlock.
path: PathBuf,
},
/// Move a worktree directory and patch its link files.
Move {
/// Current path of the worktree.
old: PathBuf,
/// Target path.
new: PathBuf,
},
/// Re-validate every linked worktree's link files and report broken ones.
Repair,
}
#[derive(Subcommand)]
enum IgnoreCommands {
/// Add a path pattern to .toriignore (or .toriignore.local with --local)
Add {
/// Glob/path pattern (e.g. `build/`, `*.log`, `/internal/`)
pattern: String,
/// Write to .toriignore.local instead of .toriignore (private, not committed)
#[arg(long)]
local: bool,
},
/// Add a secret regex rule. Defaults to .toriignore.local (private).
/// Pass --public to put the rule in the committed .toriignore instead.
Secret {
/// Regex pattern matching the secret
pattern: String,
/// Optional human name shown when the rule fires
#[arg(long)]
name: Option<String>,
/// Write to public .toriignore instead of .toriignore.local
#[arg(long)]
public: bool,
},
/// List effective rules (public + local merged)
List,
}
#[derive(Subcommand)]
enum PrCommands {
/// List pull requests
List {
/// State: open, closed, merged, all (default: open)
#[arg(long, default_value = "open")]
state: String,
},
/// Create a pull request
Create {
/// PR title
#[arg(short, long)]
title: String,
/// Base branch (default: main)
#[arg(short, long, default_value = "main")]
base: String,
/// Head branch (default: current branch)
#[arg(long)]
head: Option<String>,
/// PR description
#[arg(short, long)]
description: Option<String>,
/// Mark as draft
#[arg(long)]
draft: bool,
},
/// Merge a pull request
Merge {
/// PR number
number: u64,
/// Merge method: merge, squash, rebase (default: merge)
#[arg(long, default_value = "merge")]
method: String,
},
/// Close a pull request
Close {
/// PR number
number: u64,
},
/// Checkout the branch of a pull request
Checkout {
/// PR number
number: u64,
},
/// Open a pull request in the browser
Open {
/// PR number
number: u64,
},
}
#[derive(Subcommand)]
enum IssueCommands {
/// List issues
List {
#[arg(long, default_value = "open")]
state: String,
},
/// Create an issue
Create {
#[arg(short, long)]
title: String,
#[arg(short = 'd', long)]
description: Option<String>,
},
/// Close an issue
Close {
number: u64,
},
/// Add a comment to an issue
Comment {
number: u64,
#[arg(short, long)]
message: String,
},
}
#[derive(Subcommand)]
enum WorkspaceCommands {
/// Add a repository to a workspace
Add {
/// Workspace name
workspace: String,
/// Repository path
path: String,
},
/// Remove a repository from a workspace
Remove {
/// Workspace name
workspace: String,
/// Repository path
path: String,
},
/// Delete a workspace entirely
Delete {
/// Workspace name
workspace: String,
},
/// List all workspaces and their repos
List,
/// Show git status across all repos in a workspace
Status {
/// Workspace name
workspace: String,
},
/// Commit changes across all repos in a workspace
Save {
/// Workspace name
workspace: String,
/// Commit message
#[arg(short, long)]
message: String,
/// Stage all changes before committing
#[arg(short, long)]
all: bool,
},
/// Pull and push all repos in a workspace
Sync {
/// Workspace name
workspace: String,
/// Force push
#[arg(long)]
force: bool,
},
}
#[derive(Subcommand)]
enum AuthCommands {
/// Save an API key locally and validate it against the backend.
Login {
/// API key (gitorii_sk_…). If omitted, prompts on stdin.
#[arg(long)]
key: Option<String>,
/// Custom API endpoint (default: https://api.gitorii.com).
/// Useful for self-hosted / local dev.
#[arg(long)]
endpoint: Option<String>,
},
/// Show the org / plan / seats tied to the active key.
Status,
/// Alias of `status`.
Whoami,
/// Delete the local key (env var TORII_API_KEY still wins if set).
Logout,
}
#[derive(Subcommand)]
enum ConfigCommands {
/// Set a configuration value
Set {
/// Configuration key (e.g., user.name, snapshot.auto_enabled)
key: String,
/// Configuration value
value: String,
/// Set in local repository config instead of global
#[arg(long)]
local: bool,
},
/// Get a configuration value
Get {
/// Configuration key (e.g., user.name, snapshot.auto_enabled)
key: String,
/// Get from local repository config
#[arg(long)]
local: bool,
},
/// List all configuration values
List {
/// Show local repository config
#[arg(long)]
local: bool,
},
/// Edit configuration file in editor
Edit {
/// Edit local repository config instead of global
#[arg(long)]
local: bool,
},
/// Reset configuration to defaults
Reset {
/// Reset local repository config instead of global
#[arg(long)]
local: bool,
},
/// Check SSH configuration and show setup instructions
#[command(name = "check-ssh")]
CheckSsh,
}
#[derive(Subcommand)]
enum RemoteCommands {
/// Create a new remote repository on one or more platforms
#[command(after_help = "Examples:
torii remote create github myrepo User repo (your account)
torii remote create github acme/widget Org repo: acme/widget
torii remote create gitlab syrakon/svitrio-turso GitLab group repo
torii remote create gitlab engineering/web/api GitLab subgroup repo
torii remote create github,gitlab acme/myrepo --push Same owner on both
torii remote create github acme/myrepo --private --push
`<NAME>` accepts either `repo` (creates in your personal namespace) or
`owner/repo` (creates in the named org / group / subgroup). The
`--namespace <owner>` flag is the equivalent if you prefer keeping
NAME bare.")]
Create {
/// Platform (or comma-separated list): github, gitlab, codeberg, bitbucket, gitea, forgejo
#[arg(value_delimiter = ',')]
platforms: String,
/// Repository name. Supports `repo` (personal) or `owner/repo`
/// (organization / GitLab group / subgroup path). Slashes select
/// the namespace.
name: String,
#[arg(short, long)]
description: Option<String>,
#[arg(long)]
public: bool,
#[arg(long)]
private: bool,
#[arg(long)]
push: bool,
/// Override namespace explicitly. Equivalent to passing
/// `<namespace>/<name>` as NAME. Useful when the repo name itself
/// contains a slash you don't want parsed as a namespace.
#[arg(long, value_name = "OWNER")]
namespace: Option<String>,
},
/// Delete a remote repository on one or more platforms
Delete {
/// Platform (or comma-separated list)
platforms: String,
owner: String,
repo: String,
#[arg(short = 'y', long)]
yes: bool,
},
Visibility {
platform: String,
owner: String,
repo: String,
#[arg(long, conflicts_with = "private")]
public: bool,
#[arg(long, conflicts_with = "public")]
private: bool,
},
Configure {
platform: String,
owner: String,
repo: String,
#[arg(long)]
description: Option<String>,
#[arg(long)]
homepage: Option<String>,
#[arg(long)]
default_branch: Option<String>,
#[arg(long)]
enable_issues: bool,
#[arg(long, conflicts_with = "enable_issues")]
disable_issues: bool,
#[arg(long)]
enable_wiki: bool,
#[arg(long, conflicts_with = "enable_wiki")]
disable_wiki: bool,
#[arg(long)]
enable_projects: bool,
#[arg(long, conflicts_with = "enable_projects")]
disable_projects: bool,
},
Info {
platform: String,
owner: String,
repo: String,
},
List {
platform: String,
},
/// List remotes configured in the current repository
Local,
/// Link an existing remote repo to local (writes origin without touching the platform)
#[command(after_help = "Examples:
torii remote link github user/repo Link via SSH (default)
torii remote link gitlab user/repo --https Link via HTTPS
torii remote link --url git@host:owner/repo.git
torii remote link my-fork github user/repo Use a remote name other than 'origin'")]
Link {
/// Optional remote name (default: origin)
#[arg(long, default_value = "origin")]
name: String,
/// Platform shortcut: github, gitlab, codeberg, bitbucket, gitea, forgejo, sourcehut
platform: Option<String>,
/// owner/repo on the platform
repo: Option<String>,
/// Use HTTPS instead of SSH
#[arg(long)]
https: bool,
/// Provide a full URL directly (bypasses platform/repo)
#[arg(long, value_name = "URL")]
url: Option<String>,
/// Replace existing remote with the same name
#[arg(long)]
force: bool,
},
/// Remove a local remote alias from .git/config — does NOT touch the
/// platform. Inverse of `link`.
#[command(after_help = "Examples:
torii remote unlink origin Drop the default origin alias
torii remote unlink upstream Drop a custom-named remote
torii remote unlink old --yes Skip confirmation prompt")]
Unlink {
/// Name of the local remote alias to remove (e.g. origin, upstream)
name: String,
/// Skip the confirmation prompt
#[arg(short = 'y', long)]
yes: bool,
},
/// List refs the remote currently advertises (≡ `git ls-remote`).
/// Hits the network — uses your configured auth.
#[command(after_help = "Examples:
torii remote refs origin List all refs on origin
torii remote refs origin --heads Branch heads only
torii remote refs origin --tags Tags only
torii remote refs https://... Ad-hoc URL (no need to add as remote first)")]
Refs {
/// Local remote alias OR a full URL.
target: String,
/// Only print branch heads (`refs/heads/*`).
#[arg(long)]
heads: bool,
/// Only print tag refs (`refs/tags/*`).
#[arg(long)]
tags: bool,
},
}
#[derive(Subcommand)]
enum HistoryCommands {
/// Rewrite commit history dates
Rewrite {
/// Start date (YYYY-MM-DD HH:MM)
start: String,
/// End date (YYYY-MM-DD HH:MM)
end: String,
},
/// Compact the repository — repack objects, expire reflog,
/// drop unreachable refs. Same operation as `git gc`.
///
/// Renamed from `clean` → `gc` → `compact` over 0.7.0 as we
/// converged on plain English. `gc` still works as an alias for
/// users coming from git; old `clean` (top-level, was GC) is a
/// deprecated alias and prints a warning.
#[command(alias = "gc")]
Compact,
/// **Deprecated** — alias for `torii history gc`. Will be removed in 0.8.
/// `torii clean` (top-level) is now the cleanup-untracked-files command.
#[command(hide = true)]
Clean,
/// Remove a file from the entire git history
RemoveFile {
/// File path to remove from all commits
file: String,
},
/// Rebase current branch onto a target
Rebase {
/// Target branch or commit to rebase onto
target: Option<String>,
/// Interactive rebase
#[arg(short, long)]
interactive: bool,
/// Path to a pre-written rebase todo file (skips editor)
#[arg(long, value_name = "FILE")]
todo_file: Option<PathBuf>,
/// Rebase from the root commit (no target needed; useful to squash initial commits)
#[arg(long)]
root: bool,
/// Continue an in-progress rebase
#[arg(long)]
r#continue: bool,
/// Abort the current rebase
#[arg(long)]
abort: bool,
/// Skip the current patch
#[arg(long)]
skip: bool,
},
/// Find unreachable objects (orphaned commits/blobs/trees) — recovery aid
/// after a destructive operation like reset --hard, force-push, or rebase.
/// By default lists the unreachable objects with a one-line summary.
/// Use --show <oid> to inspect content; --restore to write a blob to disk.
#[command(alias = "fsck", after_help = "Examples:
torii history orphans List unreachable objects
torii history orphans --show abc1234 Print object content (commit/blob)
torii history orphans --restore abc1234 --to f.txt Recover a blob to disk
`torii history fsck` works too — alias kept for users coming from git.")]
Orphans {
/// Show an object's content (commit message + tree, or blob bytes).
#[arg(long, value_name = "OID")]
show: Option<String>,
/// Restore a blob to disk (use with --to).
#[arg(long, value_name = "OID")]
restore: Option<String>,
/// Destination path for --restore.
#[arg(long, value_name = "PATH")]
to: Option<PathBuf>,
},
/// Rewrite author (and optionally committer) identity across history.
///
/// Match a single `--old` identity and replace with `--new`. Use this for
/// one-off renames; for batch rewrites driven by a file see
/// `torii history mailmap apply`.
#[command(after_help = "Examples:
torii history reauthor --old \"outsider <x@y.com>\" --new \"Pasqual <paski@paski.dev>\"
torii history reauthor --old outsider --new \"Pasqual <paski@paski.dev>\" # match by name only
torii history reauthor --old x@y.com --new \"Pasqual <paski@paski.dev>\" # match by email only
torii history reauthor --old ... --new ... --committer # also rewrite committer
torii history reauthor --old ... --new ... --since v0.6.0 # only commits since v0.6.0
torii history reauthor --old ... --new ... --dry-run # preview, no changes
torii history reauthor --old ... --new ... --no-snapshot # skip safety snapshot
torii history reauthor --old ... --new ... --allow-dirty # allow uncommitted changes
History is rewritten in-place. Annotated tags get a new tagger that matches
the rewrite. A safety snapshot is taken by default (revert with
'torii snapshot restore <id>'). If commits are signed, signatures invalidate
— re-sign manually after the rewrite or document the rotation.")]
Reauthor {
/// Identity to match. Accepts "Name <email>", a bare name, or a bare email.
#[arg(long)]
old: String,
/// Replacement identity. Must be in "Name <email>" form.
#[arg(long)]
new: String,
/// Limit rewrite to commits since this revision (exclusive).
#[arg(long, value_name = "REV")]
since: Option<String>,
/// Preview the rewrite without touching the repo.
#[arg(long)]
dry_run: bool,
/// Skip the safety snapshot taken before rewriting.
#[arg(long)]
no_snapshot: bool,
/// Also rewrite the committer (default: only author).
#[arg(long)]
committer: bool,
/// Proceed even if the working tree has uncommitted changes.
#[arg(long)]
allow_dirty: bool,
},
/// Apply a `.mailmap` file (standard git format) across history.
///
/// See <https://git-scm.com/docs/gitmailmap> for the format. Use this for
/// batch identity reconciliation; for a single rename use
/// `torii history reauthor`.
#[command(after_help = "Examples:
torii history mailmap apply Apply repo .mailmap
torii history mailmap apply --file other.mailmap Apply a different file
torii history mailmap apply --since v0.6.0 Limit to a range
torii history mailmap apply --dry-run Preview, no changes
torii history mailmap apply --no-snapshot Skip safety snapshot
Mailmap supports four line forms:
Proper Name <commit@email>
<proper@email> <commit@email>
Proper Name <proper@email> <commit@email>
Proper Name <proper@email> Commit Name <commit@email>")]
Mailmap {
#[command(subcommand)]
action: MailmapCommands,
},
}
#[derive(Subcommand)]
enum MailmapCommands {
/// Apply rewrites from a `.mailmap` file to every reachable commit.
Apply {
/// Mailmap file path (default: `.mailmap` at repo root).
#[arg(long, value_name = "FILE")]
file: Option<PathBuf>,
/// Limit rewrite to commits since this revision (exclusive).
#[arg(long, value_name = "REV")]
since: Option<String>,
/// Preview the rewrite without touching the repo.
#[arg(long)]
dry_run: bool,
/// Skip the safety snapshot taken before rewriting.
#[arg(long)]
no_snapshot: bool,
/// Also rewrite the committer (default: only author).
#[arg(long)]
committer: bool,
/// Proceed even if the working tree has uncommitted changes.
#[arg(long)]
allow_dirty: bool,
},
}
#[derive(Subcommand)]
enum SnapshotCommands {
/// Create a new snapshot
Create {
/// Optional snapshot name/description
#[arg(short, long)]
name: Option<String>,
},
/// List all snapshots
List,
/// Restore from a snapshot
Restore {
/// Snapshot ID to restore
id: String,
},
/// Delete a snapshot
Delete {
/// Snapshot ID to delete
id: String,
},
/// Auto-snapshot configuration
Config {
/// Enable auto-snapshots
#[arg(long)]
enable: bool,
/// Snapshot interval (e.g., 1h, 30m)
#[arg(long)]
interval: Option<String>,
},
/// Save work temporarily (like git stash)
Stash {
/// Name for the stash
#[arg(short, long)]
name: Option<String>,
/// Include untracked files
#[arg(short = 'u', long)]
include_untracked: bool,
},
/// Restore stashed work
Unstash {
/// Stash ID to restore (latest if not specified)
id: Option<String>,
/// Keep the stash after restoring
#[arg(short, long)]
keep: bool,
},
/// `git stash apply` alias — restore without dropping the stash.
/// Equivalent to `torii snapshot unstash --keep [<id>]`.
Apply {
/// Snapshot/stash ID (latest if not specified).
id: Option<String>,
},
/// `git stash pop` alias — restore and drop the stash.
/// Equivalent to `torii snapshot unstash [<id>]`.
Pop {
/// Snapshot/stash ID (latest if not specified).
id: Option<String>,
},
/// `git stash drop` alias — delete a specific snapshot.
/// Equivalent to `torii snapshot delete <id>`.
Drop {
/// Snapshot/stash ID to drop.
id: String,
},
/// Delete every snapshot/stash in this repo. Asks for confirmation
/// unless `--yes` is given.
Clear {
/// Skip the confirmation prompt.
#[arg(short = 'y', long)]
yes: bool,
},
/// Show what's inside a snapshot — branch, commit, timestamp,
/// and a list of files captured.
Show {
/// Snapshot/stash ID.
id: String,
},
/// Undo last operation
Undo,
}
#[derive(Debug, Subcommand)]
enum TagCommands {
/// Create a new tag (or auto-bump the next release tag with --release)
Create {
/// Tag name (omit when using --release)
name: Option<String>,
/// Tag message (creates annotated tag)
#[arg(short, long)]
message: Option<String>,
/// Auto-bump the next version from conventional commits since last tag
#[arg(long)]
release: bool,
/// Force a specific bump (used with --release): major, minor, patch
#[arg(long, requires = "release")]
bump: Option<String>,
/// Preview the next version without creating the tag (used with --release)
#[arg(long, requires = "release")]
dry_run: bool,
},
/// List all tags
List,
/// Delete a tag
Delete {
/// Tag name to delete
name: String,
},
/// Push tags to remote
Push {
/// Specific tag to push (all if not specified)
name: Option<String>,
/// Force-push tags even when the remote ref already exists at a
/// different commit (rewrites remote tag history).
#[arg(short = 'f', long)]
force: bool,
},
/// Show tag details
Show {
/// Tag name
name: String,
},
}
#[derive(Subcommand)]
enum MirrorCommands {
/// Add a mirror (replica by default; use --primary for the source of truth)
Add {
/// Platform (github, gitlab, bitbucket, codeberg)
platform: String,
/// Account type (user or org)
account_type: String,
/// Account name (username or organization)
account: String,
/// Repository name
repo: String,
/// Mark this mirror as the primary (source of truth). Default: replica.
#[arg(long)]
primary: bool,
/// Protocol (ssh or https, defaults to ssh)
#[arg(short, long)]
protocol: Option<String>,
},
/// List all mirrors
List,
/// Sync to all replica mirrors
Sync {
/// Force sync
#[arg(short, long)]
force: bool,
},
/// Promote a mirror to primary (source of truth)
Promote {
/// Platform
platform: String,
/// Account name
account: String,
},
/// Remove a mirror
Remove {
/// Platform
platform: String,
/// Account name
account: String,
},
/// Configure autofetch (automatic fetch from mirrors)
Autofetch {
/// Enable autofetch
#[arg(long)]
enable: bool,
/// Disable autofetch
#[arg(long, conflicts_with = "enable")]
disable: bool,
/// Fetch interval (e.g., 10m, 30s, 2h, 1d)
#[arg(long)]
interval: Option<String>,
/// Show current autofetch status
#[arg(long, conflicts_with_all = ["enable", "disable", "interval"])]
status: bool,
},
}
impl Cli {
pub fn execute(&self) -> Result<()> {
match &self.command {
Commands::Init { path } => {
let repo_path = path.as_deref().unwrap_or(".");
GitRepo::init(repo_path)?;
// Create .toriignore with sensible defaults
let toriignore_path = std::path::Path::new(repo_path).join(".toriignore");
if !toriignore_path.exists() {
std::fs::write(&toriignore_path, crate::toriignore::ToriIgnore::default_content())
.ok();
}
// Scaffold policies/commits.toml so `torii scan --commits` has
// something to read out of the box.
let policies_dir = std::path::Path::new(repo_path).join("policies");
let commits_policy = policies_dir.join("commits.toml");
if !commits_policy.exists() {
let _ = std::fs::create_dir_all(&policies_dir);
let _ = std::fs::write(&commits_policy, DEFAULT_COMMITS_POLICY);
}
// Sync .toriignore → .git/info/exclude immediately
let repo = GitRepo::open(repo_path)?;
repo.sync_toriignore()?;
println!("✅ Initialized repository at {}", repo_path);
println!(" Created .toriignore with default patterns");
println!(" Created policies/commits.toml (run: torii scan --commits)");
}
Commands::Save { message, all, files, amend, revert, reset, reset_mode, unstage, skip_hooks } => {
let repo = GitRepo::open(".")?;
if *unstage {
if *all {
if !files.is_empty() {
anyhow::bail!("Pass either --all or specific paths, not both");
}
repo.unstage_all()?;
println!("✅ Unstaged all paths");
} else {
if files.is_empty() {
anyhow::bail!("Provide at least one path or use --all");
}
repo.unstage(files)?;
println!("✅ Unstaged {} path(s)", files.len());
}
return Ok(());
}
if let Some(commit_hash) = reset {
repo.reset_commit(commit_hash, reset_mode)?;
println!("✅ Reset to commit: {} (mode: {})", commit_hash, reset_mode);
} else if let Some(commit_hash) = revert {
repo.revert_commit(commit_hash)?;
println!("✅ Reverted commit: {}", commit_hash);
} else {
if *all && !files.is_empty() {
anyhow::bail!("Cannot use --all and specific files at the same time");
}
if *all {
repo.add_all()?;
} else if !files.is_empty() {
repo.add(files)?;
}
// Scan staged files for sensitive data before committing
let repo_path = std::path::Path::new(".");
// Load .toriignore (sections: secrets/size/hooks)
let ti = crate::toriignore::ToriIgnore::load(repo_path)?;
// [size] guard
let staged = scanner::staged_paths(repo_path).unwrap_or_default();
crate::hooks::check_size(&ti.size, repo_path, &staged)?;
// [hooks] pre-save
if !*skip_hooks {
crate::hooks::pre_save(&ti.hooks, repo_path)?;
}
let mut findings = scanner::scan_staged(repo_path)?;
// [secrets] custom regex rules
findings.extend(scanner::scan_staged_with_custom(repo_path, &ti.secrets)?);
if !findings.is_empty() {
println!("⚠️ Sensitive data detected in staged files:\n");
for f in &findings {
if f.line == 0 {
println!(" {} — {}", f.file, f.pattern_name);
} else {
println!(" {}:{} — {}", f.file, f.line, f.pattern_name);
}
println!(" {}\n", f.preview);
}
println!("💡 Tip: use .env.example for placeholder values — those files are always safe to commit.");
print!(" Continue anyway? [y/N] ");
use std::io::Write;
std::io::stdout().flush()?;
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
if !input.trim().eq_ignore_ascii_case("y") {
println!("❌ Commit cancelled.");
return Ok(());
}
}
let msg = message.as_deref().ok_or_else(|| anyhow::anyhow!(
"--message/-m is required for commit/amend"
))?;
if *amend {
repo.commit_amend(msg)?;
println!("✅ Commit amended: {}", msg);
} else {
repo.commit(msg)?;
println!("✅ Changes saved: {}", msg);
}
if !*skip_hooks {
crate::hooks::post_save(&ti.hooks, repo_path);
}
}
}
Commands::Sync { branch, pull, push, force, fetch, merge, rebase, preview, verify, skip_hooks } => {
let repo = GitRepo::open(".")?;
let repo_path = std::path::Path::new(".");
let ti = crate::toriignore::ToriIgnore::load(repo_path)?;
if !*skip_hooks {
crate::hooks::pre_sync(&ti.hooks, repo_path)?;
}
if *verify {
repo.verify_remote()?;
return Ok(());
}
if let Some(branch_name) = branch {
if *preview {
println!("🔍 Preview: Would integrate branch '{}'", branch_name);
println!("💡 Recommendation: Use merge for feature branches, rebase for clean history");
} else if *merge {
println!("🔀 Merging branch '{}'...", branch_name);
repo.merge_branch(branch_name)?;
println!("✅ Merged branch: {}", branch_name);
} else if *rebase {
println!("🔄 Rebasing onto branch '{}'...", branch_name);
repo.rebase_branch(branch_name)?;
println!("✅ Rebased onto: {}", branch_name);
} else {
// Smart integration (default to merge for now)
println!("🔀 Integrating branch '{}'...", branch_name);
repo.merge_branch(branch_name)?;
println!("✅ Integrated branch: {}", branch_name);
}
} else if *fetch {
repo.fetch()?;
println!("✅ Fetched from remote");
} else if *force {
repo.push(true)?;
println!("✅ Force synced with remote");
let mirror_mgr = MirrorManager::new(".")?;
mirror_mgr.sync_replicas_if_any(true)?;
} else if *pull {
repo.pull()?;
println!("✅ Pulled from remote");
} else if *push {
repo.push(false)?;
println!("✅ Pushed to remote");
let mirror_mgr = MirrorManager::new(".")?;
mirror_mgr.sync_replicas_if_any(false)?;
} else {
// Default: pull then push
repo.pull()?;
repo.push(false)?;
println!("✅ Synced with remote");
// Also sync replica mirrors if any are configured
let mirror_mgr = MirrorManager::new(".")?;
mirror_mgr.sync_replicas_if_any(false)?;
}
if !*skip_hooks {
crate::hooks::post_sync(&ti.hooks, repo_path);
}
}
Commands::Status { tracked, null } => {
if *tracked {
// ls-files behaviour: walk the index and print each entry.
let repo = git2::Repository::open(".")?;
let index = repo.index()?;
let sep = if *null { '\0' } else { '\n' };
use std::io::Write;
let stdout = std::io::stdout();
let mut out = stdout.lock();
for entry in index.iter() {
let path = String::from_utf8_lossy(&entry.path);
write!(out, "{}{}", path, sep)?;
}
} else {
let repo = GitRepo::open(".")?;
repo.status()?;
}
}
Commands::Log { count, oneline, graph, author, since, until, grep, stat, reflog } => {
let repo = GitRepo::open(".")?;
if *reflog {
repo.show_reflog(count.unwrap_or(20))?;
} else {
repo.log(*count, *oneline, *graph, author.as_deref(), since.as_deref(), until.as_deref(), grep.as_deref(), *stat)?;
}
}
Commands::Diff { staged, last } => {
let repo = GitRepo::open(".")?;
repo.diff(*staged, *last)?;
}
Commands::Blame { file, lines } => {
eprintln!(
"⚠ 'torii blame' is deprecated and will be removed in 0.8.\n \
Use 'torii show {} --blame' instead.",
file
);
let repo = GitRepo::open(".")?;
repo.blame(file, lines.as_deref())?;
}
Commands::Scan { history, commits, policy_file, limit } => {
if *commits {
run_commit_scan(policy_file.as_deref(), *limit)?;
} else {
run_scan(*history)?;
}
}
Commands::CherryPick { commit, r#continue, abort } => {
let repo = GitRepo::open(".")?;
if *r#continue {
repo.cherry_pick_continue()?;
} else if *abort {
repo.cherry_pick_abort()?;
} else {
let hash = commit.as_deref().ok_or_else(|| anyhow::anyhow!("Commit hash required: torii cherry-pick <hash>"))?;
repo.cherry_pick(hash)?;
}
}
Commands::Branch { name, create, orphan, delete, force, delete_remote, list, rename, all } => {
let repo = GitRepo::open(".")?;
if *list || *all {
let branches = repo.list_branches()?;
println!("📋 Branches:");
for branch in branches {
println!(" • {}", branch);
}
if *all {
let remote_branches = repo.list_remote_branches()?;
println!("\n📡 Remote branches:");
if remote_branches.is_empty() {
println!(" (none — run 'torii sync --fetch' to update remote refs)");
} else {
for branch in remote_branches {
println!(" • {}", branch);
}
}
}
} else if let Some(branch_name) = delete_remote {
let git_repo = git2::Repository::discover(".")?;
let remotes = git_repo.remotes()?;
let mut deleted = vec![];
let mut errors = vec![];
for remote_name in remotes.iter().flatten() {
let result = std::process::Command::new("git")
.args(["push", remote_name, "--delete", branch_name])
.output();
match result {
Ok(o) if o.status.success() => deleted.push(remote_name.to_string()),
Ok(o) => errors.push(format!("{}: {}", remote_name, String::from_utf8_lossy(&o.stderr).trim().to_string())),
Err(e) => errors.push(format!("{}: {}", remote_name, e)),
}
}
if !deleted.is_empty() {
println!("✅ Deleted '{}' on: {}", branch_name, deleted.join(", "));
}
if !errors.is_empty() {
for e in &errors { eprintln!("⚠️ {}", e); }
}
if deleted.is_empty() {
anyhow::bail!("Could not delete '{}' on any remote", branch_name);
}
} else if let Some(branch_name) = delete {
if *force {
let git_repo = git2::Repository::discover(".")?;
let mut branch = git_repo.find_branch(branch_name, git2::BranchType::Local)?;
branch.delete()?;
} else {
repo.delete_branch(branch_name)?;
}
println!("✅ Deleted branch: {}", branch_name);
} else if let Some(new_name) = rename {
let current = repo.get_current_branch()?;
repo.rename_branch(¤t, new_name)?;
println!("✅ Renamed branch {} to {}", current, new_name);
} else if let Some(branch_name) = name {
if *orphan && !*create {
anyhow::bail!("--orphan requires -c/--create");
}
if *create && *orphan {
repo.create_orphan_branch(branch_name)?;
println!("✅ Created orphan branch: {} (no parents — first commit will be a new root)", branch_name);
} else if *create {
repo.create_branch(branch_name)?;
repo.switch_branch(branch_name)?;
println!("✅ Created and switched to branch: {}", branch_name);
} else {
repo.switch_branch(branch_name)?;
println!("✅ Switched to branch: {}", branch_name);
}
} else {
// Default: list branches
let branches = repo.list_branches()?;
println!("📋 Branches:");
for branch in branches {
println!(" • {}", branch);
}
}
}
Commands::Clone { source, args, directory, protocol } => {
// Match git clone's positional shape:
// torii clone <platform> <user/repo> [<path>]
// torii clone <url> [<path>]
// The trailing path arg silently used to be ignored, surprising
// users coming from `git clone <url> <path>`.
//
// Disambiguation: if `source` already looks like a URL/path
// (http(s)://, git://, ssh://, file://, /abs, ./rel,
// user@host:path), treat the first positional `args[0]` as
// the destination — NOT as user/repo. Without this guard,
// `torii clone file:///tmp/foo dest` errored with
// "Unknown platform 'file:///tmp/foo'".
let source_is_url = looks_like_clone_url(source);
let url = if !args.is_empty() && !source_is_url {
// Shorthand: torii clone <platform> <user/repo>
let platform = source;
let user_repo = &args[0];
// Protocol priority: --protocol flag > config > auto-detect
let use_ssh = match protocol.as_deref() {
Some("https") | Some("http") => false,
Some("ssh") => true,
_ => {
let cfg = ToriiConfig::load_global().unwrap_or_default();
if cfg.mirror.default_protocol == "https" {
false
} else {
SshHelper::has_ssh_keys()
}
}
};
let (ssh_host, https_host) = match platform.as_str() {
"github" => ("github.com", "github.com"),
"gitlab" => ("gitlab.com", "gitlab.com"),
"codeberg" => ("codeberg.org", "codeberg.org"),
"bitbucket" => ("bitbucket.org", "bitbucket.org"),
"gitea" => ("gitea.com", "gitea.com"),
"forgejo" => ("codeberg.org", "codeberg.org"),
_ => anyhow::bail!(
"Unknown platform '{}'. Supported: github, gitlab, codeberg, bitbucket, gitea, forgejo",
platform
),
};
if use_ssh {
format!("git@{}:{}.git", ssh_host, user_repo)
} else {
format!("https://{}/{}.git", https_host, user_repo)
}
} else if looks_like_clone_url(source) {
source.clone()
} else {
anyhow::bail!(
"Usage:\n torii clone <platform> <user/repo> e.g. torii clone github user/repo\n torii clone <platform> <user/repo> --protocol https\n torii clone <url> e.g. torii clone https://github.com/user/repo.git\n torii clone <local-path-or-file:///url> e.g. torii clone /tmp/source.git"
)
};
// Resolve destination. Precedence:
// 1. -d / --directory flag
// 2. trailing positional arg (git-style):
// torii clone <plat> <user/repo> <path> → args[1]
// torii clone <url> <path> → args[0]
// 3. derive from URL (default)
let positional_dest: Option<&str> = if source_is_url {
// URL form: first positional after the URL is the dest.
args.first().map(|s| s.as_str())
} else if !args.is_empty() {
// Shorthand: args[0] is user/repo, args[1] is dest.
args.get(1).map(|s| s.as_str())
} else {
None
};
let target_dir = directory.as_deref().or(positional_dest);
GitRepo::clone_repo(&url, target_dir)?;
let dir_name = target_dir.unwrap_or_else(|| {
url.split('/').last().unwrap_or("repo").trim_end_matches(".git")
});
println!("✅ Cloned repository to: {}", dir_name);
}
Commands::Tag { action } => {
let repo = GitRepo::open(".")?;
match action {
TagCommands::Create { name, message, release, bump, dry_run } => {
if *release {
let tagger = AutoTagger::new(repo);
let current = tagger.get_latest_version()?;
let next = if let Some(bump_str) = bump {
use crate::versioning::semver::VersionBump;
let b = match bump_str.as_str() {
"major" => VersionBump::Major,
"minor" => VersionBump::Minor,
"patch" => VersionBump::Patch,
_ => anyhow::bail!("Invalid bump: use major, minor or patch"),
};
let base = current.clone().unwrap_or_else(crate::versioning::semver::Version::initial);
base.bump(b)
} else {
tagger.calculate_next_version_from_log()?
.ok_or_else(|| anyhow::anyhow!("No releasable commits found since last tag (need feat: or fix:)"))?
};
println!("📦 Current version: {}", current.map(|v| v.to_string()).unwrap_or_else(|| "none".to_string()));
println!("🚀 Next version: v{}", next);
if *dry_run {
println!(" (dry run — no tag created)");
} else {
tagger.create_tag(&next, &format!("Release v{}", next))?;
println!("💡 Push with: torii sync --push");
}
} else {
let tag_name = name.as_deref().ok_or_else(|| anyhow::anyhow!(
"Tag name required (or use --release to auto-bump)"
))?;
repo.create_tag(tag_name, message.as_deref())?;
println!("✅ Tag created: {}", tag_name);
}
}
TagCommands::List => {
repo.list_tags()?;
}
TagCommands::Delete { name } => {
repo.delete_tag(name)?;
println!("✅ Tag deleted: {}", name);
}
TagCommands::Push { name, force } => {
repo.push_tags(name.as_deref(), *force)?;
let force_note = if *force { " (force)" } else { "" };
if let Some(tag) = name {
println!("✅ Pushed tag: {}{}", tag, force_note);
} else {
println!("✅ Pushed all tags{}", force_note);
}
}
TagCommands::Show { name } => {
repo.show_tag(name)?;
}
}
}
Commands::Snapshot { action } => {
let snapshot_mgr = SnapshotManager::new(".")?;
match action {
SnapshotCommands::Create { name } => {
let snapshot_id = snapshot_mgr.create_snapshot(name.as_deref())?;
println!("✅ Snapshot created: {}", snapshot_id);
}
SnapshotCommands::List => {
snapshot_mgr.list_snapshots()?;
}
SnapshotCommands::Restore { id } => {
snapshot_mgr.restore_snapshot(id)?;
println!("✅ Restored snapshot: {}", id);
}
SnapshotCommands::Delete { id } => {
snapshot_mgr.delete_snapshot(id)?;
println!("✅ Deleted snapshot: {}", id);
}
SnapshotCommands::Config { enable, interval } => {
let interval_minutes = interval.as_ref().and_then(|s| s.parse::<u32>().ok());
snapshot_mgr.configure_auto_snapshot(*enable, interval_minutes)?;
println!("✅ Auto-snapshot configuration updated");
}
SnapshotCommands::Stash { name, include_untracked } => {
snapshot_mgr.stash(name.as_deref(), *include_untracked)?;
}
SnapshotCommands::Unstash { id, keep } => {
snapshot_mgr.unstash(id.as_deref(), *keep)?;
}
SnapshotCommands::Apply { id } => {
snapshot_mgr.unstash(id.as_deref(), true)?;
}
SnapshotCommands::Pop { id } => {
snapshot_mgr.unstash(id.as_deref(), false)?;
}
SnapshotCommands::Drop { id } => {
snapshot_mgr.delete_snapshot(id)?;
println!("✅ Dropped snapshot: {}", id);
}
SnapshotCommands::Clear { yes } => {
if !*yes {
use std::io::{self, BufRead, IsTerminal, Write};
if !io::stdin().is_terminal() {
anyhow::bail!("Refusing to clear without --yes when there's no tty to prompt.");
}
print!("⚠ Delete ALL snapshots in this repo? [y/N] ");
io::stdout().flush().ok();
let mut line = String::new();
io::stdin().lock().read_line(&mut line)?;
if !matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes") {
println!("Aborted.");
return Ok(());
}
}
let count = snapshot_mgr.clear_all()?;
println!("🧹 Cleared {count} snapshot(s).");
}
SnapshotCommands::Show { id } => {
snapshot_mgr.show(id)?;
}
SnapshotCommands::Undo => {
snapshot_mgr.undo()?;
}
}
}
Commands::Mirror { action } => {
let mirror_mgr = MirrorManager::new(".")?;
match action {
MirrorCommands::Add { platform, account_type, account, repo, primary, protocol } => {
let acc_type = parse_account_type(account_type)?;
let proto = parse_protocol(protocol.as_ref());
mirror_mgr.add_mirror(platform, acc_type, account, repo, proto, *primary)?;
let kind = if *primary { "Primary" } else { "Replica" };
println!("✅ {} mirror added: {}/{} on {}", kind, account, repo, platform);
}
MirrorCommands::List => {
mirror_mgr.list_mirrors()?;
}
MirrorCommands::Sync { force } => {
mirror_mgr.sync_all(*force)?;
}
MirrorCommands::Promote { platform, account } => {
mirror_mgr.set_primary(platform, account)?;
println!("✅ Promoted to primary: {}/{}", platform, account);
}
MirrorCommands::Remove { platform, account } => {
mirror_mgr.remove_mirror_by_account(platform, account)?;
println!("✅ Mirror removed: {}/{}", platform, account);
}
MirrorCommands::Autofetch { enable, disable, interval, status } => {
if *status {
mirror_mgr.show_autofetch_status()?;
} else if *enable {
let interval_minutes = if let Some(interval_str) = interval {
Some(parse_duration(interval_str)?)
} else {
None
};
mirror_mgr.configure_autofetch(true, interval_minutes)?;
} else if *disable {
mirror_mgr.configure_autofetch(false, None)?;
} else {
mirror_mgr.show_autofetch_status()?;
}
}
}
}
Commands::Auth { action } => {
run_auth(action)?;
}
Commands::Config { action } => {
match action {
ConfigCommands::Set { key, value, local } => {
if *local {
let mut config = ToriiConfig::load_local(".")?;
config.set(key, value)?;
config.save_local(".")?;
println!("✅ Local config updated: {} = {}", key, value);
} else {
let mut config = ToriiConfig::load_global()?;
config.set(key, value)?;
config.save_global()?;
println!("✅ Global config updated: {} = {}", key, value);
}
}
ConfigCommands::Get { key, local } => {
let config = if *local {
ToriiConfig::load_local(".")?
} else {
ToriiConfig::load_global()?
};
if let Some(value) = config.get(key) {
println!("{}", value);
} else {
println!("❌ Config key not found: {}", key);
}
}
ConfigCommands::List { local } => {
let config = if *local {
ToriiConfig::load_local(".")?
} else {
ToriiConfig::load_global()?
};
let scope = if *local { "Local" } else { "Global" };
println!("⚙️ {} Configuration:\n", scope);
for (key, value) in config.list() {
println!(" {} = {}", key, value);
}
}
ConfigCommands::Edit { local } => {
let config_path = if *local {
std::path::PathBuf::from(".").join(".torii").join("config.toml")
} else {
dirs::config_dir()
.ok_or_else(|| anyhow::anyhow!("Could not determine config directory"))?
.join("torii")
.join("config.toml")
};
// Ensure config exists
if *local {
let config = ToriiConfig::load_local(".")?;
config.save_local(".")?;
} else {
let config = ToriiConfig::load_global()?;
config.save_global()?;
}
// Get editor
let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());
// Open editor
let status = std::process::Command::new(&editor)
.arg(&config_path)
.status()?;
if status.success() {
println!("✅ Configuration edited");
} else {
println!("❌ Editor exited with error");
}
}
ConfigCommands::Reset { local } => {
let config = ToriiConfig::default();
if *local {
config.save_local(".")?;
println!("✅ Local configuration reset to defaults");
} else {
config.save_global()?;
println!("✅ Global configuration reset to defaults");
}
}
ConfigCommands::CheckSsh => {
run_ssh_check();
}
}
}
Commands::Remote { action } => {
match action {
RemoteCommands::Create { platforms, name, description, public, private: _, push, namespace } => {
let platforms: Vec<String> = platforms.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
if platforms.is_empty() {
anyhow::bail!("At least one platform is required");
}
let visibility = if *public { Visibility::Public } else { Visibility::Private };
let multi = platforms.len() > 1;
// Resolve namespace + repo name. Precedence:
// --namespace <owner> wins (NAME stays bare).
// else, last `/` in NAME splits owner/repo (GitLab
// subgroups stay in the owner segment, e.g.
// `engineering/web/api` → owner=`engineering/web`,
// repo=`api`).
let (resolved_ns, resolved_name): (Option<String>, String) = match namespace {
Some(ns) => (Some(ns.clone()), name.clone()),
None => match name.rsplit_once('/') {
Some((owner, repo)) => (Some(owner.to_string()), repo.to_string()),
None => (None, name.clone()),
},
};
let mut created: Vec<(String, crate::remote::RemoteRepo)> = Vec::new();
for platform in &platforms {
print!("🚀 {} - ", platform);
match get_platform_client(platform) {
Ok(client) => match client.create_repo(&resolved_name, description.as_deref(), visibility.clone(), resolved_ns.as_deref()) {
Ok(repo) => {
println!("✅ Created");
println!(" URL: {}", repo.url);
println!(" SSH: {}", repo.ssh_url);
created.push((platform.clone(), repo));
}
Err(e) => println!("❌ Failed: {}", e),
},
Err(e) => println!("❌ Platform error: {}", e),
}
}
if multi {
println!("\n📊 Created on {}/{} platforms", created.len(), platforms.len());
}
if *push && !created.is_empty() {
println!("\n📤 Linking remotes and pushing...");
let git_repo = GitRepo::open(".")?;
for (idx, (platform, repo)) in created.iter().enumerate() {
let remote_name = if !multi || idx == 0 { "origin".to_string() } else { platform.clone() };
let _ = git_repo.repository().remote(&remote_name, &repo.ssh_url);
}
git_repo.push(false)?;
println!("✅ Pushed");
}
}
RemoteCommands::Delete { platforms, owner, repo, yes } => {
let platforms: Vec<String> = platforms.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
if platforms.is_empty() {
anyhow::bail!("At least one platform is required");
}
if !yes {
println!("⚠️ Are you sure you want to delete {}/{} on {} platform(s)? This cannot be undone!", owner, repo, platforms.len());
println!(" Run with --yes to confirm");
return Ok(());
}
for platform in &platforms {
print!("🗑️ {} - ", platform);
match get_platform_client(platform) {
Ok(client) => match client.delete_repo(owner, repo) {
Ok(_) => println!("✅ Deleted"),
Err(e) => println!("❌ Failed: {}", e),
},
Err(e) => println!("❌ Platform error: {}", e),
}
}
return Ok(());
}
RemoteCommands::Visibility { platform, owner, repo, public, private } => {
let client = get_platform_client(platform)?;
let visibility = if *public {
Visibility::Public
} else if *private {
Visibility::Private
} else {
println!("❌ Specify --public or --private");
return Ok(());
};
println!("🔒 Changing visibility of {}/{} to {:?}...", owner, repo, visibility);
client.set_visibility(owner, repo, visibility)?;
println!("✅ Visibility updated");
}
RemoteCommands::Configure {
platform, owner, repo, description, homepage, default_branch,
enable_issues, disable_issues, enable_wiki, disable_wiki,
enable_projects, disable_projects
} => {
let client = get_platform_client(platform)?;
// Build settings
let mut settings = RepoSettings::default();
settings.description = description.clone();
settings.homepage = homepage.clone();
settings.default_branch = default_branch.clone();
// Build features
let mut features = RepoFeatures::default();
if *enable_issues { features.issues = Some(true); }
if *disable_issues { features.issues = Some(false); }
if *enable_wiki { features.wiki = Some(true); }
if *disable_wiki { features.wiki = Some(false); }
if *enable_projects { features.projects = Some(true); }
if *disable_projects { features.projects = Some(false); }
println!("⚙️ Configuring repository {}/{}...", owner, repo);
// Update settings if any
if settings.description.is_some() || settings.homepage.is_some() || settings.default_branch.is_some() {
client.update_repo(owner, repo, settings)?;
}
// Update features if any
if features.issues.is_some() || features.wiki.is_some() || features.projects.is_some() {
client.configure_features(owner, repo, features)?;
}
println!("✅ Repository configured");
}
RemoteCommands::Info { platform, owner, repo } => {
let client = get_platform_client(platform)?;
println!("📊 Fetching repository information...");
let repo_info = client.get_repo(owner, repo)?;
println!("\n📦 Repository: {}", repo_info.name);
if let Some(desc) = &repo_info.description {
println!(" Description: {}", desc);
}
println!(" Visibility: {:?}", repo_info.visibility);
println!(" Default Branch: {}", repo_info.default_branch);
println!(" URL: {}", repo_info.url);
println!(" SSH: {}", repo_info.ssh_url);
}
RemoteCommands::Local => {
let repo = GitRepo::open(".")?;
let git_repo = repo.repository();
let remotes = git_repo.remotes()?;
if remotes.is_empty() {
println!("No remotes configured");
} else {
for name in remotes.iter().flatten() {
if let Ok(remote) = git_repo.find_remote(name) {
let url = remote.url().unwrap_or("(no url)");
println!(" {} {}", name, url);
}
}
}
}
RemoteCommands::Link { name, platform, repo, https, url, force } => {
let resolved_url = if let Some(u) = url {
u.clone()
} else {
let plat = platform.as_deref().ok_or_else(|| anyhow::anyhow!(
"Provide --url <URL> or <platform> <owner>/<repo>"
))?;
let owner_repo = repo.as_deref().ok_or_else(|| anyhow::anyhow!(
"Missing <owner>/<repo>"
))?;
let (ssh_host, https_host) = match plat {
"github" => ("github.com", "github.com"),
"gitlab" => ("gitlab.com", "gitlab.com"),
"codeberg" => ("codeberg.org", "codeberg.org"),
"bitbucket" => ("bitbucket.org", "bitbucket.org"),
"gitea" => ("gitea.com", "gitea.com"),
"forgejo" => ("codeberg.org", "codeberg.org"),
"sourcehut" => ("git.sr.ht", "git.sr.ht"),
_ => anyhow::bail!(
"Unknown platform '{}'. Supported: github, gitlab, codeberg, bitbucket, gitea, forgejo, sourcehut",
plat
),
};
let use_ssh = if *https { false } else { SshHelper::has_ssh_keys() };
if use_ssh {
format!("git@{}:{}.git", ssh_host, owner_repo)
} else {
format!("https://{}/{}.git", https_host, owner_repo)
}
};
let git_repo = GitRepo::open(".")?;
let inner = git_repo.repository();
let exists = inner.find_remote(name).is_ok();
if exists {
if !*force {
anyhow::bail!(
"Remote '{}' already exists. Use --force to overwrite, or 'torii remote local' to inspect.",
name
);
}
inner.remote_set_url(name, &resolved_url)?;
println!("🔗 Updated remote '{}' → {}", name, resolved_url);
} else {
inner.remote(name, &resolved_url)?;
println!("🔗 Linked remote '{}' → {}", name, resolved_url);
}
}
RemoteCommands::Unlink { name, yes } => {
let git_repo = GitRepo::open(".")?;
let inner = git_repo.repository();
let remote = inner.find_remote(name).map_err(|_| anyhow::anyhow!(
"No local remote named '{}'. Run `torii remote local` to list.",
name
))?;
let url = remote.url().unwrap_or("(no url)").to_string();
drop(remote);
if !*yes {
use std::io::{BufRead, Write};
println!("⚠️ Drop local alias '{}' → {}?", name, url);
println!(" (Does NOT touch the remote on the platform.)");
print!(" Confirm [y/N]: ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin().lock().read_line(&mut line)?;
let ans = line.trim().to_ascii_lowercase();
if !matches!(ans.as_str(), "y" | "yes") {
println!("Aborted.");
return Ok(());
}
}
inner.remote_delete(name)
.map_err(|e| anyhow::anyhow!("delete remote '{}': {}", name, e))?;
println!("🔗 Unlinked local remote '{}' (platform untouched)", name);
}
RemoteCommands::List { platform } => {
let client = get_platform_client(platform)?;
println!("📋 Fetching repositories from {}...", platform);
let repos = client.list_repos()?;
if repos.is_empty() {
println!("No repositories found");
} else {
println!("\n📦 Repositories ({}):\n", repos.len());
for repo in repos {
println!(" • {} - {:?}", repo.name, repo.visibility);
if let Some(desc) = &repo.description {
println!(" {}", desc);
}
}
}
}
RemoteCommands::Refs { target, heads, tags } => {
// Resolve target — local remote alias or URL.
let repo = git2::Repository::open(".")?;
let mut remote = match repo.find_remote(target) {
Ok(r) => r,
Err(_) => repo.remote_anonymous(target)?,
};
// Connect read-only with default auth callbacks.
let mut callbacks = git2::RemoteCallbacks::new();
callbacks.credentials(|url, user, allowed| {
// SSH agent first (most common); fall back to
// userpass-plaintext nothing — let libgit2 fail
// cleanly so the user knows to set up auth.
if allowed.contains(git2::CredentialType::SSH_KEY) {
git2::Cred::ssh_key_from_agent(user.unwrap_or("git"))
} else {
Err(git2::Error::from_str(&format!(
"no credentials available for {url}"
)))
}
});
remote.connect_auth(git2::Direction::Fetch, Some(callbacks), None)?;
let list = remote.list()?;
for head in list {
let name = head.name();
let keep = match (*heads, *tags) {
(true, false) => name.starts_with("refs/heads/"),
(false, true) => name.starts_with("refs/tags/"),
_ => true,
};
if keep {
println!("{}\t{}", head.oid(), name);
}
}
}
}
}
Commands::Show { object, blame, lines } => {
let repo = GitRepo::open(".")?;
if *blame {
let file = object.as_deref().ok_or_else(|| anyhow::anyhow!("File path required for --blame"))?;
repo.blame(file, lines.as_deref())?;
} else {
repo.show(object.as_deref())?;
}
}
Commands::History { action } => {
let repo = GitRepo::open(".")?;
match action {
HistoryCommands::Rewrite { start, end } => {
repo.rewrite_history(start, end)?;
println!("✅ History rewritten successfully");
}
HistoryCommands::Compact => {
repo.clean_history()?;
println!("✅ Repository compacted (objects repacked, reflog expired)");
}
HistoryCommands::Clean => {
eprintln!(
"⚠ 'torii history clean' is deprecated and will be removed in 0.8.\n \
Use 'torii history compact' (or 'gc' alias) instead.\n \
Heads up: 'torii clean' (top-level) now exists as untracked-file cleanup."
);
repo.clean_history()?;
println!("✅ Repository compacted");
}
HistoryCommands::RemoveFile { file } => {
repo.remove_file_from_history(file)?;
}
HistoryCommands::Rebase { target, interactive, todo_file, root, r#continue, abort, skip } => {
if *r#continue {
repo.rebase_continue()?;
} else if *abort {
repo.rebase_abort()?;
} else if *skip {
repo.rebase_skip()?;
} else if *root {
if let Some(todo) = todo_file {
repo.rebase_root_with_todo(todo)?;
} else {
repo.rebase_root_interactive()?;
}
} else if let Some(todo) = todo_file {
let base = target.as_deref().ok_or_else(|| anyhow::anyhow!("Target required: torii history rebase <base> --todo-file plan.txt (or use --root)"))?;
repo.rebase_with_todo(base, todo)?;
} else if *interactive {
let base = target.as_deref().ok_or_else(|| anyhow::anyhow!("Target required: torii history rebase HEAD~3 --interactive (or use --root)"))?;
repo.rebase_interactive(base)?;
} else if let Some(base) = target {
repo.rebase_branch(base)?;
println!("✅ Rebased onto: {}", base);
} else {
anyhow::bail!("Specify a target or use --root / --interactive / --todo-file / --continue / --abort / --skip");
}
}
HistoryCommands::Orphans { show, restore, to } => {
run_fsck(show.as_deref(), restore.as_deref(), to.as_deref())?;
}
HistoryCommands::Reauthor {
old,
new,
since,
dry_run,
no_snapshot,
committer,
allow_dirty,
} => {
use crate::history_reauthor;
let old_m = history_reauthor::OldMatcher::parse_loose(old)?;
let new_id = history_reauthor::Identity::parse_full(new)?;
let opts = history_reauthor::Options {
since: since.clone(),
dry_run: *dry_run,
no_snapshot: *no_snapshot,
committer: *committer,
allow_dirty: *allow_dirty,
};
let stats = history_reauthor::reauthor(
std::path::Path::new("."),
old_m,
new_id,
&opts,
)?;
history_reauthor::print_summary(&stats, *dry_run);
}
HistoryCommands::Mailmap { action } => match action {
MailmapCommands::Apply {
file,
since,
dry_run,
no_snapshot,
committer,
allow_dirty,
} => {
use crate::history_reauthor;
let mailmap_path = file
.clone()
.unwrap_or_else(|| PathBuf::from(".mailmap"));
if !mailmap_path.exists() {
anyhow::bail!(
"mailmap file not found: {}",
mailmap_path.display()
);
}
let opts = history_reauthor::Options {
since: since.clone(),
dry_run: *dry_run,
no_snapshot: *no_snapshot,
committer: *committer,
allow_dirty: *allow_dirty,
};
let stats = history_reauthor::mailmap_apply(
std::path::Path::new("."),
&mailmap_path,
&opts,
)?;
history_reauthor::print_summary(&stats, *dry_run);
}
},
}
}
Commands::Workspace { action } => {
use crate::workspace::WorkspaceManager;
match action {
WorkspaceCommands::Add { workspace, path } => {
WorkspaceManager::add(workspace, path)?;
}
WorkspaceCommands::Remove { workspace, path } => {
WorkspaceManager::remove(workspace, path)?;
}
WorkspaceCommands::Delete { workspace } => {
WorkspaceManager::delete(workspace)?;
}
WorkspaceCommands::List => {
WorkspaceManager::list()?;
}
WorkspaceCommands::Status { workspace } => {
WorkspaceManager::status(workspace)?;
}
WorkspaceCommands::Save { workspace, message, all } => {
WorkspaceManager::save(workspace, message, *all)?;
}
WorkspaceCommands::Sync { workspace, force } => {
WorkspaceManager::sync(workspace, *force)?;
}
}
}
Commands::Pr { action } => {
use crate::pr::{get_pr_client, detect_platform_from_remote, CreatePrOptions, MergeMethod};
let repo_path = std::env::current_dir()
.unwrap_or_else(|_| std::path::PathBuf::from("."))
.to_string_lossy().to_string();
let (platform, owner, repo_name) = detect_platform_from_remote(&repo_path)
.ok_or_else(|| crate::error::ToriiError::InvalidConfig(
"Could not detect platform from remote. Is 'origin' set to a GitHub/GitLab URL?".to_string()
))?;
let client = get_pr_client(&platform)?;
match action {
PrCommands::List { state } => {
let prs = client.list(&owner, &repo_name, state)?;
if prs.is_empty() {
println!("No {} pull requests.", state);
} else {
for pr in &prs {
let draft = if pr.draft { " [draft]" } else { "" };
let merge = match pr.mergeable {
Some(true) => " ✓",
Some(false) => " ✗",
None => "",
};
println!("#{:<5} {}{}{}", pr.number, pr.title, draft, merge);
println!(" {} → {} by {} {}", pr.head, pr.base, pr.author, pr.created_at);
println!(" {}", pr.url);
println!();
}
}
}
PrCommands::Create { title, base, head, description, draft } => {
let head_branch = if let Some(h) = head {
h.clone()
} else {
let repo = git2::Repository::discover(&repo_path)
.map_err(crate::error::ToriiError::Git)?;
repo.head().ok()
.and_then(|h| h.shorthand().map(|s| s.to_string()))
.unwrap_or_else(|| "HEAD".to_string())
};
let opts = CreatePrOptions {
title: title.clone(),
body: description.clone(),
head: head_branch,
base: base.clone(),
draft: *draft,
};
let pr = client.create(&owner, &repo_name, opts)?;
println!("Created PR #{}: {}", pr.number, pr.title);
println!("{}", pr.url);
}
PrCommands::Merge { number, method } => {
let merge_method = match method.as_str() {
"squash" => MergeMethod::Squash,
"rebase" => MergeMethod::Rebase,
_ => MergeMethod::Merge,
};
client.merge(&owner, &repo_name, *number, merge_method)?;
println!("Merged PR #{}", number);
}
PrCommands::Close { number } => {
client.close(&owner, &repo_name, *number)?;
println!("Closed PR #{}", number);
}
PrCommands::Checkout { number } => {
let pr = client.get(&owner, &repo_name, *number)?;
let branch = client.checkout_branch(&pr);
let status = std::process::Command::new("torii")
.args(["branch", &branch])
.status();
match status {
Ok(s) if s.success() => println!("Checked out branch: {}", branch),
_ => eprintln!("Failed to checkout branch: {}", branch),
}
}
PrCommands::Open { number } => {
let pr = client.get(&owner, &repo_name, *number)?;
let _ = std::process::Command::new("xdg-open")
.arg(&pr.url)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn();
println!("Opening: {}", pr.url);
}
}
}
Commands::Issue { action } => {
let repo_path = std::env::current_dir()?.to_string_lossy().to_string();
let (platform, owner, repo_name) = detect_platform_from_remote(&repo_path)
.ok_or_else(|| anyhow::anyhow!("Could not detect platform from remote origin"))?;
let client = get_issue_client(&platform)?;
match action {
IssueCommands::List { state } => {
let issues = client.list(&owner, &repo_name, &state)?;
if issues.is_empty() {
println!("No {} issues.", state);
} else {
for i in &issues {
let labels = if i.labels.is_empty() {
String::new()
} else {
format!(" [{}]", i.labels.join(", "))
};
let comments = if i.comments > 0 { format!(" 💬{}", i.comments) } else { String::new() };
println!("#{:<6} {}{}{}", i.number, i.title, labels, comments);
println!(" {} → {} by {} {}", i.state, i.url, i.author, &i.created_at[..10]);
}
}
}
IssueCommands::Create { title, description } => {
let opts = CreateIssueOptions { title: title.clone(), body: description.clone() };
let issue = client.create(&owner, &repo_name, opts)?;
println!("Created issue #{}: {}", issue.number, issue.title);
println!("{}", issue.url);
}
IssueCommands::Close { number } => {
client.close(&owner, &repo_name, *number)?;
println!("✅ Closed issue #{}", number);
}
IssueCommands::Comment { number, message } => {
client.comment(&owner, &repo_name, *number, message)?;
println!("✅ Comment added to issue #{}", number);
}
}
}
Commands::Ignore { action } => {
handle_ignore(action)?;
}
Commands::Tui => {
let current = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
if git2::Repository::discover(¤t).is_ok() {
// Estamos dentro de un repo — abre directamente
crate::tui::run()?;
} else {
// No hay repo — lanza el picker
use crate::tui::picker::{run_picker, save_workspace, PickerResult};
match run_picker(¤t)? {
PickerResult::Cancelled => {}
PickerResult::SingleRepo(path) => {
std::env::set_current_dir(&path)?;
crate::tui::run()?;
}
PickerResult::Workspace { name, repos } => {
save_workspace(&name, &repos)?;
if let Some(first) = repos.first() {
std::env::set_current_dir(first)?;
}
crate::tui::run_with_workspace(name)?;
}
PickerResult::OpenWorkspace(name) => {
let ws_path = dirs::home_dir()
.map(|h| h.join(".torii/workspaces.toml"))
.unwrap_or_default();
if let Ok(content) = std::fs::read_to_string(&ws_path) {
let mut in_ws = false;
let mut first_path: Option<std::path::PathBuf> = None;
for line in content.lines() {
let line = line.trim();
if line == format!("[{}]", name) { in_ws = true; continue; }
if line.starts_with('[') { in_ws = false; }
if in_ws && line.starts_with("path") {
let p = line.split('=').nth(1).unwrap_or("").trim().trim_matches('"');
first_path = Some(std::path::PathBuf::from(p));
break;
}
}
if let Some(p) = first_path {
std::env::set_current_dir(&p)?;
}
}
crate::tui::run_with_workspace(name)?;
}
}
}
}
Commands::Worktree { action } => {
use crate::worktree;
let repo_path = std::path::Path::new(".");
// Default to `list` when no subcommand is given — git/cargo/npm convention.
match action.as_ref() {
None | Some(WorktreeCommands::List) => {
worktree::list(repo_path)?;
}
Some(WorktreeCommands::Add {
path,
new_branch,
existing_branch,
}) => {
let spec = match (new_branch, existing_branch) {
(Some(_), Some(_)) => anyhow::bail!(
"Pass either -b <new-branch> OR a positional <existing-branch>, not both."
),
(Some(name), None) => worktree::BranchSpec::New(name.clone()),
(None, Some(name)) => worktree::BranchSpec::Existing(name.clone()),
(None, None) => anyhow::bail!(
"Specify the branch: either -b <new-branch> or a positional <existing-branch>."
),
};
let opts = worktree::AddOpts {
explicit_path: path.clone(),
};
worktree::add(repo_path, spec, &opts)?;
}
Some(WorktreeCommands::Remove {
path,
force,
no_snapshot,
}) => {
let opts = worktree::RemoveOpts {
force: *force,
no_snapshot: *no_snapshot,
};
worktree::remove(repo_path, path, &opts)?;
}
Some(WorktreeCommands::Prune) => {
worktree::prune(repo_path)?;
}
Some(WorktreeCommands::Open { path }) => {
worktree::open(repo_path, path)?;
}
Some(WorktreeCommands::Lock { path, reason }) => {
worktree::lock(repo_path, path, reason.as_deref())?;
}
Some(WorktreeCommands::Unlock { path }) => {
worktree::unlock(repo_path, path)?;
}
Some(WorktreeCommands::Move { old, new }) => {
worktree::move_wt(repo_path, old, new)?;
}
Some(WorktreeCommands::Repair) => {
worktree::repair(repo_path)?;
}
}
}
Commands::Submodule { action } => {
use crate::submodule;
let repo_path = std::path::Path::new(".");
match action.as_ref() {
None | Some(SubmoduleCommands::Status) => {
submodule::status(repo_path)?;
}
Some(SubmoduleCommands::Add { url, path, branch, name, recursive }) => {
let opts = submodule::AddOpts {
branch: branch.clone(),
name: name.clone(),
recursive: *recursive,
};
submodule::add(repo_path, url, path, &opts)?;
}
Some(SubmoduleCommands::Init { force }) => {
submodule::init(repo_path, *force)?;
}
Some(SubmoduleCommands::Update { init, recursive }) => {
let opts = submodule::UpdateOpts {
init: *init,
recursive: *recursive,
};
submodule::update(repo_path, &opts)?;
}
Some(SubmoduleCommands::Sync) => {
submodule::sync(repo_path)?;
}
Some(SubmoduleCommands::Foreach { cmd }) => {
if cmd.is_empty() {
anyhow::bail!("foreach needs a command, e.g. torii submodule foreach 'cargo build'");
}
let joined = cmd.join(" ");
submodule::foreach(repo_path, &joined)?;
}
Some(SubmoduleCommands::Remove { path }) => {
submodule::remove(repo_path, path)?;
}
}
}
Commands::Subtree { action } => {
use crate::subtree;
let repo_path = std::path::Path::new(".");
match action {
SubtreeCommands::Add { prefix, url, refname, squash } => {
subtree::add(repo_path, prefix, url, refname, &subtree::CommonOpts { squash: *squash })?;
}
SubtreeCommands::Pull { prefix, url, refname, squash } => {
subtree::pull(repo_path, prefix, url, refname, &subtree::CommonOpts { squash: *squash })?;
}
SubtreeCommands::Push { prefix, url, refname } => {
subtree::push(repo_path, prefix, url, refname)?;
}
SubtreeCommands::Split { prefix, branch, annotate } => {
subtree::split(repo_path, prefix, branch.as_deref(), annotate.as_deref())?;
}
SubtreeCommands::Merge { prefix, refname, squash } => {
subtree::merge(repo_path, prefix, refname, &subtree::CommonOpts { squash: *squash })?;
}
}
}
Commands::Bisect { action } => {
let p = std::path::Path::new(".");
match action {
BisectCommands::Start { bad, good } => crate::bisect::start(p, bad.as_deref(), good)?,
BisectCommands::Bad { commit } => crate::bisect::bad(p, commit.as_deref())?,
BisectCommands::Good { commit } => crate::bisect::good(p, commit.as_deref())?,
BisectCommands::Skip { commit } => crate::bisect::skip(p, commit.as_deref())?,
BisectCommands::Reset => crate::bisect::reset(p)?,
BisectCommands::Log => crate::bisect::log(p)?,
BisectCommands::Run { cmd } => crate::bisect::run(p, cmd)?,
}
}
Commands::Describe { tags, long, dirty, candidates } => {
let opts = crate::describe::Opts {
tags: *tags,
long: *long,
dirty: *dirty,
candidates: *candidates,
};
crate::describe::describe(std::path::Path::new("."), &opts)?;
}
Commands::Archive { revision, output, format, prefix } => {
let opts = crate::archive::Opts {
output: output.clone(),
format: format.clone(),
prefix: prefix.clone(),
};
crate::archive::archive(std::path::Path::new("."), revision, &opts)?;
}
Commands::Remove { paths, cached, recursive, force } => {
let opts = crate::fileops::RmOpts {
cached: *cached,
recursive: *recursive,
force: *force,
};
crate::fileops::rm(std::path::Path::new("."), paths, &opts)?;
}
Commands::Rename { from, to, force } => {
let opts = crate::fileops::MvOpts { force: *force };
crate::fileops::mv(std::path::Path::new("."), from, to, &opts)?;
}
Commands::Grep { pattern, paths, ignore_case, word_regexp, files_with_matches, no_line_number } => {
let opts = crate::grep::Opts {
ignore_case: *ignore_case,
word_regexp: *word_regexp,
files_with_matches: *files_with_matches,
no_line_number: *no_line_number,
extra: Vec::new(),
};
crate::grep::grep(std::path::Path::new("."), pattern, paths, &opts)?;
}
Commands::Notes { action } => {
let p = std::path::Path::new(".");
match action.as_ref() {
None | Some(NotesCommands::List) => crate::notes::list(p)?,
Some(NotesCommands::Add { commit, message, force }) => {
crate::notes::add(p, commit, message.as_deref(), *force)?;
}
Some(NotesCommands::Append { commit, message }) => {
crate::notes::append(p, commit, message)?;
}
Some(NotesCommands::Show { commit }) => crate::notes::show(p, commit)?,
Some(NotesCommands::Edit { commit }) => crate::notes::edit(p, commit)?,
Some(NotesCommands::Copy { from, to, force }) => {
crate::notes::copy(p, from, to, *force)?;
}
Some(NotesCommands::Remove { commit }) => crate::notes::remove(p, commit)?,
}
}
Commands::Patch { action } => {
let p = std::path::Path::new(".");
match action {
PatchCommands::Export { range, output_dir, stdout, cover_letter } => {
let opts = crate::patch::ExportOpts {
output_dir: output_dir.clone(),
stdout: *stdout,
cover_letter: *cover_letter,
};
crate::patch::export(p, range, &opts)?;
}
PatchCommands::Apply { files, three_way, continue_, skip, abort } => {
let opts = crate::patch::ApplyOpts {
three_way: *three_way,
continue_: *continue_,
skip: *skip,
abort: *abort,
};
crate::patch::apply(p, files, &opts)?;
}
}
}
Commands::Clean { force, dirs, include_ignored, only_ignored } => {
let opts = crate::clean::Opts {
force: *force,
dirs: *dirs,
include_ignored: *include_ignored,
only_ignored: *only_ignored,
};
crate::clean::clean(std::path::Path::new("."), &opts)?;
}
}
Ok(())
}
}
fn run_ssh_check() {
println!("🔐 SSH Configuration Check\n");
if SshHelper::has_ssh_keys() {
println!("✅ SSH keys found!\n");
let keys = SshHelper::list_keys();
if !keys.is_empty() {
println!("Available keys:");
for key in &keys {
println!(" • {}", key);
}
}
println!("\n💡 Recommendation: Use SSH protocol (default)");
} else {
println!("❌ No SSH keys found");
println!("\n💡 To set up SSH keys:");
println!(" 1. Generate a new key:");
println!(" ssh-keygen -t ed25519 -C \"your_email@example.com\"");
println!(" 2. Start the SSH agent:");
println!(" eval \"$(ssh-agent -s)\"");
println!(" 3. Add your key:");
println!(" ssh-add ~/.ssh/id_ed25519");
println!(" 4. Copy your public key:");
println!(" cat ~/.ssh/id_ed25519.pub");
println!(" 5. Add it to your Git hosting service");
}
}
fn run_auth(action: &AuthCommands) -> Result<()> {
use crate::auth;
use crate::cloud::{whoami::whoami, CloudClient};
match action {
AuthCommands::Login { key, endpoint } => {
let key_value = match key {
Some(k) => k.clone(),
None => {
use std::io::{BufRead, Write};
print!("API key (gitorii_sk_…): ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin().lock().read_line(&mut line)?;
line.trim().to_string()
}
};
if !key_value.starts_with("gitorii_sk_") {
anyhow::bail!("API key must start with `gitorii_sk_`");
}
let endpoint = endpoint
.clone()
.unwrap_or_else(auth::default_endpoint);
// Validate before saving so we don't store a bogus key.
let client = CloudClient::new(auth::ApiKey {
key: key_value.clone(),
endpoint: endpoint.clone(),
});
let me = whoami(&client)?;
auth::save(&key_value, &endpoint)?;
println!("✅ Logged in to {}", endpoint);
println!(" org: {} ({})", me.org_name, me.org_slug);
println!(" plan: {}", me.plan);
}
AuthCommands::Status | AuthCommands::Whoami => {
let key = auth::load().ok_or_else(|| anyhow::anyhow!(
"no API key configured. Run `torii auth login` or set TORII_API_KEY."
))?;
let client = CloudClient::new(key);
let me = whoami(&client)?;
println!("endpoint: {}", client.endpoint());
println!("org: {} ({}) [{}]", me.org_name, me.org_slug, me.org_id);
println!("plan: {}", me.plan);
println!("seats: {}", me.seats);
if me.suspended {
println!("status: ⚠️ suspended");
}
}
AuthCommands::Logout => {
auth::delete()?;
println!("✅ Local API key deleted");
if std::env::var("TORII_API_KEY").is_ok() {
println!("⚠️ TORII_API_KEY env var still set — unset it to fully log out.");
}
}
}
Ok(())
}
fn run_scan(history: bool) -> Result<()> {
let repo_path = std::path::Path::new(".");
if history {
println!("🔍 Scanning full git history for sensitive data...\n");
let results = scanner::scan_history(repo_path)?;
if results.is_empty() {
println!("✅ No sensitive data found in history.");
} else {
println!("⚠️ Found sensitive data in {} commit(s):\n", results.len());
for (commit, findings) in &results {
println!(" 📌 {}", commit);
for f in findings {
println!(" {}:{} — {}", f.file, f.line, f.pattern_name);
println!(" {}", f.preview);
}
println!();
}
println!("💡 To clean history: torii history rebase <base> --todo-file <plan>");
}
} else {
println!("🔍 Scanning staged files for sensitive data...\n");
let findings = scanner::scan_staged(repo_path)?;
if findings.is_empty() {
println!("✅ No sensitive data detected in staged files.");
} else {
println!("⚠️ Found {} issue(s):\n", findings.len());
for f in &findings {
println!(" {}:{} — {}", f.file, f.line, f.pattern_name);
println!(" {}\n", f.preview);
}
println!("💡 Tip: use .env.example for placeholder values.");
}
}
Ok(())
}
fn run_commit_scan(policy_path: Option<&std::path::Path>, limit: usize) -> Result<()> {
use crate::commit_scan::{CompiledCommitPolicy, default_policy_path, scan_repo};
let repo = git2::Repository::discover(".").map_err(|e| anyhow::anyhow!("not a repo: {}", e))?;
let workdir = repo
.workdir()
.ok_or_else(|| anyhow::anyhow!("bare repos can't host policies/commits.toml"))?
.to_path_buf();
let path = match policy_path {
Some(p) => p.to_path_buf(),
None => default_policy_path(&workdir),
};
let policy = match CompiledCommitPolicy::load(&path)? {
Some(p) => p,
None => {
println!("ℹ️ No commit policy found at {}.", path.display());
println!(" Run `torii init` (or create the file manually) to add one.");
return Ok(());
}
};
let violations = scan_repo(&repo, &policy, limit)?;
if violations.is_empty() {
println!("✅ {} commits scanned, no policy violations.", limit);
return Ok(());
}
println!("❌ {} violation(s) across the last {} commits:\n", violations.len(), limit);
for v in &violations {
println!(" {} \"{}\"", v.commit_short, v.subject);
println!(" [{}] {}", v.rule, v.detail);
}
println!();
std::process::exit(1);
}
/// Walk the object database, mark everything reachable from refs + reflogs +
/// the index + HEAD, then list / inspect / restore the leftover unreachable
/// objects. Recovery aid after destructive ops (reset --hard, force-push,
/// rebase that drops commits, etc.).
fn run_fsck(
show: Option<&str>,
restore: Option<&str>,
to: Option<&std::path::Path>,
) -> Result<()> {
use std::collections::HashSet;
let repo = git2::Repository::discover(".")
.map_err(|e| anyhow::anyhow!("not a repo: {}", e))?;
// --- branch: --show <oid>
if let Some(oid_str) = show {
let oid = resolve_oid(&repo, oid_str)?;
let odb = repo.odb().map_err(|e| anyhow::anyhow!("odb: {}", e))?;
let obj = odb.read(oid).map_err(|e| anyhow::anyhow!("read {}: {}", oid, e))?;
match obj.kind() {
git2::ObjectType::Blob => {
use std::io::Write;
std::io::stdout().write_all(obj.data()).ok();
}
git2::ObjectType::Commit => {
let commit = repo
.find_commit(oid)
.map_err(|e| anyhow::anyhow!("find commit {}: {}", oid, e))?;
println!("commit {}", oid);
if let Some(t) = commit.tree_id().to_string().get(..) {
println!("tree {}", t);
}
for p in commit.parent_ids() {
println!("parent {}", p);
}
let a = commit.author();
println!("author {} <{}>", a.name().unwrap_or(""), a.email().unwrap_or(""));
println!();
println!("{}", commit.message().unwrap_or(""));
}
git2::ObjectType::Tree => {
let tree = repo
.find_tree(oid)
.map_err(|e| anyhow::anyhow!("find tree {}: {}", oid, e))?;
println!("tree {} ({} entries)", oid, tree.len());
for e in tree.iter() {
println!(
" {:o} {} {}",
e.filemode(),
e.id(),
e.name().unwrap_or("?")
);
}
}
other => println!("object {} kind={:?} size={}", oid, other, obj.len()),
}
return Ok(());
}
// --- branch: --restore <oid> --to <path>
if let Some(oid_str) = restore {
let dest = to.ok_or_else(|| anyhow::anyhow!("--restore requires --to <path>"))?;
let oid = resolve_oid(&repo, oid_str)?;
let blob = repo
.find_blob(oid)
.map_err(|e| anyhow::anyhow!("not a blob {}: {}", oid, e))?;
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).ok();
}
std::fs::write(dest, blob.content())
.map_err(|e| anyhow::anyhow!("write {}: {}", dest.display(), e))?;
println!(
"✅ Restored {} bytes from {} → {}",
blob.content().len(),
oid,
dest.display()
);
return Ok(());
}
// --- default: list unreachable
let mut reachable: HashSet<git2::Oid> = HashSet::new();
// Refs (branches, tags, remotes)
if let Ok(refs) = repo.references() {
for r in refs.flatten() {
if let Some(target) = r.target() {
mark_commit_tree(&repo, target, &mut reachable);
}
}
}
// HEAD (covers detached HEAD case)
if let Ok(head) = repo.head() {
if let Some(target) = head.target() {
mark_commit_tree(&repo, target, &mut reachable);
}
}
// Reflog of HEAD + every branch — protects work that survived
// ref deletion but still has a reflog entry.
if let Ok(refs) = repo.references() {
for r in refs.flatten() {
let Some(name) = r.name() else { continue };
if let Ok(rl) = repo.reflog(name) {
for entry in rl.iter() {
mark_commit_tree(&repo, entry.id_old(), &mut reachable);
mark_commit_tree(&repo, entry.id_new(), &mut reachable);
}
}
}
}
if let Ok(rl) = repo.reflog("HEAD") {
for entry in rl.iter() {
mark_commit_tree(&repo, entry.id_old(), &mut reachable);
mark_commit_tree(&repo, entry.id_new(), &mut reachable);
}
}
// Index — protects staged blobs not yet committed
if let Ok(index) = repo.index() {
for e in index.iter() {
reachable.insert(e.id);
}
}
// Walk ODB, collect unreachable.
let odb = repo.odb().map_err(|e| anyhow::anyhow!("odb: {}", e))?;
let mut unreachable: Vec<(git2::Oid, git2::ObjectType, usize)> = Vec::new();
odb.foreach(|oid| {
if !reachable.contains(oid) {
if let Ok(obj) = odb.read(*oid) {
unreachable.push((*oid, obj.kind(), obj.len()));
}
}
true
})
.map_err(|e| anyhow::anyhow!("odb walk: {}", e))?;
if unreachable.is_empty() {
println!("✅ No unreachable objects.");
return Ok(());
}
// Sort: commits first, then trees, then blobs by size desc
unreachable.sort_by(|a, b| {
let ka = type_rank(a.1);
let kb = type_rank(b.1);
ka.cmp(&kb).then(b.2.cmp(&a.2))
});
let total: usize = unreachable.iter().map(|(_, _, s)| *s).sum();
println!(
"🔍 {} unreachable object(s), {} bytes total\n",
unreachable.len(),
total
);
println!("{:<8} {:7} {:>10} preview", "type", "oid", "size");
println!("{}", "─".repeat(60));
for (oid, kind, size) in &unreachable {
let short: String = oid.to_string().chars().take(7).collect();
let kind_str = match kind {
git2::ObjectType::Commit => "commit",
git2::ObjectType::Tree => "tree",
git2::ObjectType::Blob => "blob",
git2::ObjectType::Tag => "tag",
_ => "any",
};
let preview = preview_object(&repo, *oid, *kind);
println!(
"{:<8} {:7} {:>10} {}",
kind_str, short, size, preview
);
}
println!();
println!("Inspect: torii history fsck --show <oid>");
println!("Restore: torii history fsck --restore <oid> --to <path>");
Ok(())
}
/// Resolve a (possibly short) hex OID to a full Oid by walking the ODB.
/// Accepts 4..=40 hex chars, errors on ambiguous prefixes.
fn resolve_oid(repo: &git2::Repository, hex: &str) -> Result<git2::Oid> {
if hex.len() == 40 {
return git2::Oid::from_str(hex)
.map_err(|e| anyhow::anyhow!("bad oid {}: {}", hex, e));
}
if hex.len() < 4 {
anyhow::bail!("oid prefix too short (need ≥4 chars): {}", hex);
}
let odb = repo.odb().map_err(|e| anyhow::anyhow!("odb: {}", e))?;
let mut matches: Vec<git2::Oid> = Vec::new();
odb.foreach(|oid| {
if oid.to_string().starts_with(hex) {
matches.push(*oid);
}
true
})
.map_err(|e| anyhow::anyhow!("odb walk: {}", e))?;
match matches.len() {
0 => anyhow::bail!("no object matches prefix {}", hex),
1 => Ok(matches[0]),
n => anyhow::bail!("ambiguous prefix {} ({} matches)", hex, n),
}
}
fn type_rank(t: git2::ObjectType) -> u8 {
match t {
git2::ObjectType::Commit => 0,
git2::ObjectType::Tag => 1,
git2::ObjectType::Tree => 2,
git2::ObjectType::Blob => 3,
_ => 4,
}
}
fn mark_commit_tree(
repo: &git2::Repository,
oid: git2::Oid,
set: &mut std::collections::HashSet<git2::Oid>,
) {
if !set.insert(oid) {
return;
}
let Ok(obj) = repo.find_object(oid, None) else { return };
match obj.kind() {
Some(git2::ObjectType::Commit) => {
if let Ok(commit) = obj.peel_to_commit() {
set.insert(commit.tree_id());
if let Ok(tree) = commit.tree() {
mark_tree(repo, &tree, set);
}
for p in commit.parent_ids() {
mark_commit_tree(repo, p, set);
}
}
}
Some(git2::ObjectType::Tag) => {
if let Ok(tag) = obj.peel_to_tag() {
mark_commit_tree(repo, tag.target_id(), set);
}
}
Some(git2::ObjectType::Tree) => {
if let Ok(tree) = obj.peel_to_tree() {
mark_tree(repo, &tree, set);
}
}
_ => {}
}
}
fn mark_tree(
repo: &git2::Repository,
tree: &git2::Tree,
set: &mut std::collections::HashSet<git2::Oid>,
) {
for entry in tree.iter() {
let id = entry.id();
if !set.insert(id) {
continue;
}
if entry.kind() == Some(git2::ObjectType::Tree) {
if let Ok(sub) = repo.find_tree(id) {
mark_tree(repo, &sub, set);
}
}
}
}
fn preview_object(repo: &git2::Repository, oid: git2::Oid, kind: git2::ObjectType) -> String {
match kind {
git2::ObjectType::Commit => repo
.find_commit(oid)
.ok()
.and_then(|c| c.summary().map(|s| s.to_string()))
.unwrap_or_default(),
git2::ObjectType::Blob => repo
.find_blob(oid)
.ok()
.and_then(|b| std::str::from_utf8(b.content()).ok().map(|s| s.to_string()))
.map(|s| s.lines().next().unwrap_or("").chars().take(50).collect())
.unwrap_or_else(|| "<binary>".to_string()),
git2::ObjectType::Tree => repo
.find_tree(oid)
.ok()
.map(|t| format!("({} entries)", t.len()))
.unwrap_or_default(),
_ => String::new(),
}
}
fn handle_ignore(action: &IgnoreCommands) -> Result<()> {
use std::fs::OpenOptions;
use std::io::Write;
let repo_root = std::path::Path::new(".");
let public = repo_root.join(".toriignore");
let local = repo_root.join(".toriignore.local");
fn append_section(path: &std::path::Path, section: &str, line: &str) -> Result<()> {
let existing = std::fs::read_to_string(path).unwrap_or_default();
let header = format!("[{}]", section);
// Active header = line equal to `[section]` after trimming, NOT commented.
let has_active_header = existing.lines().any(|l| l.trim() == header);
let mut out = OpenOptions::new().create(true).append(true).open(path)?;
if !has_active_header {
if !existing.is_empty() && !existing.ends_with('\n') {
writeln!(out)?;
}
writeln!(out)?;
writeln!(out, "{}", header)?;
}
writeln!(out, "{}", line)?;
Ok(())
}
match action {
IgnoreCommands::Add { pattern, local: use_local } => {
let target = if *use_local { &local } else { &public };
let existing = std::fs::read_to_string(target).unwrap_or_default();
let mut f = OpenOptions::new().create(true).append(true).open(target)?;
if !existing.is_empty() && !existing.ends_with('\n') {
writeln!(f)?;
}
writeln!(f, "{}", pattern)?;
let label = if *use_local { ".toriignore.local (private)" } else { ".toriignore" };
println!("✅ Added `{}` to {}", pattern, label);
}
IgnoreCommands::Secret { pattern, name, public: use_public } => {
// Validate regex before writing
regex::Regex::new(pattern)
.map_err(|e| anyhow::anyhow!("invalid regex: {}", e))?;
let line = match name {
Some(n) => format!("deny: {} # {}", pattern, n),
None => format!("deny: {}", pattern),
};
let target = if *use_public { &public } else { &local };
append_section(target, "secrets", &line)?;
let label = if *use_public {
".toriignore (public — visible in repo)"
} else {
".toriignore.local (private — never committed)"
};
println!("✅ Added secret rule to {}", label);
if *use_public {
println!("⚠️ Consider --local instead: secret-pattern shape can aid recon if repo leaks");
}
}
IgnoreCommands::List => {
let ti = crate::toriignore::ToriIgnore::load(repo_root)?;
println!("📋 Effective .toriignore rules (public + local merged)\n");
println!("Paths ({}):", ti.patterns().len());
for p in ti.patterns() { println!(" {}", p); }
println!("\nSecrets ({}):", ti.secrets.len());
for s in &ti.secrets { println!(" {} → {}", s.name, s.regex.as_str()); }
if ti.size.max_bytes.is_some() || ti.size.warn_bytes.is_some() {
println!("\nSize:");
if let Some(m) = ti.size.max_bytes { println!(" max: {} bytes", m); }
if let Some(w) = ti.size.warn_bytes { println!(" warn: {} bytes", w); }
}
if !ti.hooks.pre_save.is_empty() || !ti.hooks.pre_sync.is_empty() {
println!("\nHooks:");
for h in &ti.hooks.pre_save { println!(" pre-save: {}", h); }
for h in &ti.hooks.pre_sync { println!(" pre-sync: {}", h); }
for h in &ti.hooks.post_save { println!(" post-save: {}", h); }
for h in &ti.hooks.post_sync { println!(" post-sync: {}", h); }
}
if local.exists() {
println!("\n🔒 .toriignore.local present (private, gitignored)");
}
}
}
Ok(())
}