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
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as os from 'os';
import * as path from 'path';
import { Command, commands, Disposable, LineChange, MessageOptions, OutputChannel, Position, ProgressLocation, QuickPickItem, Range, SourceControlResourceState, TextDocumentShowOptions, TextEditor, Uri, ViewColumn, window, workspace, WorkspaceEdit, WorkspaceFolder, TimelineItem, env, Selection, TextDocumentContentProvider } from 'vscode';
import TelemetryReporter from '@vscode/extension-telemetry';
import * as nls from 'vscode-nls';
import { Branch, ForcePushMode, GitErrorCodes, Ref, RefType, Status, CommitOptions, RemoteSourcePublisher } from './api/git';
import { Git, Stash } from './git';
import { Model } from './model';
import { Repository, Resource, ResourceGroupType } from './repository';
import { applyLineChanges, getModifiedRange, intersectDiffWithRange, invertLineChange, toLineRanges } from './staging';
import { fromGitUri, toGitUri, isGitUri } from './uri';
import { grep, isDescendant, logTimestamp, pathEquals, relativePath } from './util';
import { Log, LogLevel } from './log';
import { GitTimelineItem } from './timelineProvider';
import { ApiRepository } from './api/api1';
import { pickRemoteSource } from './remoteSource';
const localize = nls.loadMessageBundle();
class CheckoutItem implements QuickPickItem {
protected get shortCommit(): string { return (this.ref.commit || '').substr(0, 8); }
get label(): string { return this.ref.name || this.shortCommit; }
get description(): string { return this.shortCommit; }
constructor(protected ref: Ref) { }
async run(repository: Repository, opts?: { detached?: boolean }): Promise<void> {
const ref = this.ref.name;
if (!ref) {
return;
}
await repository.checkout(ref, opts);
}
}
class CheckoutTagItem extends CheckoutItem {
override get description(): string {
return localize('tag at', "Tag at {0}", this.shortCommit);
}
}
class CheckoutRemoteHeadItem extends CheckoutItem {
override get description(): string {
return localize('remote branch at', "Remote branch at {0}", this.shortCommit);
}
override async run(repository: Repository, opts?: { detached?: boolean }): Promise<void> {
if (!this.ref.name) {
return;
}
const branches = await repository.findTrackingBranches(this.ref.name);
if (branches.length > 0) {
await repository.checkout(branches[0].name!, opts);
} else {
await repository.checkoutTracking(this.ref.name, opts);
}
}
}
class BranchDeleteItem implements QuickPickItem {
private get shortCommit(): string { return (this.ref.commit || '').substr(0, 8); }
get branchName(): string | undefined { return this.ref.name; }
get label(): string { return this.branchName || ''; }
get description(): string { return this.shortCommit; }
constructor(private ref: Ref) { }
async run(repository: Repository, force?: boolean): Promise<void> {
if (!this.branchName) {
return;
}
await repository.deleteBranch(this.branchName, force);
}
}
class MergeItem implements QuickPickItem {
get label(): string { return this.ref.name || ''; }
get description(): string { return this.ref.name || ''; }
constructor(protected ref: Ref) { }
async run(repository: Repository): Promise<void> {
await repository.merge(this.ref.name! || this.ref.commit!);
}
}
class RebaseItem implements QuickPickItem {
get label(): string { return this.ref.name || ''; }
description: string = '';
constructor(readonly ref: Ref) { }
async run(repository: Repository): Promise<void> {
if (this.ref?.name) {
await repository.rebase(this.ref.name);
}
}
}
class CreateBranchItem implements QuickPickItem {
get label(): string { return '$(plus) ' + localize('create branch', 'Create new branch...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
}
class CreateBranchFromItem implements QuickPickItem {
get label(): string { return '$(plus) ' + localize('create branch from', 'Create new branch from...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
}
class CheckoutDetachedItem implements QuickPickItem {
get label(): string { return '$(debug-disconnect) ' + localize('checkout detached', 'Checkout detached...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
}
class HEADItem implements QuickPickItem {
constructor(private repository: Repository) { }
get label(): string { return 'HEAD'; }
get description(): string { return (this.repository.HEAD && this.repository.HEAD.commit || '').substr(0, 8); }
get alwaysShow(): boolean { return true; }
}
class AddRemoteItem implements QuickPickItem {
constructor(private cc: CommandCenter) { }
get label(): string { return '$(plus) ' + localize('add remote', 'Add a new remote...'); }
get description(): string { return ''; }
get alwaysShow(): boolean { return true; }
async run(repository: Repository): Promise<void> {
await this.cc.addRemote(repository);
}
}
interface ScmCommandOptions {
repository?: boolean;
diff?: boolean;
}
interface ScmCommand {
commandId: string;
key: string;
method: Function;
options: ScmCommandOptions;
}
const Commands: ScmCommand[] = [];
function command(commandId: string, options: ScmCommandOptions = {}): Function {
return (_target: any, key: string, descriptor: any) => {
if (!(typeof descriptor.value === 'function')) {
throw new Error('not supported');
}
Commands.push({ commandId, key, method: descriptor.value, options });
};
}
// const ImageMimetypes = [
// 'image/png',
// 'image/gif',
// 'image/jpeg',
// 'image/webp',
// 'image/tiff',
// 'image/bmp'
// ];
async function categorizeResourceByResolution(resources: Resource[]): Promise<{ merge: Resource[]; resolved: Resource[]; unresolved: Resource[]; deletionConflicts: Resource[] }> {
const selection = resources.filter(s => s instanceof Resource) as Resource[];
const merge = selection.filter(s => s.resourceGroupType === ResourceGroupType.Merge);
const isBothAddedOrModified = (s: Resource) => s.type === Status.BOTH_MODIFIED || s.type === Status.BOTH_ADDED;
const isAnyDeleted = (s: Resource) => s.type === Status.DELETED_BY_THEM || s.type === Status.DELETED_BY_US;
const possibleUnresolved = merge.filter(isBothAddedOrModified);
const promises = possibleUnresolved.map(s => grep(s.resourceUri.fsPath, /^<{7}|^={7}|^>{7}/));
const unresolvedBothModified = await Promise.all<boolean>(promises);
const resolved = possibleUnresolved.filter((_s, i) => !unresolvedBothModified[i]);
const deletionConflicts = merge.filter(s => isAnyDeleted(s));
const unresolved = [
...merge.filter(s => !isBothAddedOrModified(s) && !isAnyDeleted(s)),
...possibleUnresolved.filter((_s, i) => unresolvedBothModified[i])
];
return { merge, resolved, unresolved, deletionConflicts };
}
function createCheckoutItems(repository: Repository): CheckoutItem[] {
const config = workspace.getConfiguration('git');
const checkoutTypeConfig = config.get<string | string[]>('checkoutType');
let checkoutTypes: string[];
if (checkoutTypeConfig === 'all' || !checkoutTypeConfig || checkoutTypeConfig.length === 0) {
checkoutTypes = ['local', 'remote', 'tags'];
} else if (typeof checkoutTypeConfig === 'string') {
checkoutTypes = [checkoutTypeConfig];
} else {
checkoutTypes = checkoutTypeConfig;
}
const processors = checkoutTypes.map(getCheckoutProcessor)
.filter(p => !!p) as CheckoutProcessor[];
for (const ref of repository.refs) {
for (const processor of processors) {
processor.onRef(ref);
}
}
return processors.reduce<CheckoutItem[]>((r, p) => r.concat(...p.items), []);
}
class CheckoutProcessor {
private refs: Ref[] = [];
get items(): CheckoutItem[] { return this.refs.map(r => new this.ctor(r)); }
constructor(private type: RefType, private ctor: { new(ref: Ref): CheckoutItem }) { }
onRef(ref: Ref): void {
if (ref.type === this.type) {
this.refs.push(ref);
}
}
}
function getCheckoutProcessor(type: string): CheckoutProcessor | undefined {
switch (type) {
case 'local':
return new CheckoutProcessor(RefType.Head, CheckoutItem);
case 'remote':
return new CheckoutProcessor(RefType.RemoteHead, CheckoutRemoteHeadItem);
case 'tags':
return new CheckoutProcessor(RefType.Tag, CheckoutTagItem);
}
return undefined;
}
function sanitizeRemoteName(name: string) {
name = name.trim();
return name && name.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$|\[|\]$/g, '-');
}
class TagItem implements QuickPickItem {
get label(): string { return this.ref.name ?? ''; }
get description(): string { return this.ref.commit?.substr(0, 8) ?? ''; }
constructor(readonly ref: Ref) { }
}
enum PushType {
Push,
PushTo,
PushFollowTags,
PushTags
}
interface PushOptions {
pushType: PushType;
forcePush?: boolean;
silent?: boolean;
pushTo?: {
remote?: string;
refspec?: string;
setUpstream?: boolean;
};
}
class CommandErrorOutputTextDocumentContentProvider implements TextDocumentContentProvider {
private items = new Map<string, string>();
set(uri: Uri, contents: string): void {
this.items.set(uri.path, contents);
}
delete(uri: Uri): void {
this.items.delete(uri.path);
}
provideTextDocumentContent(uri: Uri): string | undefined {
return this.items.get(uri.path);
}
}
export class CommandCenter {
private disposables: Disposable[];
private commandErrors = new CommandErrorOutputTextDocumentContentProvider();
constructor(
private git: Git,
private model: Model,
private outputChannel: OutputChannel,
private telemetryReporter: TelemetryReporter
) {
this.disposables = Commands.map(({ commandId, key, method, options }) => {
const command = this.createCommand(commandId, key, method, options);
if (options.diff) {
return commands.registerDiffInformationCommand(commandId, command);
} else {
return commands.registerCommand(commandId, command);
}
});
this.disposables.push(workspace.registerTextDocumentContentProvider('git-output', this.commandErrors));
}
@command('git.setLogLevel')
async setLogLevel(): Promise<void> {
const createItem = (logLevel: LogLevel) => ({
label: LogLevel[logLevel],
logLevel,
description: Log.logLevel === logLevel ? localize('current', "Current") : undefined
});
const items = [
createItem(LogLevel.Trace),
createItem(LogLevel.Debug),
createItem(LogLevel.Info),
createItem(LogLevel.Warning),
createItem(LogLevel.Error),
createItem(LogLevel.Critical),
createItem(LogLevel.Off)
];
const choice = await window.showQuickPick(items, {
placeHolder: localize('select log level', "Select log level")
});
if (!choice) {
return;
}
Log.logLevel = choice.logLevel;
this.outputChannel.appendLine(localize('changed', "{0} Log level changed to: {1}", logTimestamp(), LogLevel[Log.logLevel]));
}
@command('git.refresh', { repository: true })
async refresh(repository: Repository): Promise<void> {
await repository.status();
}
@command('git.openResource')
async openResource(resource: Resource): Promise<void> {
const repository = this.model.getRepository(resource.resourceUri);
if (!repository) {
return;
}
await resource.open();
}
@command('git.openAllChanges', { repository: true })
async openChanges(repository: Repository): Promise<void> {
for (const resource of [...repository.workingTreeGroup.resourceStates, ...repository.untrackedGroup.resourceStates]) {
if (
resource.type === Status.DELETED || resource.type === Status.DELETED_BY_THEM ||
resource.type === Status.DELETED_BY_US || resource.type === Status.BOTH_DELETED
) {
continue;
}
void commands.executeCommand(
'vscode.open',
resource.resourceUri,
{ background: true, preview: false, }
);
}
}
async cloneRepository(url?: string, parentPath?: string, options: { recursive?: boolean } = {}): Promise<void> {
if (!url || typeof url !== 'string') {
url = await pickRemoteSource({
providerLabel: provider => localize('clonefrom', "Clone from {0}", provider.name),
urlLabel: localize('repourl', "Clone from URL")
});
}
if (!url) {
/* __GDPR__
"clone" : {
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_URL' });
return;
}
url = url.trim().replace(/^git\s+clone\s+/, '');
if (!parentPath) {
const config = workspace.getConfiguration('git');
let defaultCloneDirectory = config.get<string>('defaultCloneDirectory') || os.homedir();
defaultCloneDirectory = defaultCloneDirectory.replace(/^~/, os.homedir());
const uris = await window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
defaultUri: Uri.file(defaultCloneDirectory),
openLabel: localize('selectFolder', "Select Repository Location")
});
if (!uris || uris.length === 0) {
/* __GDPR__
"clone" : {
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
return;
}
const uri = uris[0];
parentPath = uri.fsPath;
}
try {
const opts = {
location: ProgressLocation.Notification,
title: localize('cloning', "Cloning git repository '{0}'...", url),
cancellable: true
};
const repositoryPath = await window.withProgress(
opts,
(progress, token) => this.git.clone(url!, { parentPath: parentPath!, progress, recursive: options.recursive }, token)
);
const config = workspace.getConfiguration('git');
const openAfterClone = config.get<'always' | 'alwaysNewWindow' | 'whenNoFolderOpen' | 'prompt'>('openAfterClone');
enum PostCloneAction { Open, OpenNewWindow, AddToWorkspace }
let action: PostCloneAction | undefined = undefined;
if (openAfterClone === 'always') {
action = PostCloneAction.Open;
} else if (openAfterClone === 'alwaysNewWindow') {
action = PostCloneAction.OpenNewWindow;
} else if (openAfterClone === 'whenNoFolderOpen' && !workspace.workspaceFolders) {
action = PostCloneAction.Open;
}
if (action === undefined) {
let message = localize('proposeopen', "Would you like to open the cloned repository?");
const open = localize('openrepo', "Open");
const openNewWindow = localize('openreponew', "Open in New Window");
const choices = [open, openNewWindow];
const addToWorkspace = localize('add', "Add to Workspace");
if (workspace.workspaceFolders) {
message = localize('proposeopen2', "Would you like to open the cloned repository, or add it to the current workspace?");
choices.push(addToWorkspace);
}
const result = await window.showInformationMessage(message, ...choices);
action = result === open ? PostCloneAction.Open
: result === openNewWindow ? PostCloneAction.OpenNewWindow
: result === addToWorkspace ? PostCloneAction.AddToWorkspace : undefined;
}
/* __GDPR__
"clone" : {
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"openFolder": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'success' }, { openFolder: action === PostCloneAction.Open || action === PostCloneAction.OpenNewWindow ? 1 : 0 });
const uri = Uri.file(repositoryPath);
if (action === PostCloneAction.Open) {
commands.executeCommand('vscode.openFolder', uri, { forceReuseWindow: true });
} else if (action === PostCloneAction.AddToWorkspace) {
workspace.updateWorkspaceFolders(workspace.workspaceFolders!.length, 0, { uri });
} else if (action === PostCloneAction.OpenNewWindow) {
commands.executeCommand('vscode.openFolder', uri, { forceNewWindow: true });
}
} catch (err) {
if (/already exists and is not an empty directory/.test(err && err.stderr || '')) {
/* __GDPR__
"clone" : {
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'directory_not_empty' });
} else if (/Cancelled/i.test(err && (err.message || err.stderr || ''))) {
return;
} else {
/* __GDPR__
"clone" : {
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'error' });
}
throw err;
}
}
@command('git.clone')
async clone(url?: string, parentPath?: string): Promise<void> {
await this.cloneRepository(url, parentPath);
}
@command('git.cloneRecursive')
async cloneRecursive(url?: string, parentPath?: string): Promise<void> {
await this.cloneRepository(url, parentPath, { recursive: true });
}
@command('git.init')
async init(skipFolderPrompt = false): Promise<void> {
let repositoryPath: string | undefined = undefined;
let askToOpen = true;
if (workspace.workspaceFolders) {
if (skipFolderPrompt && workspace.workspaceFolders.length === 1) {
repositoryPath = workspace.workspaceFolders[0].uri.fsPath;
askToOpen = false;
} else {
const placeHolder = localize('init', "Pick workspace folder to initialize git repo in");
const pick = { label: localize('choose', "Choose Folder...") };
const items: { label: string; folder?: WorkspaceFolder }[] = [
...workspace.workspaceFolders.map(folder => ({ label: folder.name, description: folder.uri.fsPath, folder })),
pick
];
const item = await window.showQuickPick(items, { placeHolder, ignoreFocusOut: true });
if (!item) {
return;
} else if (item.folder) {
repositoryPath = item.folder.uri.fsPath;
askToOpen = false;
}
}
}
if (!repositoryPath) {
const homeUri = Uri.file(os.homedir());
const defaultUri = workspace.workspaceFolders && workspace.workspaceFolders.length > 0
? Uri.file(workspace.workspaceFolders[0].uri.fsPath)
: homeUri;
const result = await window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
defaultUri,
openLabel: localize('init repo', "Initialize Repository")
});
if (!result || result.length === 0) {
return;
}
const uri = result[0];
if (homeUri.toString().startsWith(uri.toString())) {
const yes = localize('create repo', "Initialize Repository");
const answer = await window.showWarningMessage(localize('are you sure', "This will create a Git repository in '{0}'. Are you sure you want to continue?", uri.fsPath), yes);
if (answer !== yes) {
return;
}
}
repositoryPath = uri.fsPath;
if (workspace.workspaceFolders && workspace.workspaceFolders.some(w => w.uri.toString() === uri.toString())) {
askToOpen = false;
}
}
await this.git.init(repositoryPath);
let message = localize('proposeopen init', "Would you like to open the initialized repository?");
const open = localize('openrepo', "Open");
const openNewWindow = localize('openreponew', "Open in New Window");
const choices = [open, openNewWindow];
if (!askToOpen) {
return;
}
const addToWorkspace = localize('add', "Add to Workspace");
if (workspace.workspaceFolders) {
message = localize('proposeopen2 init', "Would you like to open the initialized repository, or add it to the current workspace?");
choices.push(addToWorkspace);
}
const result = await window.showInformationMessage(message, ...choices);
const uri = Uri.file(repositoryPath);
if (result === open) {
commands.executeCommand('vscode.openFolder', uri);
} else if (result === addToWorkspace) {
workspace.updateWorkspaceFolders(workspace.workspaceFolders!.length, 0, { uri });
} else if (result === openNewWindow) {
commands.executeCommand('vscode.openFolder', uri, true);
} else {
await this.model.openRepository(repositoryPath);
}
}
@command('git.openRepository', { repository: false })
async openRepository(path?: string): Promise<void> {
if (!path) {
const result = await window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
defaultUri: Uri.file(os.homedir()),
openLabel: localize('open repo', "Open Repository")
});
if (!result || result.length === 0) {
return;
}
path = result[0].fsPath;
}
await this.model.openRepository(path);
}
@command('git.close', { repository: true })
async close(repository: Repository): Promise<void> {
this.model.close(repository);
}
@command('git.openFile')
async openFile(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
const preserveFocus = arg instanceof Resource;
let uris: Uri[] | undefined;
if (arg instanceof Uri) {
if (isGitUri(arg)) {
uris = [Uri.file(fromGitUri(arg).path)];
} else if (arg.scheme === 'file') {
uris = [arg];
}
} else {
let resource = arg;
if (!(resource instanceof Resource)) {
// can happen when called from a keybinding
resource = this.getSCMResource();
}
if (resource) {
uris = ([resource, ...resourceStates] as Resource[])
.filter(r => r.type !== Status.DELETED && r.type !== Status.INDEX_DELETED)
.map(r => r.resourceUri);
} else if (window.activeTextEditor) {
uris = [window.activeTextEditor.document.uri];
}
}
if (!uris) {
return;
}
const activeTextEditor = window.activeTextEditor;
// Must extract these now because opening a new document will change the activeTextEditor reference
const previousVisibleRange = activeTextEditor?.visibleRanges[0];
const previousURI = activeTextEditor?.document.uri;
const previousSelection = activeTextEditor?.selection;
for (const uri of uris) {
const opts: TextDocumentShowOptions = {
preserveFocus,
preview: false,
viewColumn: ViewColumn.Active
};
await commands.executeCommand('vscode.open', uri, {
...opts,
override: arg instanceof Resource && arg.type === Status.BOTH_MODIFIED ? false : undefined
});
const document = window.activeTextEditor?.document;
// If the document doesn't match what we opened then don't attempt to select the range
// Additioanlly if there was no previous document we don't have information to select a range
if (document?.uri.toString() !== uri.toString() || !activeTextEditor || !previousURI || !previousSelection) {
continue;
}
// Check if active text editor has same path as other editor. we cannot compare via
// URI.toString() here because the schemas can be different. Instead we just go by path.
if (previousURI.path === uri.path && document) {
// preserve not only selection but also visible range
opts.selection = previousSelection;
const editor = await window.showTextDocument(document, opts);
// This should always be defined but just in case
if (previousVisibleRange) {
editor.revealRange(previousVisibleRange);
}
}
}
}
@command('git.openFile2')
async openFile2(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
this.openFile(arg, ...resourceStates);
}
@command('git.openHEADFile')
async openHEADFile(arg?: Resource | Uri): Promise<void> {
let resource: Resource | undefined = undefined;
const preview = !(arg instanceof Resource);
if (arg instanceof Resource) {
resource = arg;
} else if (arg instanceof Uri) {
resource = this.getSCMResource(arg);
} else {
resource = this.getSCMResource();
}
if (!resource) {
return;
}
const HEAD = resource.leftUri;
const basename = path.basename(resource.resourceUri.fsPath);
const title = `${basename} (HEAD)`;
if (!HEAD) {
window.showWarningMessage(localize('HEAD not available', "HEAD version of '{0}' is not available.", path.basename(resource.resourceUri.fsPath)));
return;
}
const opts: TextDocumentShowOptions = {
preview
};
return await commands.executeCommand<void>('vscode.open', HEAD, opts, title);
}
@command('git.openChange')
async openChange(arg?: Resource | Uri, ...resourceStates: SourceControlResourceState[]): Promise<void> {
let resources: Resource[] | undefined = undefined;
if (arg instanceof Uri) {
const resource = this.getSCMResource(arg);
if (resource !== undefined) {
resources = [resource];
}
} else {
let resource: Resource | undefined = undefined;
if (arg instanceof Resource) {
resource = arg;
} else {
resource = this.getSCMResource();
}
if (resource) {
resources = [...resourceStates as Resource[], resource];
}
}
if (!resources) {
return;
}
for (const resource of resources) {
await resource.openChange();
}
}
@command('git.rename', { repository: true })
async rename(repository: Repository, fromUri: Uri | undefined): Promise<void> {
fromUri = fromUri ?? window.activeTextEditor?.document.uri;
if (!fromUri) {
return;
}
const from = relativePath(repository.root, fromUri.fsPath);
let to = await window.showInputBox({
value: from,
valueSelection: [from.length - path.basename(from).length, from.length]
});
to = to?.trim();
if (!to) {
return;
}
await repository.move(from, to);
}
@command('git.stage')
async stage(...resourceStates: SourceControlResourceState[]): Promise<void> {
this.outputChannel.appendLine(`${logTimestamp()} git.stage ${resourceStates.length}`);
resourceStates = resourceStates.filter(s => !!s);
if (resourceStates.length === 0 || (resourceStates[0] && !(resourceStates[0].resourceUri instanceof Uri))) {
const resource = this.getSCMResource();
this.outputChannel.appendLine(`${logTimestamp()} git.stage.getSCMResource ${resource ? resource.resourceUri.toString() : null}`);
if (!resource) {
return;
}
resourceStates = [resource];
}
const selection = resourceStates.filter(s => s instanceof Resource) as Resource[];
const { resolved, unresolved, deletionConflicts } = await categorizeResourceByResolution(selection);
if (unresolved.length > 0) {
const message = unresolved.length > 1
? localize('confirm stage files with merge conflicts', "Are you sure you want to stage {0} files with merge conflicts?", unresolved.length)
: localize('confirm stage file with merge conflicts', "Are you sure you want to stage {0} with merge conflicts?", path.basename(unresolved[0].resourceUri.fsPath));
const yes = localize('yes', "Yes");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick !== yes) {
return;
}
}
try {
await this.runByRepository(deletionConflicts.map(r => r.resourceUri), async (repository, resources) => {
for (const resource of resources) {
await this._stageDeletionConflict(repository, resource);
}
});
} catch (err) {
if (/Cancelled/.test(err.message)) {
return;
}
throw err;
}
const workingTree = selection.filter(s => s.resourceGroupType === ResourceGroupType.WorkingTree);
const untracked = selection.filter(s => s.resourceGroupType === ResourceGroupType.Untracked);
const scmResources = [...workingTree, ...untracked, ...resolved, ...unresolved];
this.outputChannel.appendLine(`${logTimestamp()} git.stage.scmResources ${scmResources.length}`);
if (!scmResources.length) {
return;
}
const resources = scmResources.map(r => r.resourceUri);
await this.runByRepository(resources, async (repository, resources) => repository.add(resources));
}
@command('git.stageAll', { repository: true })
async stageAll(repository: Repository): Promise<void> {
const resources = [...repository.workingTreeGroup.resourceStates, ...repository.untrackedGroup.resourceStates];
const uris = resources.map(r => r.resourceUri);
if (uris.length > 0) {
const config = workspace.getConfiguration('git', Uri.file(repository.root));
const untrackedChanges = config.get<'mixed' | 'separate' | 'hidden'>('untrackedChanges');
await repository.add(uris, untrackedChanges === 'mixed' ? undefined : { update: true });
}
}
private async _stageDeletionConflict(repository: Repository, uri: Uri): Promise<void> {
const uriString = uri.toString();
const resource = repository.mergeGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString)[0];
if (!resource) {
return;
}
if (resource.type === Status.DELETED_BY_THEM) {
const keepIt = localize('keep ours', "Keep Our Version");
const deleteIt = localize('delete', "Delete File");
const result = await window.showInformationMessage(localize('deleted by them', "File '{0}' was deleted by them and modified by us.\n\nWhat would you like to do?", path.basename(uri.fsPath)), { modal: true }, keepIt, deleteIt);
if (result === keepIt) {
await repository.add([uri]);
} else if (result === deleteIt) {
await repository.rm([uri]);
} else {
throw new Error('Cancelled');
}
} else if (resource.type === Status.DELETED_BY_US) {
const keepIt = localize('keep theirs', "Keep Their Version");
const deleteIt = localize('delete', "Delete File");
const result = await window.showInformationMessage(localize('deleted by us', "File '{0}' was deleted by us and modified by them.\n\nWhat would you like to do?", path.basename(uri.fsPath)), { modal: true }, keepIt, deleteIt);
if (result === keepIt) {
await repository.add([uri]);
} else if (result === deleteIt) {
await repository.rm([uri]);
} else {
throw new Error('Cancelled');
}
}
}
@command('git.stageAllTracked', { repository: true })
async stageAllTracked(repository: Repository): Promise<void> {
const resources = repository.workingTreeGroup.resourceStates
.filter(r => r.type !== Status.UNTRACKED && r.type !== Status.IGNORED);
const uris = resources.map(r => r.resourceUri);
await repository.add(uris);
}
@command('git.stageAllUntracked', { repository: true })
async stageAllUntracked(repository: Repository): Promise<void> {
const resources = [...repository.workingTreeGroup.resourceStates, ...repository.untrackedGroup.resourceStates]
.filter(r => r.type === Status.UNTRACKED || r.type === Status.IGNORED);
const uris = resources.map(r => r.resourceUri);
await repository.add(uris);
}
@command('git.stageAllMerge', { repository: true })
async stageAllMerge(repository: Repository): Promise<void> {
const resources = repository.mergeGroup.resourceStates.filter(s => s instanceof Resource) as Resource[];
const { merge, unresolved, deletionConflicts } = await categorizeResourceByResolution(resources);
try {
for (const deletionConflict of deletionConflicts) {
await this._stageDeletionConflict(repository, deletionConflict.resourceUri);
}
} catch (err) {
if (/Cancelled/.test(err.message)) {
return;
}
throw err;
}
if (unresolved.length > 0) {
const message = unresolved.length > 1
? localize('confirm stage files with merge conflicts', "Are you sure you want to stage {0} files with merge conflicts?", merge.length)
: localize('confirm stage file with merge conflicts', "Are you sure you want to stage {0} with merge conflicts?", path.basename(merge[0].resourceUri.fsPath));
const yes = localize('yes', "Yes");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick !== yes) {
return;
}
}
const uris = resources.map(r => r.resourceUri);
if (uris.length > 0) {
await repository.add(uris);
}
}
@command('git.stageChange')
async stageChange(uri: Uri, changes: LineChange[], index: number): Promise<void> {
if (!uri) {
return;
}
const textEditor = window.visibleTextEditors.filter(e => e.document.uri.toString() === uri.toString())[0];
if (!textEditor) {
return;
}
await this._stageChanges(textEditor, [changes[index]]);
const firstStagedLine = changes[index].modifiedStartLineNumber - 1;
textEditor.selections = [new Selection(firstStagedLine, 0, firstStagedLine, 0)];
}
@command('git.stageSelectedRanges', { diff: true })
async stageSelectedChanges(changes: LineChange[]): Promise<void> {
const textEditor = window.activeTextEditor;
if (!textEditor) {
return;
}
const modifiedDocument = textEditor.document;
const selectedLines = toLineRanges(textEditor.selections, modifiedDocument);
const selectedChanges = changes
.map(diff => selectedLines.reduce<LineChange | null>((result, range) => result || intersectDiffWithRange(modifiedDocument, diff, range), null))
.filter(d => !!d) as LineChange[];
if (!selectedChanges.length) {
return;
}
await this._stageChanges(textEditor, selectedChanges);
}
private async _stageChanges(textEditor: TextEditor, changes: LineChange[]): Promise<void> {
const modifiedDocument = textEditor.document;
const modifiedUri = modifiedDocument.uri;
if (modifiedUri.scheme !== 'file') {
return;
}
const originalUri = toGitUri(modifiedUri, '~');
const originalDocument = await workspace.openTextDocument(originalUri);
const result = applyLineChanges(originalDocument, modifiedDocument, changes);
await this.runByRepository(modifiedUri, async (repository, resource) => await repository.stage(resource, result));
}
@command('git.revertChange')
async revertChange(uri: Uri, changes: LineChange[], index: number): Promise<void> {
if (!uri) {
return;
}
const textEditor = window.visibleTextEditors.filter(e => e.document.uri.toString() === uri.toString())[0];
if (!textEditor) {
return;
}
await this._revertChanges(textEditor, [...changes.slice(0, index), ...changes.slice(index + 1)]);
const firstStagedLine = changes[index].modifiedStartLineNumber - 1;
textEditor.selections = [new Selection(firstStagedLine, 0, firstStagedLine, 0)];
}
@command('git.revertSelectedRanges', { diff: true })
async revertSelectedRanges(changes: LineChange[]): Promise<void> {
const textEditor = window.activeTextEditor;
if (!textEditor) {
return;
}
const modifiedDocument = textEditor.document;
const selections = textEditor.selections;
const selectedChanges = changes.filter(change => {
const modifiedRange = getModifiedRange(modifiedDocument, change);
return selections.every(selection => !selection.intersection(modifiedRange));
});
if (selectedChanges.length === changes.length) {
return;
}
const selectionsBeforeRevert = textEditor.selections;
await this._revertChanges(textEditor, selectedChanges);
textEditor.selections = selectionsBeforeRevert;
}
private async _revertChanges(textEditor: TextEditor, changes: LineChange[]): Promise<void> {
const modifiedDocument = textEditor.document;
const modifiedUri = modifiedDocument.uri;
if (modifiedUri.scheme !== 'file') {
return;
}
const originalUri = toGitUri(modifiedUri, '~');
const originalDocument = await workspace.openTextDocument(originalUri);
const visibleRangesBeforeRevert = textEditor.visibleRanges;
const result = applyLineChanges(originalDocument, modifiedDocument, changes);
const edit = new WorkspaceEdit();
edit.replace(modifiedUri, new Range(new Position(0, 0), modifiedDocument.lineAt(modifiedDocument.lineCount - 1).range.end), result);
workspace.applyEdit(edit);
await modifiedDocument.save();
textEditor.revealRange(visibleRangesBeforeRevert[0]);
}
@command('git.unstage')
async unstage(...resourceStates: SourceControlResourceState[]): Promise<void> {
resourceStates = resourceStates.filter(s => !!s);
if (resourceStates.length === 0 || (resourceStates[0] && !(resourceStates[0].resourceUri instanceof Uri))) {
const resource = this.getSCMResource();
if (!resource) {
return;
}
resourceStates = [resource];
}
const scmResources = resourceStates
.filter(s => s instanceof Resource && s.resourceGroupType === ResourceGroupType.Index) as Resource[];
if (!scmResources.length) {
return;
}
const resources = scmResources.map(r => r.resourceUri);
await this.runByRepository(resources, async (repository, resources) => repository.revert(resources));
}
@command('git.unstageAll', { repository: true })
async unstageAll(repository: Repository): Promise<void> {
await repository.revert([]);
}
@command('git.unstageSelectedRanges', { diff: true })
async unstageSelectedRanges(diffs: LineChange[]): Promise<void> {
const textEditor = window.activeTextEditor;
if (!textEditor) {
return;
}
const modifiedDocument = textEditor.document;
const modifiedUri = modifiedDocument.uri;
if (!isGitUri(modifiedUri)) {
return;
}
const { ref } = fromGitUri(modifiedUri);
if (ref !== '') {
return;
}
const originalUri = toGitUri(modifiedUri, 'HEAD');
const originalDocument = await workspace.openTextDocument(originalUri);
const selectedLines = toLineRanges(textEditor.selections, modifiedDocument);
const selectedDiffs = diffs
.map(diff => selectedLines.reduce<LineChange | null>((result, range) => result || intersectDiffWithRange(modifiedDocument, diff, range), null))
.filter(d => !!d) as LineChange[];
if (!selectedDiffs.length) {
return;
}
const invertedDiffs = selectedDiffs.map(invertLineChange);
const result = applyLineChanges(modifiedDocument, originalDocument, invertedDiffs);
await this.runByRepository(modifiedUri, async (repository, resource) => await repository.stage(resource, result));
}
@command('git.clean')
async clean(...resourceStates: SourceControlResourceState[]): Promise<void> {
resourceStates = resourceStates.filter(s => !!s);
if (resourceStates.length === 0 || (resourceStates[0] && !(resourceStates[0].resourceUri instanceof Uri))) {
const resource = this.getSCMResource();
if (!resource) {
return;
}
resourceStates = [resource];
}
const scmResources = resourceStates.filter(s => s instanceof Resource
&& (s.resourceGroupType === ResourceGroupType.WorkingTree || s.resourceGroupType === ResourceGroupType.Untracked)) as Resource[];
if (!scmResources.length) {
return;
}
const untrackedCount = scmResources.reduce((s, r) => s + (r.type === Status.UNTRACKED ? 1 : 0), 0);
let message: string;
let yes = localize('discard', "Discard Changes");
if (scmResources.length === 1) {
if (untrackedCount > 0) {
message = localize('confirm delete', "Are you sure you want to DELETE {0}?\nThis is IRREVERSIBLE!\nThis file will be FOREVER LOST if you proceed.", path.basename(scmResources[0].resourceUri.fsPath));
yes = localize('delete file', "Delete file");
} else {
if (scmResources[0].type === Status.DELETED) {
yes = localize('restore file', "Restore file");
message = localize('confirm restore', "Are you sure you want to restore {0}?", path.basename(scmResources[0].resourceUri.fsPath));
} else {
message = localize('confirm discard', "Are you sure you want to discard changes in {0}?", path.basename(scmResources[0].resourceUri.fsPath));
}
}
} else {
if (scmResources.every(resource => resource.type === Status.DELETED)) {
yes = localize('restore files', "Restore files");
message = localize('confirm restore multiple', "Are you sure you want to restore {0} files?", scmResources.length);
} else {
message = localize('confirm discard multiple', "Are you sure you want to discard changes in {0} files?", scmResources.length);
}
if (untrackedCount > 0) {
message = `${message}\n\n${localize('warn untracked', "This will DELETE {0} untracked files!\nThis is IRREVERSIBLE!\nThese files will be FOREVER LOST.", untrackedCount)}`;
}
}
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick !== yes) {
return;
}
const resources = scmResources.map(r => r.resourceUri);
await this.runByRepository(resources, async (repository, resources) => repository.clean(resources));
}
@command('git.cleanAll', { repository: true })
async cleanAll(repository: Repository): Promise<void> {
let resources = repository.workingTreeGroup.resourceStates;
if (resources.length === 0) {
return;
}
const trackedResources = resources.filter(r => r.type !== Status.UNTRACKED && r.type !== Status.IGNORED);
const untrackedResources = resources.filter(r => r.type === Status.UNTRACKED || r.type === Status.IGNORED);
if (untrackedResources.length === 0) {
await this._cleanTrackedChanges(repository, resources);
} else if (resources.length === 1) {
await this._cleanUntrackedChange(repository, resources[0]);
} else if (trackedResources.length === 0) {
await this._cleanUntrackedChanges(repository, resources);
} else { // resources.length > 1 && untrackedResources.length > 0 && trackedResources.length > 0
const untrackedMessage = untrackedResources.length === 1
? localize('there are untracked files single', "The following untracked file will be DELETED FROM DISK if discarded: {0}.", path.basename(untrackedResources[0].resourceUri.fsPath))
: localize('there are untracked files', "There are {0} untracked files which will be DELETED FROM DISK if discarded.", untrackedResources.length);
const message = localize('confirm discard all 2', "{0}\n\nThis is IRREVERSIBLE, your current working set will be FOREVER LOST.", untrackedMessage, resources.length);
const yesTracked = trackedResources.length === 1
? localize('yes discard tracked', "Discard 1 Tracked File", trackedResources.length)
: localize('yes discard tracked multiple', "Discard {0} Tracked Files", trackedResources.length);
const yesAll = localize('discardAll', "Discard All {0} Files", resources.length);
const pick = await window.showWarningMessage(message, { modal: true }, yesTracked, yesAll);
if (pick === yesTracked) {
resources = trackedResources;
} else if (pick !== yesAll) {
return;
}
await repository.clean(resources.map(r => r.resourceUri));
}
}
@command('git.cleanAllTracked', { repository: true })
async cleanAllTracked(repository: Repository): Promise<void> {
const resources = repository.workingTreeGroup.resourceStates
.filter(r => r.type !== Status.UNTRACKED && r.type !== Status.IGNORED);
if (resources.length === 0) {
return;
}
await this._cleanTrackedChanges(repository, resources);
}
@command('git.cleanAllUntracked', { repository: true })
async cleanAllUntracked(repository: Repository): Promise<void> {
const resources = [...repository.workingTreeGroup.resourceStates, ...repository.untrackedGroup.resourceStates]
.filter(r => r.type === Status.UNTRACKED || r.type === Status.IGNORED);
if (resources.length === 0) {
return;
}
if (resources.length === 1) {
await this._cleanUntrackedChange(repository, resources[0]);
} else {
await this._cleanUntrackedChanges(repository, resources);
}
}
private async _cleanTrackedChanges(repository: Repository, resources: Resource[]): Promise<void> {
const message = resources.length === 1
? localize('confirm discard all single', "Are you sure you want to discard changes in {0}?", path.basename(resources[0].resourceUri.fsPath))
: localize('confirm discard all', "Are you sure you want to discard ALL changes in {0} files?\nThis is IRREVERSIBLE!\nYour current working set will be FOREVER LOST if you proceed.", resources.length);
const yes = resources.length === 1
? localize('discardAll multiple', "Discard 1 File")
: localize('discardAll', "Discard All {0} Files", resources.length);
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick !== yes) {
return;
}
await repository.clean(resources.map(r => r.resourceUri));
}
private async _cleanUntrackedChange(repository: Repository, resource: Resource): Promise<void> {
const message = localize('confirm delete', "Are you sure you want to DELETE {0}?\nThis is IRREVERSIBLE!\nThis file will be FOREVER LOST if you proceed.", path.basename(resource.resourceUri.fsPath));
const yes = localize('delete file', "Delete file");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick !== yes) {
return;
}
await repository.clean([resource.resourceUri]);
}
private async _cleanUntrackedChanges(repository: Repository, resources: Resource[]): Promise<void> {
const message = localize('confirm delete multiple', "Are you sure you want to DELETE {0} files?\nThis is IRREVERSIBLE!\nThese files will be FOREVER LOST if you proceed.", resources.length);
const yes = localize('delete files', "Delete Files");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick !== yes) {
return;
}
await repository.clean(resources.map(r => r.resourceUri));
}
private async smartCommit(
repository: Repository,
getCommitMessage: () => Promise<string | undefined>,
opts?: CommitOptions
): Promise<boolean> {
const config = workspace.getConfiguration('git', Uri.file(repository.root));
let promptToSaveFilesBeforeCommit = config.get<'always' | 'staged' | 'never'>('promptToSaveFilesBeforeCommit');
// migration
if (promptToSaveFilesBeforeCommit as any === true) {
promptToSaveFilesBeforeCommit = 'always';
} else if (promptToSaveFilesBeforeCommit as any === false) {
promptToSaveFilesBeforeCommit = 'never';
}
const enableSmartCommit = config.get<boolean>('enableSmartCommit') === true;
const enableCommitSigning = config.get<boolean>('enableCommitSigning') === true;
let noStagedChanges = repository.indexGroup.resourceStates.length === 0;
let noUnstagedChanges = repository.workingTreeGroup.resourceStates.length === 0;
if (promptToSaveFilesBeforeCommit !== 'never') {
let documents = workspace.textDocuments
.filter(d => !d.isUntitled && d.isDirty && isDescendant(repository.root, d.uri.fsPath));
if (promptToSaveFilesBeforeCommit === 'staged' || repository.indexGroup.resourceStates.length > 0) {
documents = documents
.filter(d => repository.indexGroup.resourceStates.some(s => pathEquals(s.resourceUri.fsPath, d.uri.fsPath)));
}
if (documents.length > 0) {
const message = documents.length === 1
? localize('unsaved files single', "The following file has unsaved changes which won't be included in the commit if you proceed: {0}.\n\nWould you like to save it before committing?", path.basename(documents[0].uri.fsPath))
: localize('unsaved files', "There are {0} unsaved files.\n\nWould you like to save them before committing?", documents.length);
const saveAndCommit = localize('save and commit', "Save All & Commit");
const commit = localize('commit', "Commit Staged Changes");
const pick = await window.showWarningMessage(message, { modal: true }, saveAndCommit, commit);
if (pick === saveAndCommit) {
await Promise.all(documents.map(d => d.save()));
await repository.add(documents.map(d => d.uri));
noStagedChanges = repository.indexGroup.resourceStates.length === 0;
noUnstagedChanges = repository.workingTreeGroup.resourceStates.length === 0;
} else if (pick !== commit) {
return false; // do not commit on cancel
}
}
}
if (!opts) {
opts = { all: noStagedChanges };
} else if (!opts.all && noStagedChanges && !opts.empty) {
opts = { ...opts, all: true };
}
// no changes, and the user has not configured to commit all in this case
if (!noUnstagedChanges && noStagedChanges && !enableSmartCommit && !opts.empty) {
const suggestSmartCommit = config.get<boolean>('suggestSmartCommit') === true;
if (!suggestSmartCommit) {
return false;
}
// prompt the user if we want to commit all or not
const message = localize('no staged changes', "There are no staged changes to commit.\n\nWould you like to stage all your changes and commit them directly?");
const yes = localize('yes', "Yes");
const always = localize('always', "Always");
const never = localize('never', "Never");
const pick = await window.showWarningMessage(message, { modal: true }, yes, always, never);
if (pick === always) {
config.update('enableSmartCommit', true, true);
} else if (pick === never) {
config.update('suggestSmartCommit', false, true);
return false;
} else if (pick !== yes) {
return false; // do not commit on cancel
}
}
// enable signing of commits if configured
opts.signCommit = enableCommitSigning;
if (config.get<boolean>('alwaysSignOff')) {
opts.signoff = true;
}
const smartCommitChanges = config.get<'all' | 'tracked'>('smartCommitChanges');
if (
(
// no changes
(noStagedChanges && noUnstagedChanges)
// or no staged changes and not `all`
|| (!opts.all && noStagedChanges)
// no staged changes and no tracked unstaged changes
|| (noStagedChanges && smartCommitChanges === 'tracked' && repository.workingTreeGroup.resourceStates.every(r => r.type === Status.UNTRACKED))
)
// amend allows changing only the commit message
&& !opts.amend
&& !opts.empty
) {
const commitAnyway = localize('commit anyway', "Create Empty Commit");
const answer = await window.showInformationMessage(localize('no changes', "There are no changes to commit."), commitAnyway);
if (answer !== commitAnyway) {
return false;
}
opts.empty = true;
}
if (opts.noVerify) {
if (!config.get<boolean>('allowNoVerifyCommit')) {
await window.showErrorMessage(localize('no verify commit not allowed', "Commits without verification are not allowed, please enable them with the 'git.allowNoVerifyCommit' setting."));
return false;
}
if (config.get<boolean>('confirmNoVerifyCommit')) {
const message = localize('confirm no verify commit', "You are about to commit your changes without verification, this skips pre-commit hooks and can be undesirable.\n\nAre you sure to continue?");
const yes = localize('ok', "OK");
const neverAgain = localize('never ask again', "OK, Don't Ask Again");
const pick = await window.showWarningMessage(message, { modal: true }, yes, neverAgain);
if (pick === neverAgain) {
config.update('confirmNoVerifyCommit', false, true);
} else if (pick !== yes) {
return false;
}
}
}
let message = await getCommitMessage();
if (!message && !opts.amend) {
return false;
}
if (opts.all && smartCommitChanges === 'tracked') {
opts.all = 'tracked';
}
if (opts.all && config.get<'mixed' | 'separate' | 'hidden'>('untrackedChanges') !== 'mixed') {
opts.all = 'tracked';
}
await repository.commit(message, opts);
const postCommitCommand = config.get<'none' | 'push' | 'sync'>('postCommitCommand');
switch (postCommitCommand) {
case 'push':
await this._push(repository, { pushType: PushType.Push, silent: true });
break;
case 'sync':
await this.sync(repository);
break;
}
return true;
}
private async commitWithAnyInput(repository: Repository, opts?: CommitOptions): Promise<void> {
const message = repository.inputBox.value;
const getCommitMessage = async () => {
let _message: string | undefined = message;
if (!_message) {
let value: string | undefined = undefined;
if (opts && opts.amend && repository.HEAD && repository.HEAD.commit) {
return undefined;
}
const branchName = repository.headShortName;
let placeHolder: string;
if (branchName) {
placeHolder = localize('commitMessageWithHeadLabel2', "Message (commit on '{0}')", branchName);
} else {
placeHolder = localize('commit message', "Commit message");
}
_message = await window.showInputBox({
value,
placeHolder,
prompt: localize('provide commit message', "Please provide a commit message"),
ignoreFocusOut: true
});
}
return _message;
};
const didCommit = await this.smartCommit(repository, getCommitMessage, opts);
if (message && didCommit) {
repository.inputBox.value = await repository.getInputTemplate();
}
}
@command('git.commit', { repository: true })
async commit(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository);
}
@command('git.commitStaged', { repository: true })
async commitStaged(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: false });
}
@command('git.commitStagedSigned', { repository: true })
async commitStagedSigned(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: false, signoff: true });
}
@command('git.commitStagedAmend', { repository: true })
async commitStagedAmend(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: false, amend: true });
}
@command('git.commitAll', { repository: true })
async commitAll(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: true });
}
@command('git.commitAllSigned', { repository: true })
async commitAllSigned(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: true, signoff: true });
}
@command('git.commitAllAmend', { repository: true })
async commitAllAmend(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: true, amend: true });
}
private async _commitEmpty(repository: Repository, noVerify?: boolean): Promise<void> {
const root = Uri.file(repository.root);
const config = workspace.getConfiguration('git', root);
const shouldPrompt = config.get<boolean>('confirmEmptyCommits') === true;
if (shouldPrompt) {
const message = localize('confirm emtpy commit', "Are you sure you want to create an empty commit?");
const yes = localize('yes', "Yes");
const neverAgain = localize('yes never again', "Yes, Don't Show Again");
const pick = await window.showWarningMessage(message, { modal: true }, yes, neverAgain);
if (pick === neverAgain) {
await config.update('confirmEmptyCommits', false, true);
} else if (pick !== yes) {
return;
}
}
await this.commitWithAnyInput(repository, { empty: true, noVerify });
}
@command('git.commitEmpty', { repository: true })
async commitEmpty(repository: Repository): Promise<void> {
await this._commitEmpty(repository);
}
@command('git.commitNoVerify', { repository: true })
async commitNoVerify(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { noVerify: true });
}
@command('git.commitStagedNoVerify', { repository: true })
async commitStagedNoVerify(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: false, noVerify: true });
}
@command('git.commitStagedSignedNoVerify', { repository: true })
async commitStagedSignedNoVerify(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: false, signoff: true, noVerify: true });
}
@command('git.commitStagedAmendNoVerify', { repository: true })
async commitStagedAmendNoVerify(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: false, amend: true, noVerify: true });
}
@command('git.commitAllNoVerify', { repository: true })
async commitAllNoVerify(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: true, noVerify: true });
}
@command('git.commitAllSignedNoVerify', { repository: true })
async commitAllSignedNoVerify(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: true, signoff: true, noVerify: true });
}
@command('git.commitAllAmendNoVerify', { repository: true })
async commitAllAmendNoVerify(repository: Repository): Promise<void> {
await this.commitWithAnyInput(repository, { all: true, amend: true, noVerify: true });
}
@command('git.commitEmptyNoVerify', { repository: true })
async commitEmptyNoVerify(repository: Repository): Promise<void> {
await this._commitEmpty(repository, true);
}
@command('git.restoreCommitTemplate', { repository: true })
async restoreCommitTemplate(repository: Repository): Promise<void> {
repository.inputBox.value = await repository.getCommitTemplate();
}
@command('git.undoCommit', { repository: true })
async undoCommit(repository: Repository): Promise<void> {
const HEAD = repository.HEAD;
if (!HEAD || !HEAD.commit) {
window.showWarningMessage(localize('no more', "Can't undo because HEAD doesn't point to any commit."));
return;
}
const commit = await repository.getCommit('HEAD');
if (commit.parents.length > 1) {
const yes = localize('undo commit', "Undo merge commit");
const result = await window.showWarningMessage(localize('merge commit', "The last commit was a merge commit. Are you sure you want to undo it?"), { modal: true }, yes);
if (result !== yes) {
return;
}
}
if (commit.parents.length > 0) {
await repository.reset('HEAD~');
} else {
await repository.deleteRef('HEAD');
await this.unstageAll(repository);
}
repository.inputBox.value = commit.message;
}
@command('git.checkout', { repository: true })
async checkout(repository: Repository, treeish?: string): Promise<boolean> {
return this._checkout(repository, { treeish });
}
@command('git.checkoutDetached', { repository: true })
async checkoutDetached(repository: Repository, treeish?: string): Promise<boolean> {
return this._checkout(repository, { detached: true, treeish });
}
private async _checkout(repository: Repository, opts?: { detached?: boolean; treeish?: string }): Promise<boolean> {
if (typeof opts?.treeish === 'string') {
await repository.checkout(opts?.treeish, opts);
return true;
}
const createBranch = new CreateBranchItem();
const createBranchFrom = new CreateBranchFromItem();
const checkoutDetached = new CheckoutDetachedItem();
const picks: QuickPickItem[] = [];
if (!opts?.detached) {
picks.push(createBranch, createBranchFrom, checkoutDetached);
}
picks.push(...createCheckoutItems(repository));
const quickpick = window.createQuickPick();
quickpick.items = picks;
quickpick.placeholder = opts?.detached
? localize('select a ref to checkout detached', 'Select a ref to checkout in detached mode')
: localize('select a ref to checkout', 'Select a ref to checkout');
quickpick.show();
const choice = await new Promise<QuickPickItem | undefined>(c => quickpick.onDidAccept(() => c(quickpick.activeItems[0])));
quickpick.hide();
if (!choice) {
return false;
}
if (choice === createBranch) {
await this._branch(repository, quickpick.value);
} else if (choice === createBranchFrom) {
await this._branch(repository, quickpick.value, true);
} else if (choice === checkoutDetached) {
return this._checkout(repository, { detached: true });
} else {
const item = choice as CheckoutItem;
try {
await item.run(repository, opts);
} catch (err) {
if (err.gitErrorCode !== GitErrorCodes.DirtyWorkTree) {
throw err;
}
const force = localize('force', "Force Checkout");
const stash = localize('stashcheckout', "Stash & Checkout");
const choice = await window.showWarningMessage(localize('local changes', "Your local changes would be overwritten by checkout."), { modal: true }, force, stash);
if (choice === force) {
await this.cleanAll(repository);
await item.run(repository, opts);
} else if (choice === stash) {
await this.stash(repository);
await item.run(repository, opts);
await this.stashPopLatest(repository);
}
}
}
return true;
}
@command('git.branch', { repository: true })
async branch(repository: Repository): Promise<void> {
await this._branch(repository);
}
@command('git.branchFrom', { repository: true })
async branchFrom(repository: Repository): Promise<void> {
await this._branch(repository, undefined, true);
}
private async promptForBranchName(defaultName?: string, initialValue?: string): Promise<string> {
const config = workspace.getConfiguration('git');
const branchWhitespaceChar = config.get<string>('branchWhitespaceChar')!;
const branchValidationRegex = config.get<string>('branchValidationRegex')!;
const sanitize = (name: string) => name ?
name.trim().replace(/^-+/, '').replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$|\[|\]$/g, branchWhitespaceChar)
: name;
const rawBranchName = defaultName || await window.showInputBox({
placeHolder: localize('branch name', "Branch name"),
prompt: localize('provide branch name', "Please provide a new branch name"),
value: initialValue,
ignoreFocusOut: true,
validateInput: (name: string) => {
const validateName = new RegExp(branchValidationRegex);
if (validateName.test(sanitize(name))) {
return null;
}
return localize('branch name format invalid', "Branch name needs to match regex: {0}", branchValidationRegex);
}
});
return sanitize(rawBranchName || '');
}
private async _branch(repository: Repository, defaultName?: string, from = false): Promise<void> {
const branchName = await this.promptForBranchName(defaultName);
if (!branchName) {
return;
}
let target = 'HEAD';
if (from) {
const picks = [new HEADItem(repository), ...createCheckoutItems(repository)];
const placeHolder = localize('select a ref to create a new branch from', 'Select a ref to create the \'{0}\' branch from', branchName);
const choice = await window.showQuickPick(picks, { placeHolder });
if (!choice) {
return;
}
target = choice.label;
}
await repository.branch(branchName, true, target);
}
@command('git.deleteBranch', { repository: true })
async deleteBranch(repository: Repository, name: string, force?: boolean): Promise<void> {
let run: (force?: boolean) => Promise<void>;
if (typeof name === 'string') {
run = force => repository.deleteBranch(name, force);
} else {
const currentHead = repository.HEAD && repository.HEAD.name;
const heads = repository.refs.filter(ref => ref.type === RefType.Head && ref.name !== currentHead)
.map(ref => new BranchDeleteItem(ref));
const placeHolder = localize('select branch to delete', 'Select a branch to delete');
const choice = await window.showQuickPick<BranchDeleteItem>(heads, { placeHolder });
if (!choice || !choice.branchName) {
return;
}
name = choice.branchName;
run = force => choice.run(repository, force);
}
try {
await run(force);
} catch (err) {
if (err.gitErrorCode !== GitErrorCodes.BranchNotFullyMerged) {
throw err;
}
const message = localize('confirm force delete branch', "The branch '{0}' is not fully merged. Delete anyway?", name);
const yes = localize('delete branch', "Delete Branch");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick === yes) {
await run(true);
}
}
}
@command('git.renameBranch', { repository: true })
async renameBranch(repository: Repository): Promise<void> {
const currentBranchName = repository.HEAD && repository.HEAD.name;
const branchName = await this.promptForBranchName(undefined, currentBranchName);
if (!branchName) {
return;
}
try {
await repository.renameBranch(branchName);
} catch (err) {
switch (err.gitErrorCode) {
case GitErrorCodes.InvalidBranchName:
window.showErrorMessage(localize('invalid branch name', 'Invalid branch name'));
return;
case GitErrorCodes.BranchAlreadyExists:
window.showErrorMessage(localize('branch already exists', "A branch named '{0}' already exists", branchName));
return;
default:
throw err;
}
}
}
@command('git.merge', { repository: true })
async merge(repository: Repository): Promise<void> {
const config = workspace.getConfiguration('git');
const checkoutType = config.get<string | string[]>('checkoutType');
const includeRemotes = checkoutType === 'all' || checkoutType === 'remote' || checkoutType?.includes('remote');
const heads = repository.refs.filter(ref => ref.type === RefType.Head)
.filter(ref => ref.name || ref.commit)
.map(ref => new MergeItem(ref as Branch));
const remoteHeads = (includeRemotes ? repository.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
.filter(ref => ref.name || ref.commit)
.map(ref => new MergeItem(ref as Branch));
const picks = [...heads, ...remoteHeads];
const placeHolder = localize('select a branch to merge from', 'Select a branch to merge from');
const choice = await window.showQuickPick<MergeItem>(picks, { placeHolder });
if (!choice) {
return;
}
await choice.run(repository);
}
@command('git.rebase', { repository: true })
async rebase(repository: Repository): Promise<void> {
const config = workspace.getConfiguration('git');
const checkoutType = config.get<string | string[]>('checkoutType');
const includeRemotes = checkoutType === 'all' || checkoutType === 'remote' || checkoutType?.includes('remote');
const heads = repository.refs.filter(ref => ref.type === RefType.Head)
.filter(ref => ref.name !== repository.HEAD?.name)
.filter(ref => ref.name || ref.commit);
const remoteHeads = (includeRemotes ? repository.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
.filter(ref => ref.name || ref.commit);
const picks = [...heads, ...remoteHeads]
.map(ref => new RebaseItem(ref));
// set upstream branch as first
if (repository.HEAD?.upstream) {
const upstreamName = `${repository.HEAD?.upstream.remote}/${repository.HEAD?.upstream.name}`;
const index = picks.findIndex(e => e.ref.name === upstreamName);
if (index > -1) {
const [ref] = picks.splice(index, 1);
ref.description = '(upstream)';
picks.unshift(ref);
}
}
const placeHolder = localize('select a branch to rebase onto', 'Select a branch to rebase onto');
const choice = await window.showQuickPick<RebaseItem>(picks, { placeHolder });
if (!choice) {
return;
}
await choice.run(repository);
}
@command('git.createTag', { repository: true })
async createTag(repository: Repository): Promise<void> {
const inputTagName = await window.showInputBox({
placeHolder: localize('tag name', "Tag name"),
prompt: localize('provide tag name', "Please provide a tag name"),
ignoreFocusOut: true
});
if (!inputTagName) {
return;
}
const inputMessage = await window.showInputBox({
placeHolder: localize('tag message', "Message"),
prompt: localize('provide tag message', "Please provide a message to annotate the tag"),
ignoreFocusOut: true
});
const name = inputTagName.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$/g, '-');
await repository.tag(name, inputMessage);
}
@command('git.deleteTag', { repository: true })
async deleteTag(repository: Repository): Promise<void> {
const picks = repository.refs.filter(ref => ref.type === RefType.Tag)
.map(ref => new TagItem(ref));
if (picks.length === 0) {
window.showWarningMessage(localize('no tags', "This repository has no tags."));
return;
}
const placeHolder = localize('select a tag to delete', 'Select a tag to delete');
const choice = await window.showQuickPick(picks, { placeHolder });
if (!choice) {
return;
}
await repository.deleteTag(choice.label);
}
@command('git.fetch', { repository: true })
async fetch(repository: Repository): Promise<void> {
if (repository.remotes.length === 0) {
window.showWarningMessage(localize('no remotes to fetch', "This repository has no remotes configured to fetch from."));
return;
}
await repository.fetchDefault();
}
@command('git.fetchPrune', { repository: true })
async fetchPrune(repository: Repository): Promise<void> {
if (repository.remotes.length === 0) {
window.showWarningMessage(localize('no remotes to fetch', "This repository has no remotes configured to fetch from."));
return;
}
await repository.fetchPrune();
}
@command('git.fetchAll', { repository: true })
async fetchAll(repository: Repository): Promise<void> {
if (repository.remotes.length === 0) {
window.showWarningMessage(localize('no remotes to fetch', "This repository has no remotes configured to fetch from."));
return;
}
await repository.fetchAll();
}
@command('git.pullFrom', { repository: true })
async pullFrom(repository: Repository): Promise<void> {
const remotes = repository.remotes;
if (remotes.length === 0) {
window.showWarningMessage(localize('no remotes to pull', "Your repository has no remotes configured to pull from."));
return;
}
const remotePicks = remotes.filter(r => r.fetchUrl !== undefined).map(r => ({ label: r.name, description: r.fetchUrl! }));
const placeHolder = localize('pick remote pull repo', "Pick a remote to pull the branch from");
const remotePick = await window.showQuickPick(remotePicks, { placeHolder });
if (!remotePick) {
return;
}
const remoteRefs = repository.refs;
const remoteRefsFiltered = remoteRefs.filter(r => (r.remote === remotePick.label));
const branchPicks = remoteRefsFiltered.map(r => ({ label: r.name! }));
const branchPlaceHolder = localize('pick branch pull', "Pick a branch to pull from");
const branchPick = await window.showQuickPick(branchPicks, { placeHolder: branchPlaceHolder });
if (!branchPick) {
return;
}
const remoteCharCnt = remotePick.label.length;
await repository.pullFrom(false, remotePick.label, branchPick.label.slice(remoteCharCnt + 1));
}
@command('git.pull', { repository: true })
async pull(repository: Repository): Promise<void> {
const remotes = repository.remotes;
if (remotes.length === 0) {
window.showWarningMessage(localize('no remotes to pull', "Your repository has no remotes configured to pull from."));
return;
}
await repository.pull(repository.HEAD);
}
@command('git.pullRebase', { repository: true })
async pullRebase(repository: Repository): Promise<void> {
const remotes = repository.remotes;
if (remotes.length === 0) {
window.showWarningMessage(localize('no remotes to pull', "Your repository has no remotes configured to pull from."));
return;
}
await repository.pullWithRebase(repository.HEAD);
}
private async _push(repository: Repository, pushOptions: PushOptions) {
const remotes = repository.remotes;
if (remotes.length === 0) {
if (pushOptions.silent) {
return;
}
const addRemote = localize('addremote', 'Add Remote');
const result = await window.showWarningMessage(localize('no remotes to push', "Your repository has no remotes configured to push to."), addRemote);
if (result === addRemote) {
await this.addRemote(repository);
}
return;
}
const config = workspace.getConfiguration('git', Uri.file(repository.root));
let forcePushMode: ForcePushMode | undefined = undefined;
if (pushOptions.forcePush) {
if (!config.get<boolean>('allowForcePush')) {
await window.showErrorMessage(localize('force push not allowed', "Force push is not allowed, please enable it with the 'git.allowForcePush' setting."));
return;
}
forcePushMode = config.get<boolean>('useForcePushWithLease') === true ? ForcePushMode.ForceWithLease : ForcePushMode.Force;
if (config.get<boolean>('confirmForcePush')) {
const message = localize('confirm force push', "You are about to force push your changes, this can be destructive and could inadvertently overwrite changes made by others.\n\nAre you sure to continue?");
const yes = localize('ok', "OK");
const neverAgain = localize('never ask again', "OK, Don't Ask Again");
const pick = await window.showWarningMessage(message, { modal: true }, yes, neverAgain);
if (pick === neverAgain) {
config.update('confirmForcePush', false, true);
} else if (pick !== yes) {
return;
}
}
}
if (pushOptions.pushType === PushType.PushFollowTags) {
await repository.pushFollowTags(undefined, forcePushMode);
return;
}
if (pushOptions.pushType === PushType.PushTags) {
await repository.pushTags(undefined, forcePushMode);
}
if (!repository.HEAD || !repository.HEAD.name) {
if (!pushOptions.silent) {
window.showWarningMessage(localize('nobranch', "Please check out a branch to push to a remote."));
}
return;
}
if (pushOptions.pushType === PushType.Push) {
try {
await repository.push(repository.HEAD, forcePushMode);
} catch (err) {
if (err.gitErrorCode !== GitErrorCodes.NoUpstreamBranch) {
throw err;
}
if (pushOptions.silent) {
return;
}
const branchName = repository.HEAD.name;
const message = localize('confirm publish branch', "The branch '{0}' has no remote branch. Would you like to publish this branch?", branchName);
const yes = localize('ok', "OK");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick === yes) {
await this.publish(repository);
}
}
} else {
const branchName = repository.HEAD.name;
if (!pushOptions.pushTo?.remote) {
const addRemote = new AddRemoteItem(this);
const picks = [...remotes.filter(r => r.pushUrl !== undefined).map(r => ({ label: r.name, description: r.pushUrl })), addRemote];
const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
const choice = await window.showQuickPick(picks, { placeHolder });
if (!choice) {
return;
}
if (choice === addRemote) {
const newRemote = await this.addRemote(repository);
if (newRemote) {
await repository.pushTo(newRemote, branchName, undefined, forcePushMode);
}
} else {
await repository.pushTo(choice.label, branchName, undefined, forcePushMode);
}
} else {
await repository.pushTo(pushOptions.pushTo.remote, pushOptions.pushTo.refspec || branchName, pushOptions.pushTo.setUpstream, forcePushMode);
}
}
}
@command('git.push', { repository: true })
async push(repository: Repository): Promise<void> {
await this._push(repository, { pushType: PushType.Push });
}
@command('git.pushForce', { repository: true })
async pushForce(repository: Repository): Promise<void> {
await this._push(repository, { pushType: PushType.Push, forcePush: true });
}
@command('git.pushWithTags', { repository: true })
async pushFollowTags(repository: Repository): Promise<void> {
await this._push(repository, { pushType: PushType.PushFollowTags });
}
@command('git.pushWithTagsForce', { repository: true })
async pushFollowTagsForce(repository: Repository): Promise<void> {
await this._push(repository, { pushType: PushType.PushFollowTags, forcePush: true });
}
@command('git.cherryPick', { repository: true })
async cherryPick(repository: Repository): Promise<void> {
const hash = await window.showInputBox({
placeHolder: localize('commit hash', "Commit Hash"),
prompt: localize('provide commit hash', "Please provide the commit hash"),
ignoreFocusOut: true
});
if (!hash) {
return;
}
await repository.cherryPick(hash);
}
@command('git.pushTo', { repository: true })
async pushTo(repository: Repository, remote?: string, refspec?: string, setUpstream?: boolean): Promise<void> {
await this._push(repository, { pushType: PushType.PushTo, pushTo: { remote: remote, refspec: refspec, setUpstream: setUpstream } });
}
@command('git.pushToForce', { repository: true })
async pushToForce(repository: Repository, remote?: string, refspec?: string, setUpstream?: boolean): Promise<void> {
await this._push(repository, { pushType: PushType.PushTo, pushTo: { remote: remote, refspec: refspec, setUpstream: setUpstream }, forcePush: true });
}
@command('git.pushTags', { repository: true })
async pushTags(repository: Repository): Promise<void> {
await this._push(repository, { pushType: PushType.PushTags });
}
@command('git.addRemote', { repository: true })
async addRemote(repository: Repository): Promise<string | undefined> {
const url = await pickRemoteSource({
providerLabel: provider => localize('addfrom', "Add remote from {0}", provider.name),
urlLabel: localize('addFrom', "Add remote from URL")
});
if (!url) {
return;
}
const resultName = await window.showInputBox({
placeHolder: localize('remote name', "Remote name"),
prompt: localize('provide remote name', "Please provide a remote name"),
ignoreFocusOut: true,
validateInput: (name: string) => {
if (!sanitizeRemoteName(name)) {
return localize('remote name format invalid', "Remote name format invalid");
} else if (repository.remotes.find(r => r.name === name)) {
return localize('remote already exists', "Remote '{0}' already exists.", name);
}
return null;
}
});
const name = sanitizeRemoteName(resultName || '');
if (!name) {
return;
}
await repository.addRemote(name, url.trim());
await repository.fetch({ remote: name });
return name;
}
@command('git.removeRemote', { repository: true })
async removeRemote(repository: Repository): Promise<void> {
const remotes = repository.remotes;
if (remotes.length === 0) {
window.showErrorMessage(localize('no remotes added', "Your repository has no remotes."));
return;
}
const picks = remotes.map(r => r.name);
const placeHolder = localize('remove remote', "Pick a remote to remove");
const remoteName = await window.showQuickPick(picks, { placeHolder });
if (!remoteName) {
return;
}
await repository.removeRemote(remoteName);
}
private async _sync(repository: Repository, rebase: boolean): Promise<void> {
const HEAD = repository.HEAD;
if (!HEAD) {
return;
} else if (!HEAD.upstream) {
const branchName = HEAD.name;
const message = localize('confirm publish branch', "The branch '{0}' has no remote branch. Would you like to publish this branch?", branchName);
const yes = localize('ok', "OK");
const pick = await window.showWarningMessage(message, { modal: true }, yes);
if (pick === yes) {
await this.publish(repository);
}
return;
}
const remoteName = HEAD.remote || HEAD.upstream.remote;
const remote = repository.remotes.find(r => r.name === remoteName);
const isReadonly = remote && remote.isReadOnly;
const config = workspace.getConfiguration('git');
const shouldPrompt = !isReadonly && config.get<boolean>('confirmSync') === true;
if (shouldPrompt) {
const message = localize('sync is unpredictable', "This action will push and pull commits to and from '{0}/{1}'.", HEAD.upstream.remote, HEAD.upstream.name);
const yes = localize('ok', "OK");
const neverAgain = localize('never again', "OK, Don't Show Again");
const pick = await window.showWarningMessage(message, { modal: true }, yes, neverAgain);
if (pick === neverAgain) {
await config.update('confirmSync', false, true);
} else if (pick !== yes) {
return;
}
}
if (rebase) {
await repository.syncRebase(HEAD);
} else {
await repository.sync(HEAD);
}
}
@command('git.sync', { repository: true })
async sync(repository: Repository): Promise<void> {
try {
await this._sync(repository, false);
} catch (err) {
if (/Cancelled/i.test(err && (err.message || err.stderr || ''))) {
return;
}
throw err;
}
}
@command('git._syncAll')
async syncAll(): Promise<void> {
await Promise.all(this.model.repositories.map(async repository => {
const HEAD = repository.HEAD;
if (!HEAD || !HEAD.upstream) {
return;
}
await repository.sync(HEAD);
}));
}
@command('git.syncRebase', { repository: true })
async syncRebase(repository: Repository): Promise<void> {
try {
await this._sync(repository, true);
} catch (err) {
if (/Cancelled/i.test(err && (err.message || err.stderr || ''))) {
return;
}
throw err;
}
}
@command('git.publish', { repository: true })
async publish(repository: Repository): Promise<void> {
const branchName = repository.HEAD && repository.HEAD.name || '';
const remotes = repository.remotes;
if (remotes.length === 0) {
const publishers = this.model.getRemoteSourcePublishers();
if (publishers.length === 0) {
window.showWarningMessage(localize('no remotes to publish', "Your repository has no remotes configured to publish to."));
return;
}
let publisher: RemoteSourcePublisher;
if (publishers.length === 1) {
publisher = publishers[0];
} else {
const picks = publishers
.map(provider => ({ label: (provider.icon ? `$(${provider.icon}) ` : '') + localize('publish to', "Publish to {0}", provider.name), alwaysShow: true, provider }));
const placeHolder = localize('pick provider', "Pick a provider to publish the branch '{0}' to:", branchName);
const choice = await window.showQuickPick(picks, { placeHolder });
if (!choice) {
return;
}
publisher = choice.provider;
}
await publisher.publishRepository(new ApiRepository(repository));
this.model.firePublishEvent(repository, branchName);
return;
}
if (remotes.length === 1) {
await repository.pushTo(remotes[0].name, branchName, true);
this.model.firePublishEvent(repository, branchName);
return;
}
const addRemote = new AddRemoteItem(this);
const picks = [...repository.remotes.map(r => ({ label: r.name, description: r.pushUrl })), addRemote];
const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
const choice = await window.showQuickPick(picks, { placeHolder });
if (!choice) {
return;
}
if (choice === addRemote) {
const newRemote = await this.addRemote(repository);
if (newRemote) {
await repository.pushTo(newRemote, branchName, true);
this.model.firePublishEvent(repository, branchName);
}
} else {
await repository.pushTo(choice.label, branchName, true);
this.model.firePublishEvent(repository, branchName);
}
}
@command('git.ignore')
async ignore(...resourceStates: SourceControlResourceState[]): Promise<void> {
resourceStates = resourceStates.filter(s => !!s);
if (resourceStates.length === 0 || (resourceStates[0] && !(resourceStates[0].resourceUri instanceof Uri))) {
const resource = this.getSCMResource();
if (!resource) {
return;
}
resourceStates = [resource];
}
const resources = resourceStates
.filter(s => s instanceof Resource)
.map(r => r.resourceUri);
if (!resources.length) {
return;
}
await this.runByRepository(resources, async (repository, resources) => repository.ignore(resources));
}
@command('git.revealInExplorer')
async revealInExplorer(resourceState: SourceControlResourceState): Promise<void> {
if (!resourceState) {
return;
}
if (!(resourceState.resourceUri instanceof Uri)) {
return;
}
await commands.executeCommand('revealInExplorer', resourceState.resourceUri);
}
private async _stash(repository: Repository, includeUntracked = false): Promise<void> {
const noUnstagedChanges = repository.workingTreeGroup.resourceStates.length === 0
&& (!includeUntracked || repository.untrackedGroup.resourceStates.length === 0);
const noStagedChanges = repository.indexGroup.resourceStates.length === 0;
if (noUnstagedChanges && noStagedChanges) {
window.showInformationMessage(localize('no changes stash', "There are no changes to stash."));
return;
}
const config = workspace.getConfiguration('git', Uri.file(repository.root));
const promptToSaveFilesBeforeStashing = config.get<'always' | 'staged' | 'never'>('promptToSaveFilesBeforeStash');
if (promptToSaveFilesBeforeStashing !== 'never') {
let documents = workspace.textDocuments
.filter(d => !d.isUntitled && d.isDirty && isDescendant(repository.root, d.uri.fsPath));
if (promptToSaveFilesBeforeStashing === 'staged' || repository.indexGroup.resourceStates.length > 0) {
documents = documents
.filter(d => repository.indexGroup.resourceStates.some(s => pathEquals(s.resourceUri.fsPath, d.uri.fsPath)));
}
if (documents.length > 0) {
const message = documents.length === 1
? localize('unsaved stash files single', "The following file has unsaved changes which won't be included in the stash if you proceed: {0}.\n\nWould you like to save it before stashing?", path.basename(documents[0].uri.fsPath))
: localize('unsaved stash files', "There are {0} unsaved files.\n\nWould you like to save them before stashing?", documents.length);
const saveAndStash = localize('save and stash', "Save All & Stash");
const stash = localize('stash', "Stash Anyway");
const pick = await window.showWarningMessage(message, { modal: true }, saveAndStash, stash);
if (pick === saveAndStash) {
await Promise.all(documents.map(d => d.save()));
} else if (pick !== stash) {
return; // do not stash on cancel
}
}
}
let message: string | undefined;
if (config.get<boolean>('useCommitInputAsStashMessage') && (!repository.sourceControl.commitTemplate || repository.inputBox.value !== repository.sourceControl.commitTemplate)) {
message = repository.inputBox.value;
}
message = await window.showInputBox({
value: message,
prompt: localize('provide stash message', "Optionally provide a stash message"),
placeHolder: localize('stash message', "Stash message")
});
if (typeof message === 'undefined') {
return;
}
await repository.createStash(message, includeUntracked);
}
@command('git.stash', { repository: true })
stash(repository: Repository): Promise<void> {
return this._stash(repository);
}
@command('git.stashIncludeUntracked', { repository: true })
stashIncludeUntracked(repository: Repository): Promise<void> {
return this._stash(repository, true);
}
@command('git.stashPop', { repository: true })
async stashPop(repository: Repository): Promise<void> {
const placeHolder = localize('pick stash to pop', "Pick a stash to pop");
const stash = await this.pickStash(repository, placeHolder);
if (!stash) {
return;
}
await repository.popStash(stash.index);
}
@command('git.stashPopLatest', { repository: true })
async stashPopLatest(repository: Repository): Promise<void> {
const stashes = await repository.getStashes();
if (stashes.length === 0) {
window.showInformationMessage(localize('no stashes', "There are no stashes in the repository."));
return;
}
await repository.popStash();
}
@command('git.stashApply', { repository: true })
async stashApply(repository: Repository): Promise<void> {
const placeHolder = localize('pick stash to apply', "Pick a stash to apply");
const stash = await this.pickStash(repository, placeHolder);
if (!stash) {
return;
}
await repository.applyStash(stash.index);
}
@command('git.stashApplyLatest', { repository: true })
async stashApplyLatest(repository: Repository): Promise<void> {
const stashes = await repository.getStashes();
if (stashes.length === 0) {
window.showInformationMessage(localize('no stashes', "There are no stashes in the repository."));
return;
}
await repository.applyStash();
}
@command('git.stashDrop', { repository: true })
async stashDrop(repository: Repository): Promise<void> {
const placeHolder = localize('pick stash to drop', "Pick a stash to drop");
const stash = await this.pickStash(repository, placeHolder);
if (!stash) {
return;
}
// request confirmation for the operation
const yes = localize('yes', "Yes");
const result = await window.showWarningMessage(
localize('sure drop', "Are you sure you want to drop the stash: {0}?", stash.description),
yes
);
if (result !== yes) {
return;
}
await repository.dropStash(stash.index);
}
@command('git.stashDropAll', { repository: true })
async stashDropAll(repository: Repository): Promise<void> {
const stashes = await repository.getStashes();
if (stashes.length === 0) {
window.showInformationMessage(localize('no stashes', "There are no stashes in the repository."));
return;
}
// request confirmation for the operation
const yes = localize('yes', "Yes");
const question = stashes.length === 1 ?
localize('drop one stash', "Are you sure you want to drop ALL stashes? There is 1 stash that will be subject to pruning, and MAY BE IMPOSSIBLE TO RECOVER.") :
localize('drop all stashes', "Are you sure you want to drop ALL stashes? There are {0} stashes that will be subject to pruning, and MAY BE IMPOSSIBLE TO RECOVER.", stashes.length);
const result = await window.showWarningMessage(question, yes);
if (result !== yes) {
return;
}
await repository.dropStash();
}
private async pickStash(repository: Repository, placeHolder: string): Promise<Stash | undefined> {
const stashes = await repository.getStashes();
if (stashes.length === 0) {
window.showInformationMessage(localize('no stashes', "There are no stashes in the repository."));
return;
}
const picks = stashes.map(stash => ({ label: `#${stash.index}: ${stash.description}`, description: '', details: '', stash }));
const result = await window.showQuickPick(picks, { placeHolder });
return result && result.stash;
}
@command('git.timeline.openDiff', { repository: false })
async timelineOpenDiff(item: TimelineItem, uri: Uri | undefined, _source: string) {
const cmd = this.resolveTimelineOpenDiffCommand(
item, uri,
{
preserveFocus: true,
preview: true,
viewColumn: ViewColumn.Active
},
);
if (cmd === undefined) {
return undefined;
}
return commands.executeCommand(cmd.command, ...(cmd.arguments ?? []));
}
resolveTimelineOpenDiffCommand(item: TimelineItem, uri: Uri | undefined, options?: TextDocumentShowOptions): Command | undefined {
if (uri === undefined || uri === null || !GitTimelineItem.is(item)) {
return undefined;
}
const basename = path.basename(uri.fsPath);
let title;
if ((item.previousRef === 'HEAD' || item.previousRef === '~') && item.ref === '') {
title = localize('git.title.workingTree', '{0} (Working Tree)', basename);
}
else if (item.previousRef === 'HEAD' && item.ref === '~') {
title = localize('git.title.index', '{0} (Index)', basename);
} else {
title = localize('git.title.diffRefs', '{0} ({1}) ↔ {0} ({2})', basename, item.shortPreviousRef, item.shortRef);
}
return {
command: 'vscode.diff',
title: localize('git.timeline.openDiffCommand', "Open Comparison"),
arguments: [toGitUri(uri, item.previousRef), item.ref === '' ? uri : toGitUri(uri, item.ref), title, options]
};
}
@command('git.timeline.copyCommitId', { repository: false })
async timelineCopyCommitId(item: TimelineItem, _uri: Uri | undefined, _source: string) {
if (!GitTimelineItem.is(item)) {
return;
}
env.clipboard.writeText(item.ref);
}
@command('git.timeline.copyCommitMessage', { repository: false })
async timelineCopyCommitMessage(item: TimelineItem, _uri: Uri | undefined, _source: string) {
if (!GitTimelineItem.is(item)) {
return;
}
env.clipboard.writeText(item.message);
}
private _selectedForCompare: { uri: Uri; item: GitTimelineItem } | undefined;
@command('git.timeline.selectForCompare', { repository: false })
async timelineSelectForCompare(item: TimelineItem, uri: Uri | undefined, _source: string) {
if (!GitTimelineItem.is(item) || !uri) {
return;
}
this._selectedForCompare = { uri, item };
await commands.executeCommand('setContext', 'git.timeline.selectedForCompare', true);
}
@command('git.timeline.compareWithSelected', { repository: false })
async timelineCompareWithSelected(item: TimelineItem, uri: Uri | undefined, _source: string) {
if (!GitTimelineItem.is(item) || !uri || !this._selectedForCompare || uri.toString() !== this._selectedForCompare.uri.toString()) {
return;
}
const { item: selected } = this._selectedForCompare;
const basename = path.basename(uri.fsPath);
let leftTitle;
if ((selected.previousRef === 'HEAD' || selected.previousRef === '~') && selected.ref === '') {
leftTitle = localize('git.title.workingTree', '{0} (Working Tree)', basename);
}
else if (selected.previousRef === 'HEAD' && selected.ref === '~') {
leftTitle = localize('git.title.index', '{0} (Index)', basename);
} else {
leftTitle = localize('git.title.ref', '{0} ({1})', basename, selected.shortRef);
}
let rightTitle;
if ((item.previousRef === 'HEAD' || item.previousRef === '~') && item.ref === '') {
rightTitle = localize('git.title.workingTree', '{0} (Working Tree)', basename);
}
else if (item.previousRef === 'HEAD' && item.ref === '~') {
rightTitle = localize('git.title.index', '{0} (Index)', basename);
} else {
rightTitle = localize('git.title.ref', '{0} ({1})', basename, item.shortRef);
}
const title = localize('git.title.diff', '{0} ↔ {1}', leftTitle, rightTitle);
await commands.executeCommand('vscode.diff', selected.ref === '' ? uri : toGitUri(uri, selected.ref), item.ref === '' ? uri : toGitUri(uri, item.ref), title);
}
@command('git.rebaseAbort', { repository: true })
async rebaseAbort(repository: Repository): Promise<void> {
if (repository.rebaseCommit) {
await repository.rebaseAbort();
} else {
await window.showInformationMessage(localize('no rebase', "No rebase in progress."));
}
}
@command('git.closeAllDiffEditors', { repository: true })
closeDiffEditors(repository: Repository): void {
const resources = [
...repository.indexGroup.resourceStates.map(r => r.resourceUri.fsPath),
...repository.workingTreeGroup.resourceStates.map(r => r.resourceUri.fsPath),
...repository.untrackedGroup.resourceStates.map(r => r.resourceUri.fsPath)
];
repository.closeDiffEditors(resources, resources, true);
}
private createCommand(id: string, key: string, method: Function, options: ScmCommandOptions): (...args: any[]) => any {
const result = (...args: any[]) => {
let result: Promise<any>;
if (!options.repository) {
result = Promise.resolve(method.apply(this, args));
} else {
// try to guess the repository based on the first argument
const repository = this.model.getRepository(args[0]);
let repositoryPromise: Promise<Repository | undefined>;
if (repository) {
repositoryPromise = Promise.resolve(repository);
} else if (this.model.repositories.length === 1) {
repositoryPromise = Promise.resolve(this.model.repositories[0]);
} else {
repositoryPromise = this.model.pickRepository();
}
result = repositoryPromise.then(repository => {
if (!repository) {
return Promise.resolve();
}
return Promise.resolve(method.apply(this, [repository, ...args.slice(1)]));
});
}
/* __GDPR__
"git.command" : {
"command" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryReporter.sendTelemetryEvent('git.command', { command: id });
return result.catch(async err => {
const options: MessageOptions = {
modal: true
};
let message: string;
let type: 'error' | 'warning' = 'error';
const choices = new Map<string, () => void>();
const openOutputChannelChoice = localize('open git log', "Open Git Log");
const outputChannel = this.outputChannel as OutputChannel;
choices.set(openOutputChannelChoice, () => outputChannel.show());
const showCommandOutputChoice = localize('show command output', "Show Command Output");
if (err.stderr) {
choices.set(showCommandOutputChoice, async () => {
const timestamp = new Date().getTime();
const uri = Uri.parse(`git-output:/git-error-${timestamp}`);
let command = 'git';
if (err.gitArgs) {
command = `${command} ${err.gitArgs.join(' ')}`;
} else if (err.gitCommand) {
command = `${command} ${err.gitCommand}`;
}
this.commandErrors.set(uri, `> ${command}\n${err.stderr}`);
try {
const doc = await workspace.openTextDocument(uri);
await window.showTextDocument(doc);
} finally {
this.commandErrors.delete(uri);
}
});
}
switch (err.gitErrorCode) {
case GitErrorCodes.DirtyWorkTree:
message = localize('clean repo', "Please clean your repository working tree before checkout.");
break;
case GitErrorCodes.PushRejected:
message = localize('cant push', "Can't push refs to remote. Try running 'Pull' first to integrate your changes.");
break;
case GitErrorCodes.Conflict:
message = localize('merge conflicts', "There are merge conflicts. Resolve them before committing.");
type = 'warning';
options.modal = false;
break;
case GitErrorCodes.StashConflict:
message = localize('stash merge conflicts', "There were merge conflicts while applying the stash.");
type = 'warning';
options.modal = false;
break;
case GitErrorCodes.AuthenticationFailed: {
const regex = /Authentication failed for '(.*)'/i;
const match = regex.exec(err.stderr || String(err));
message = match
? localize('auth failed specific', "Failed to authenticate to git remote:\n\n{0}", match[1])
: localize('auth failed', "Failed to authenticate to git remote.");
break;
}
case GitErrorCodes.NoUserNameConfigured:
case GitErrorCodes.NoUserEmailConfigured:
message = localize('missing user info', "Make sure you configure your 'user.name' and 'user.email' in git.");
choices.set(localize('learn more', "Learn More"), () => commands.executeCommand('vscode.open', Uri.parse('https://aka.ms/vscode-setup-git')));
break;
default: {
const hint = (err.stderr || err.message || String(err))
.replace(/^error: /mi, '')
.replace(/^> husky.*$/mi, '')
.split(/[\r\n]/)
.filter((line: string) => !!line)
[0];
message = hint
? localize('git error details', "Git: {0}", hint)
: localize('git error', "Git error");
break;
}
}
if (!message) {
console.error(err);
return;
}
const allChoices = Array.from(choices.keys());
const result = type === 'error'
? await window.showErrorMessage(message, options, ...allChoices)
: await window.showWarningMessage(message, options, ...allChoices);
if (result) {
const resultFn = choices.get(result);
if (resultFn) {
resultFn();
}
}
});
};
// patch this object, so people can call methods directly
(this as any)[key] = result;
return result;
}
private getSCMResource(uri?: Uri): Resource | undefined {
uri = uri ? uri : (window.activeTextEditor && window.activeTextEditor.document.uri);
this.outputChannel.appendLine(`${logTimestamp()} git.getSCMResource.uri ${uri && uri.toString()}`);
for (const r of this.model.repositories.map(r => r.root)) {
this.outputChannel.appendLine(`${logTimestamp()} repo root ${r}`);
}
if (!uri) {
return undefined;
}
if (isGitUri(uri)) {
const { path } = fromGitUri(uri);
uri = Uri.file(path);
}
if (uri.scheme === 'file') {
const uriString = uri.toString();
const repository = this.model.getRepository(uri);
if (!repository) {
return undefined;
}
return repository.workingTreeGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString)[0]
|| repository.indexGroup.resourceStates.filter(r => r.resourceUri.toString() === uriString)[0];
}
return undefined;
}
private runByRepository<T>(resource: Uri, fn: (repository: Repository, resource: Uri) => Promise<T>): Promise<T[]>;
private runByRepository<T>(resources: Uri[], fn: (repository: Repository, resources: Uri[]) => Promise<T>): Promise<T[]>;
private async runByRepository<T>(arg: Uri | Uri[], fn: (repository: Repository, resources: any) => Promise<T>): Promise<T[]> {
const resources = arg instanceof Uri ? [arg] : arg;
const isSingleResource = arg instanceof Uri;
const groups = resources.reduce((result, resource) => {
let repository = this.model.getRepository(resource);
if (!repository) {
console.warn('Could not find git repository for ', resource);
return result;
}
// Could it be a submodule?
if (pathEquals(resource.fsPath, repository.root)) {
repository = this.model.getRepositoryForSubmodule(resource) || repository;
}
const tuple = result.filter(p => p.repository === repository)[0];
if (tuple) {
tuple.resources.push(resource);
} else {
result.push({ repository, resources: [resource] });
}
return result;
}, [] as { repository: Repository; resources: Uri[] }[]);
const promises = groups
.map(({ repository, resources }) => fn(repository as Repository, isSingleResource ? resources[0] : resources));
return Promise.all(promises);
}
dispose(): void {
this.disposables.forEach(d => d.dispose());
}
}
|