File: src

package info (click to toggle)
simple-revision-control 1.41-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 364 kB
  • sloc: python: 2,675; sh: 1,810; makefile: 69
file content (3652 lines) | stat: -rwxr-xr-x 144,261 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
#!/usr/bin/env python3
"""
SRC - simple revision control.

Things to know before hacking this:

All the code outside the RCS and SCCS classes (and the RevisionMixin
helper) is intended to be generic to any file-oriented VCS.

SRC and RCS/SCCS have different goals in managing locks.  RCS/SCCS
wants to keep the workfile read-only except when it's explicitly
checked out, SRC wants to leave it writeable all the time.  Thus,
the checkin sequence is "release lock; check in; assert lock".  If
this seems confusing, it's because in RCS/SCCS terminology, locked is
writeable and unlocked is read-only.

Despite appearances, this code does not actually use RCS locks (and
sets locking to non-strict).  That just happens to be a handy way to
record which revision the user last checked out, which is significant
for future checkouts and for branching.

With sufficient cleverness it would be possible to go in a different
direction - leave the master unlocked at all times except during the
commit sequence, intervening with a chmod to turn off write
protection on the workfile when RCS/SCCS would normally turn it on.
I had this as a to-do for a long time but have abandoned the
concept; fighting RCS/SCCS's notion of when the workfile ought to be
write-locked seems too likely to lead to weird bugs in unexpected
situations.

In an ideal world, we'd get rid of A status. The SCCS back end doesn't
have it, because the only way to register new content is by "sccs add"
on an already existing file and that creates a new SCCS master with
the content checked in as the first commit.  RCS ci works that way as
well.  On the other hand, if you use rcs -i foo it creates a master foo,v
but does *not* stuff it with the content of any corresponding foo.  This
is what A status means.

Top of the list of things that people will bikeshed about is the
letter codes returned by 'src status'.  Different VCSes have
conflicting ideas about this.  The universal ones are 'A' = Added,
'M' = Modified, and '?' = Untracked.  Here's a table of the ones
in dispute.  Entries with '-' mean the VCS does not have a closely
corresponding status.

                  git     hg     svn      src
Unmodified        ' '     '='    ' '      '='
Renamed           'R'      -      -        -
Deleted           'D'     'R'    'D'       -
Copied            'C'      -      -        -
Ignored           '!'     'I'    'I'      'I'
Updated/unmerged  'U'      -      -        -
Missing            -      '!'    '!'      '!'
Locked             -       -     'L'      'L'

(hg used to use 'C' as the code for unmodified status.)

This is a bit oversimplified; it is meant not as a technical
comparison but rather to illustrate how bad the letter collisions are.
SRC follows the majority except for absolutely *not* using a space as
a status code; this makes the reports too hard to machine-parse.

"""
# SPDX-FileCopyrightText: Copyright Eric S. Raymond <esr@thyrsus.com>
# SPDX-License-Identifier: BSD-2-Clause

# This code runs under both Python 2 and Python 3.
# Preserve this property!

from __future__ import print_function

# Ugh. This is needed because pylint removed the no-self-use check in 2.14.
# This is the only way to prevent spurious pylint failures on earlier versions.
# pylint: disable=useless-option-value

# pylint: disable=fixme,line-too-long,too-many-lines,invalid-name,no-value-for-parameter,no-self-use,no-else-break,no-else-return,no-else-continue,missing-function-docstring,comparison-with-callable,consider-using-f-string,too-many-public-methods,too-many-nested-blocks,consider-using-with,too-many-locals.too-many-branches,unnecessary-lambda-assignment

# pylint: disable=multiple-imports
import sys, os, subprocess, time, calendar, stat, glob
import shutil, difflib, io, re, signal
import tempfile, email.utils
import struct, fcntl, termios, errno, inspect, pydoc

try:
    import curses
except ImportError:  # pragma: no cover
    pass

version = "1.41"

# General notes on Python 2/3 compatibility:
#
# SRC uses the following strategy to allow it to run on both Python 2
# and Python 3:
#
# * Use binary I/O to read/write data from/to files and subprocesses;
#   where the exact bytes are important (such as in checking for
#   modified files), use the binary data directly.
#
# * Use latin-1 encoding to transform binary data to/from Unicode when
#   necessary for operations where Python 3 expects Unicode; this will
#   ensure that bytes 0x80..0xff are passed through and not clobbered.
#   The polystr and polybytes functions are used to do this so that when
#   running on Python 2, the byte string data is used unchanged.
#
# * Construct custom stdin, stdout, and stderr streams when running
#   on Python 3 that force ASCII encoding, and wrap them around the
#   underlying binary buffers (in Python 2, the streams are binary and
#   are used unchanged); this ensures that the same transformation is
#   done on data from/to the standard streams, as is done on binary data
#   from/to files and subprocesses; the make_std_wrapper function does
#   this.  Without this change, 0x80..0xff written to stdout will be
#   garbled in unpredictable ways.

master_encoding = "latin-1"

if str is bytes:  # Python 2

    # pylint: disable=deprecated-module
    import cgi  # pragma: no cover (false negative)

    # pylint: disable=no-member
    htmlescape = cgi.escape  # pragma: no cover (false negative)

    polystr = str  # pragma: no cover (false negative)
    polybytes = bytes  # pragma: no cover (false negative)

    polyutf8str = str  # pragma: no cover (false negative)
    polyutf8bytes = bytes  # pragma: no cover (false negative)

    import pipes

    shellquote = pipes.quote

else:  # Python 3

    import html

    def htmlescape(s):
        # Python 2 compatibility.
        # Might be better to do this the other way around.
        return html.escape(s).replace("&#x27;", "'")

    def polystr(obj):
        "Polymorphic string factory function"
        # This is something of a hack: on Python 2, bytes is an alias
        # for str, so this ends up just giving a str back for all
        # inputs; but on Python 3, if fed a byte string, it decodes it
        # to Unicode using the specified master encoding, which should
        # be either 'ascii' if you're sure all data being handled will
        # be ASCII data, or 'latin-1' otherwise; this ensures that the
        # original bytes can be recovered by re-encoding.
        if isinstance(obj, str):
            return obj
        if not isinstance(obj, bytes):
            return str(obj)  # pragma: no cover (interactive only)
        return str(obj, encoding=master_encoding)

    def polybytes(s):
        "Polymorphic string encoding function"
        # This is the reverse of the above hack; on Python 2 it returns
        # all strings unchanged, but on Python 3 it encodes Unicode
        # strings back to bytes using the specified master encoding.
        if isinstance(s, bytes):
            return s
        # if not isinstance(s, str):
        #   return bytes(s)
        return bytes(s, encoding=master_encoding)

    def polystream(stream):
        "Standard input/output wrapper factory function"
        # This ensures that the encoding of standard output and standard
        # error on Python 3 matches the master encoding we use to turn
        # bytes to Unicode in polystr above.
        return io.TextIOWrapper(stream.buffer, encoding=master_encoding, newline="\n")

    def polyutf8str(obj):
        "Polymorphic string factory function, utf-8 variant"
        if isinstance(obj, str):
            return obj
        if not isinstance(obj, bytes):
            return str(obj)  # pragma: no cover (interactive only)
        return str(obj, encoding="utf-8")

    def polyutf8bytes(s):
        "Polymorphic string encoding function, utf-8 variant"
        if isinstance(s, bytes):
            return s
        return bytes(s, encoding="utf-8")

    sys.stdin = polystream(sys.stdin)
    sys.stdout = polystream(sys.stdout)
    sys.stderr = polystream(sys.stderr)

    import shlex

    shellquote = shlex.quote

# Note: Avoid using unbolded blue (poor luminance contrast with black
# terminal-emulator background) or bolded yellow (poor contrast with
# white background.)
RESET = BOLD = ""
CBLACK = CBLUE = CGREEN = CCYAN = CRED = CMAGENTA = CYELLOW = CWHITE = ""


def init_colors():  # pragma: no cover
    curses.setupterm()
    # pylint: disable=global-statement
    global RESET, BOLD
    RESET = curses.tigetstr("sgr0")
    if RESET is not None:
        RESET = polystr(RESET)
    else:
        RESET = ""
    BOLD = curses.tigetstr("bold")
    if BOLD is not None:
        BOLD = polystr(BOLD)
    else:
        BOLD = ""
    colors = {
        "setaf": [0, 4, 2, 6, 1, 5, 3, 7],  # ANSI colors
        "setf": [0, 1, 2, 3, 4, 5, 6, 7],
    }  # legacy colors
    for (k, v) in colors.items():
        x = curses.tigetstr(k)
        if x:
            for (i, c) in enumerate(
                ["black", "blue", "green", "cyan", "red", "magenta", "yellow", "white"]
            ):
                cap = curses.tparm(x, v[i])
                if cap is not None:
                    cap = polystr(cap)
                else:
                    cap = ""
                globals()["C" + c.upper()] = cap
            break


if "curses" in sys.modules and sys.stdout.isatty():  # pragma: no cover
    try:
        init_colors()
    except (curses.error, AttributeError):
        pass


def rfc3339(t):
    "RFC3339 string from Unix time."
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(t))


def announce(msg):
    sys.stdout.write("src: " + msg + "\n")


def croak(msg):
    sys.stdout.flush()
    sys.stderr.write("src: " + msg + "\n")
    raise SystemExit(1)


debug = 0
DEBUG_COMMANDS = 1  # Show commands as they are executed
DEBUG_TREESTATE = 2  # Dump directory state
DEBUG_SEQUENCE = 3  # Sequence debugging
DEBUG_PARSE = 4  # Debug logfile parse

quiet = False  # option -q: run more quietly
pseudotime = False  # option -T: artificial clock for regression testing

logstream = sys.stderr


def logit(msg):
    logstream.write(msg)


class popen_or_die:
    "Read or write from a subordinate process."

    def __init__(self, command, legend="", mode="r"):
        assert mode in ("r", "w", "rb", "wb")
        self.command = command
        self.legend = legend
        self.mode = mode
        # Pipe to the correct streams depending on the chosen mode
        self.stdin = subprocess.PIPE if mode == "w" else None
        self.stdout = subprocess.PIPE if mode == "r" else None
        self.stderr = subprocess.STDOUT if mode == "r" else None
        if self.legend:
            self.legend = " " + self.legend
        self.fp = None

    def __enter__(self):
        if debug >= DEBUG_COMMANDS:
            if self.mode == "r":
                logit(
                    "%s: reading from '%s'%s\n"
                    % (rfc3339(time.time()), self.command, self.legend)
                )
            else:
                logit(
                    "%s: writing to '%s'%s\n"
                    % (rfc3339(time.time()), self.command, self.legend)
                )
        try:
            # The I/O streams for the subprocess are always bytes; this
            # is what we want for some operations, but we will need
            # to decode to Unicode for others to work in Python 3, as
            # explained in the general notes.
            self.fp = subprocess.Popen(
                self.command,
                shell=True,
                stdin=self.stdin,
                stdout=self.stdout,
                stderr=self.stderr,
            )
            # The Python documentation recommends using communicate() to
            # avoid deadlocks, but this doesn't allow fine control over
            # reading the data; since we are not trying to both read
            # from and write to the same process, this should be OK.
            return self.fp.stdout if self.mode == "r" else self.fp.stdin
        except (OSError, IOError) as oe:  # pragma: no cover
            croak("execution of %s%s failed: %s" % (self.command, self.legend, oe))
        return None  # pragma: no cover

    def __exit__(self, extype, value, traceback_unused):
        if extype:  # pragma: no cover
            if debug > 0:
                raise extype(value)
            croak("fatal exception in popen_or_die.")
        if self.fp.stdout is not None:
            # This avoids a deadlock in wait() below if the OS pipe
            # buffer was filled because we didn't read all of the data
            # before exiting the context manager (shouldn't happen but
            # this makes sure).
            self.fp.stdout.read()
        self.fp.wait()
        if self.fp.returncode != 0:  # pragma: no cover
            croak("%s%s returned error." % (self.command, self.legend))
        return False


def screenwidth():  # pragma: no cover
    "Return the current width of the terminal window."
    default_width = 73

    if "COLUMNS" in os.environ:
        return int(os.environ["COLUMNS"])

    try:
        return struct.unpack(
            "HH", fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack("HH", 0, 0))
        )[1]
    except IOError as e:
        # ENOTTY isnormal for no terminal under Linux, but
        # Mac High Sierra can throw ENODEV.
        if e.errno in (errno.ENOTTY, errno.ENODEV):
            return default_width
        else:
            raise e


WIDTH = screenwidth() - 1


def modified(workfile, history=None):
    "Has the workfile been modified since it was checked out?"
    # Alas, we can't rely on modification times; it was tried, and
    # os.utime() is flaky from Python - sometimes has no effect.  Where
    # the bug is - Python, glibc, kernel - is unknown.  Even if we
    # could, it's nice to catch the case where an edit was undone.
    #
    # If no revisions, bail out
    if not backend.has_revisions(workfile):
        return False
    if history is None:
        history = History(workfile)
    with backend.manager(workfile) as xc:
        with backend.cat(xc.pathbase, history.current().native) as bstream:
            base_content = bstream.read()  # this data will be binary
            if os.path.getsize(workfile) != len(base_content):
                return True
            with open(xc.pathbase, "rb") as fp:
                workfile_content = fp.read()
            # This comparison uses the binary data for maximum accuracy
            return base_content != workfile_content


def relative(d=None):
    # Only used for debug/croak output
    return os.path.relpath(os.getcwd() if d is None else d, startdir)


def treedump(legend):
    # Visibly dump the state of the directory we're in
    # Used for debugging instrumentation only.
    logit(legend + "\n")
    logit(polystr(capture_or_die("ls -laR " + startdir)))


def rename(source, target, legend):
    if debug >= DEBUG_COMMANDS:
        logit("rename(%s, %a) %s\n" % (source, target, legend))
    os.rename(source, target)


def chdir(target, legend):
    if debug >= DEBUG_COMMANDS:
        logit("chdir(%a) %s\n" % (target, legend))
    os.chdir(target)


def caller(uplevel, legend=""):
    "Look up the stack for the callers of this function (for diagnostics)"
    if legend:
        legend = " " + legend
    return str(inspect.stack()[1 + uplevel][0].f_code.co_name) + legend


def do_or_die(dcmd, legend="", mute=True, missing=None, fatal=True):
    "Either execute a command or die."
    if legend:
        legend = " " + legend
    if debug == 0 and mute:
        muteme = " >/dev/null 2>&1"
    else:
        muteme = ""
    say = croak if fatal else announce
    dcmd = "(" + dcmd + ")" + muteme
    if debug >= DEBUG_TREESTATE:
        treedump("Before command " + dcmd)
    if debug >= DEBUG_COMMANDS:
        logit("at %s executing '%s'%s\n" % (relative(), dcmd, legend))
    try:
        retcode = subprocess.call(dcmd, shell=True)
        if retcode < 0:  # pragma: no cover
            croak("%s was terminated by signal %d." % (repr(dcmd), -retcode))
        elif retcode != 0:  # pragma: no cover
            errmsg = "%s returned %d." % (repr(dcmd), retcode)
            if retcode == 127:
                if missing is None:
                    missing = backend.__class__.__name__
                errmsg += "\nYou probably need to install %s." % missing
            say(errmsg)
    except (OSError, IOError) as e:  # pragma: no cover
        say("execution of %s%s failed: %s" % (repr(dcmd), legend, e))
    if debug >= DEBUG_TREESTATE:
        treedump("After command")
    return retcode


def capture_or_die(command):
    "Run a specified command, capturing the output."
    if debug >= DEBUG_COMMANDS:
        logit("%s: capturing %s\n" % (rfc3339(time.time()), command))
    try:
        # This will return binary data
        content = subprocess.check_output(command, shell=True)
    except (subprocess.CalledProcessError, OSError) as oe:  # pragma: no cover
        croak("execution of %s failed: %s" % (repr(command), oe))
    if debug >= DEBUG_COMMANDS:  # pragma: no cover
        logit(polystr(content))
    return content


# pylint: disable=too-many-instance-attributes
class HistoryEntry:
    "Capture the state of a native revision item in the log."

    def __init__(self, history):
        "Initialize a history entry."
        self.history = history
        self.revno = None
        self.native = None  # magic cookie only interpreted by back end
        self.headers = None
        self.log = ""
        self.date = None
        self.parent = None  # Another HistoryEntry
        self.child = None  # Another HistoryEntry
        self.branch = None

    def selected(self):
        "Is this the currently selected revision in the history list?"
        return self == self.history.current()

    def getdate(self, who):
        "Get the revision's commit date."
        if self.headers and not pseudotime:
            return self.headers.get(who + "-date") or self.date
        return self.date

    def unixtime(self, who):
        "Get the Unix timestamp of this revision."
        date = self.getdate(who)
        try:
            t = calendar.timegm(time.strptime(date, "%Y-%m-%dT%H:%M:%SZ"))
            offset = 0
            if self.headers and not pseudotime:
                offset = self.headers.get(who + "-date-offset") or 0
            return t, offset
        except (TypeError, ValueError):  # pragma: no cover
            croak("garbled date %s" % date)
        return None  # pragma: no cover

    def __str__(self):
        return "<%s = %s>" % (self.revno, self.native)


def registered(workfile):
    "Is this a workfile for a registered history?"
    return os.path.exists(backend.history(workfile))


# pylint: disable=too-many-instance-attributes
class History:
    "Encapsulate a revision list and some methods on it"

    def __init__(self, filename):
        "Intialize a history list."
        self.filename = filename
        self.revlist = []
        self.symbols = {}
        self.tipbranch = "trunk"
        self.lockrevs = []
        self.description = ""  # Not currently used
        if not registered(self.filename):
            croak("%s is not registered" % self.filename)
        self.by_revno_d = {}
        self.by_native_d = {}
        if debug >= DEBUG_COMMANDS:
            logit("parsing %s\n" % self.filename)
        try:
            d = os.path.dirname(filename)
            if d:
                chdir(d, "before getting history")
            backend.parse(self, os.path.basename(filename))
        finally:
            chdir(startdir, "after getting history")
        self.lift_headers()
        self.normalize_header_dates()

    def build_indices(self):
        for item in self.revlist:
            self.by_revno_d[item.revno] = item
            self.by_native_d[item.native] = item
        for item in self.revlist:
            item.parent = self.by_native_d.get(backend.pred(item.native))
            item.child = self.by_native_d.get(backend.succ(item.native))
        if debug >= DEBUG_PARSE:
            logit("Symbols: %s\n" % self.symbols)
            for item in self.revlist:
                logit("Item %s\n" % item)
            logit("By revision: %s\n" % self.by_revno_d.keys())
        if self.revlist:
            for (name, rev) in list(self.symbols.items()):
                if backend.isbranch(rev):
                    base = backend.branch_to_base(rev)
                    tip = backend.branch_to_tip(rev, self)
                    while True:
                        if base in self.by_native_d:
                            self.by_native_d[base].branch = name
                        if base == tip:
                            break
                        base = backend.succ(base)

    def lift_headers(self):
        valid = (
            "author",
            "author-date",
            "committer",
            "committer-date",
            "mark",
            "parents",
        )
        for item in self.revlist:
            headers = {}
            i = 0
            while True:
                n = item.log.find("\n", i)
                if n < 0:
                    break
                header = item.log[i:n].split(":", 1)
                if len(header) != 2:
                    break
                key = header[0].lower()
                if key in valid:
                    headers[key] = header[1].strip()
                    i = n + 1
                else:
                    break
            # eat blank line between headers and body
            while i < len(item.log) and item.log[i] == "\n":
                i += 1
            item.log = item.log[i:]
            if headers:
                item.headers = headers

    def normalize_header_dates(self):
        for item in self.revlist:
            if item.headers:
                for k in tuple(item.headers):
                    if k.endswith("-date"):
                        d = email.utils.parsedate_tz(item.headers[k])
                        if d:
                            u = email.utils.mktime_tz(d)
                            item.headers[k] = rfc3339(u)
                            item.headers[k + "-offset"] = d[9] if d[9] else 0

    def __len__(self):
        return len(self.revlist)

    def current(self):
        "Return the revision currently checked out."
        # Yes, this looks weird.  The idea is: Try to return the locked
        # revision.  If that blows up, try to return the tip revision of
        # the current branch.  If that blows up, return None.
        try:
            return self.by_native_d[self.lockrevs[0]]
        except (IndexError, KeyError):
            try:
                return self.by_native_d[
                    backend.branch_to_tip(self.symbols[self.tipbranch], self)
                ]
            except (IndexError, KeyError):  # pragma: no cover
                return None

    def current_branch(self, backwards=False):
        "Return a list of items that are descendants or ancestors of current."
        if debug >= DEBUG_SEQUENCE:
            logit(("current_branch(%s)\n" % self.current()))
        selection = []
        p = self.current()
        if p is not None:
            selection = [p]
            while True:
                if p.parent is None:
                    break
                else:
                    p = p.parent
                selection = [p] + selection
            s = self.current()
            while True:
                s = s.child
                if s is None:
                    break
                selection.append(s)
            if backwards:
                selection.reverse()
        return selection

    def tip(self, rev=None):
        "Return the tip revision of the branch of the given native revision."
        if rev is None:
            rev = self.current().native
        s = self.by_native_d[rev]
        while True:
            if s.child is None:
                return s
            else:
                s = s.child

    def native_to_revno(self, revision):
        "Map a native ID to a revno"
        item = self.by_native_d.get(revision)
        return item and item.revno

    def by_revno(self, revno):
        "Map a revno to a revision item."
        try:
            return self.by_revno_d[revno]
        except KeyError:  # pragma: no cover
            if revno == 0:
                # This case comes up if we try to select the tip
                # revision of a history without revisions.
                croak("{0} has no revisions".format(self.filename))
            else:
                croak("{0} has no revno {1}".format(self.filename, revno))
        return None  # pragma: no cover

    def revno_to_native(self, revno):
        "Map a revno to a native ID"
        return self.by_revno(revno).native


help_topics = {
    "topics": """
The following help topics are available:

intro       -- Basic concepts: commits, tags, branches. The form of commands.
revisions   -- How to specify ranges of commits to operate on.
commands    -- a summary of the commands.
init        -- the initialize command, which does nothing
commit      -- the commit command: how to commit changes to a file.
amend       -- the amend command: editing stored change comments.
checkout    -- the checkout command: retrieving historical versions of files.
cat         -- the cat command: dumping revisions to standard output.
status      -- the status command: more details and unusual status codes.
log         -- the log command: dump commit log information to standard output.
list        -- the list command: dump commit summaries to standard output.
diff        -- the diff command: dump revision differences to standard output.
fast-export -- the fast-export command: export history to other systems.
fast-import -- the fast-import command: import history from other systems.
srcify      -- the srcify command: change management from SCCS/RCS to src.
ignores     -- .srcignore files and their uses.

The 'help', 'rename', 'ls', 'move', 'copy', 'visualize', and 'version'
commands are completely described in the command summary.
""",
    "intro": """
SRC Introduction

    SRC (or src) is designed for version control on single-file
    projects. To start a single-file project, just create a file
    and commit it; this will create a subdirectory called .src
    if one does not already exist, and put your file history there.

    A SRC history is a sequence of commits numbered in strict time order
    starting from 1.  Each holds a modification to the file, a comment,
    and the date-time of the commit.

    The sequence also has a branch structure.  By default there is
    just one branch named 'trunk'.  You can start a new named branch
    at any commit.  Branches can later be renamed or deleted.  Because
    of branching, parent and child commits do not necessarily have
    consecutive numbers.

    Commits will always be added to the tip of the current branch.
    You can change the current branch by either checking out a revision
    that is on that branch, or using a 'src branch' command to
    explicitly change the current branch.

    You can assign tags (names) to point to commits.  They too can be
    renamed later or deleted.

    The general form of a SRC command is

        src verb [switches] [revision-spec] [files...]

    That is, a command verb is followed by optional switches, which are
    (sometimes) optionally followed by a range of commits to operate
    on, which is optionally followed by a list of files to operate on.
    Usually you will specify either a revision range or multiple files,
    but not both.

    The token '--' tells the command-line interpreter that subcommands,
    switches, and revision-specs are done - everything after it is a
    filename, even if it looks like a subcommand or revision number.

    A filename can be a path. In that case SRC will behave as though
    it were running in the lowest-level directory on the path and called
    with the path basename.

    If you do not specify any files, SRC will operate sequentially on
    each individual file in the current directory with a history.

    A good help topic to read after this one would be 'revisions'.
""",
    "revisions": """
SRC Revisions

    A 'revision' is a 1-origin integer, or a tag name designating an
    integer revision, or a branch name designating the tip revision of
    its branch, or '@' meaning the currently fetched revision.  Revision
    numbers always increase in commit-date order.

    A revision range is a single revision, or a pair of revisions 'M-N'
    (all revisions numerically from M to N) or 'M..N' (all revisions
    that are branch ancestors of N and branch successors of M).  If N is
    less than M, the range is generated as if N >= M then reversed.

    If SRC complains that your revision spec looks like a nonexistent
    filename, you can prefix it with '@' (this is always allowed).

    Some commands (help, commit, status, delete/rename commands for tags
    and branches, ls, move, copy, fast-import, release, srcify, version)
    don't take a revision spec at all and will abort if you give one.

    Some commands (amend, checkout, cat, tag and branch creation)
    optionally take a singleton revision spec.

    Some commands (log, list, diff, fast-export) accept a range or a
    singleton.

    Unless otherwise noted under individual commands, the default
    revision is the tip revision on the current branch.

    A good topic to read next would be 'commands'.
""",
    "commands": """
SRC Commands Summary

src help [command]
    Displays help for commands.

src init
    This command is unnecessary and does nothing. It is provided
    to reduce surprise for people who don't expect the first 
    commit into a file in a new directory to initialize a 
    repository there.

src commit [-|-m 'string'|-f 'file'|-e|-b branch] ['file'...]
    Enters a commit for specified files, separately to each one.
    A history is created for the file if it does not already exist.
    With '-', take comment text from stdin; with '-m' use the following
    string as the comment; with '-f' take from a file.  With '-e', edit
    even after '-', '-f' or '-m'. 'ci' is a synonym for 'commit'.  The -b
    option attaches the commit to the named branch, making it the default
    for future commits.

src amend [-|-m 'string'|-f 'file'|-e] ['revision'] ['file'...]
    Amends the stored comment for a specified revision, defaulting to
    the latest revision on the current branch.  Flags are as for commit.

src checkout ['revision'] ['file'...]
    Refresh the working copies of the file(s) from their history files.
    Sets the default branch for future checkins to that of whatever revision 
    you check out. 'co' is a synonym for 'checkout'.

src cat ['revision'] ['file'...]
    Send the specified revisions of the files to standard output.

src status [-a] [-q] ['file'...]
    '=' = unmodified,   'M' = modified, '!' = missing,
    '?' = not tracked,  'I' = ignored,  'A' = added,
    'L' = locked (recover with 'src checkout').
    Find more details under 'help status'. 'st' is a synonym for
    'status'.

src tag [list|-l|create|-c|delete|del|-d] ['name'] ['revision'] ['file'...]
    List tags, create tags, or delete tags.  Create/delete takes a
    singleton revision, defaulting to the current branch tip.  List
    defaults to all revisions.

src branch [list|-l|create|-c|delete|del|-d] ['name'] ['file'...]
    List, create, or delete branches.  When listing, the active branch
    is first in the list.  The default branch is 'trunk'.  Create/delete
    takes a singleton revision, defaulting to the current branch tip; on
    create that branch becomes the default for future commits. List defaults
    to all revisions, including 0 (the trunk root phantom revision).

src rename ['tag'|'branch'] ['oldname'] ['newname']  ['file'...]
    Rename a tag or branch.  Refuses to step on an existing symbol or
    rename a nonexistent one. 'rn' is a synonym for 'rename'.

src list [(-<n>|-l <n>)] [-f 'fmt'] ['revision-range'] ['file'...]
    Sends summary information about the specified commits to standard
    output.  The summary line tagged with '*' is the state that the file
    would return to on checkout without a revision-spec.  See 'help
    list' for information about custom formats.  Use '-<n>' or '-l <n>',
    where <n> is a number, to limit the listing length.  Default range is
    the current branch, reversed.

src log [-v] [(-<n>|-l <n>)] [(-p|-u|-c) [-b|-w]] ['revision-range'] ['file'...]
    Sends log information about the specified commits to standard
    output.  Use '-<n>' or '-l <n>', where <n> is a number, to limit the
    listing length.  Default range is the current branch, reversed.
    Use '--patch', '-p' or '-u' to also send a unified format diff
    listing to standard output for each revision against its immediate
    ancestor revision; '-c' emits a context diff instead. When generating
    a diff, '-b' ignores changes in the amount of whitespace, and '-w'
    ignores all whitespace.  Histories imported via 'fast-import' (when
    not using its '-p' option) have RFC-822-style headers inserted into
    the log comment to preserve metadata not otherwise representable in
    SRC, such as distinct author and committer identifications and
    dates.  These headers are normally suppressed by 'log', however,
    '-v' shows a summarized view of important headers; '-v -v' shows
    all headers as-is.

src diff [(-u|-c) [-b|-w]] ['revision-range'] ['file'...]
    Sends a diff listing to standard output.  With no revision spec,
    diffs the working copy against the last version checked in.  With
    one revno, diffs the working copy against that stored revision; with
    a range, diff between the beginning and end of the range. 'di' is a
    synonym for 'diff'.

src ls
    List all registered files.

src visualize
    Emit a DOT visualization of repository structures.  To use this,
    install the graphviz package and pipe the output to something like
    'dot -Tpng | display -'. 'vis' is a synonym for 'visualize'.

src move 'old' 'new'
    Rename a workfile and its history.  Refuses to step on existing
    workfiles or histories. 'mv' is a synonym for 'move'.

src copy 'old' 'new'
    Copy a workfile and its history.  Refuses to step on existing files
    or histories. 'cp' is a synonym for 'copy'.

src fast-export ['revision-range'] ['file'...]
    Export one or more projects to standard output as a Git fast-import
    stream.  For a history originally imported from elsewhere, author
    and committer identification is gleaned from the RFC-822-style
    headers inserted into the commit comment by 'fast-import' (if its
    '-p' option was not used).  Otherwise, this information is copied
    from your Git configuration.  The default range is all commits.

src fast-import [-p] ['file'...]
    Parse a git-fast-import stream from standard input.  The
    modifications for each individual file become separate SRC
    histories.  Mark, committer and author data, and mark cross-
    references to parent commits, are preserved in RFC-822-style headers
    on log comments unless the '-p' (plain) option is given, in which
    case this metadata is discarded.  Give arguments to restrict the
    files imported.

src release ['file'...]
    Release locks on files.  This is never necessary in a normal
    workflow, which will be repeated edit-commit cycles, but it may be
    handy if you have to interoperate with other tools that expect RCS
    masters to be in their normal (unlocked/unwriteable) state.

src srcify
    Move a directory from being RCS- or SCCS-managed to being SRC-managed.
    That is: if the current directory contains an RCS directory, rename it
    to .src (but leave any SCCS directory in place).  Then check out all
    masters for editing that are not already checked out.

src version
    Report the versions of SRC, the underlying Python, and the back end.

The omission of 'src remove' is a deliberate speed bump.
""",
    "status": """
src status [-a] [-q] ['file'...]

    The status command shows you the version-control status of files.
    It is designed to be useful for both humans and software front ends
    such as Emacs VC mode.

    The status codes, in roughly most common to rarest, are:

    = - Unmodified.  File is the same as the latest stored revision.
    M - Modified.  File has been changed since the latest stored revision.
    ? - Not tracked.  SRC does not keep a history for this file.
    I - ignored.  This file matches the patterns in '.srcignore'.
    ! - Missing.  There is a history for this file but the workfile is missing.
    A - The file has been registered into SRC but has no commits.
    L - The file is locked/writable.

    Modification status is by content rather than the filesystem's
    last-modified date.  Thus, if you make changes to a work file in
    your editor, then undo them, the file's status returns to '='.

    You can usually recover a file from 'A', 'L', and '!' status with
    'src checkout'.  'A' and 'L' statuses should only occur if you have
    used RCS directly on a file, or if you have called 'src commit' with
    the deliberately undocumented '-a' option meant for Emacs VC's use.

    If you give 'src status' no filename arguments, it surveys all files
    in the current directory but untracked and ignored files are not
    listed.  If you give it filename arguments, status is listed for all
    of them.

    The '-a' option forces status listing of all files.  This differs
    from 'src status *' because the latter will not see dotfiles and
    thus not list the status of them.  The -q option suppressed listing
    of untracked files.
""",
    "init": """
src init

    This command is unnecessary and does nothing. It is provided by
    analogy with the init commands in cvs, git, hg and bzr/brz, as a
    placeholder in scripting and to reduce surprise for people who
    don't expect the first commit into a file in a new directory to
    initialize a repository there.
""",
    "commit": """
src commit [-|-m 'string'|-f 'file'| -e] [-b branch] ['file'...]

    The commit command is how you add revisions to your file history.
    It always adds the contents of the workfile as a revision to the tip
    of the current branch. The -b option puts the commit on a new branch.

    You also use commit on files that have not been registered to start
    an SRC history for them.

    When you commit, you must specify a change comment to go with the
    revision.  There are several ways to do this.

    The '-m' option to the command takes the following string argument
    as the comment.  The '-' option takes the comment text from standard
    input.  The '-f' option takes the comment from a named file.

    If you use none of these, or if you use one of them and the '-e'
    option, SRC will start an editor in which you can compose the
    comment.  Text specified via '-m', '-f', or '-' becomes the initial
    contents of the comment.

    SRC respects the EDITOR variable and calls it on a temporary file to
    create your comment.  The file will have a footer including its name
    and revision which will be discarded when you finish editing.

    If you leave the comment empty (except for the generated footer)
    or consisting only of whitespace, the commit will be aborted.  The
    commit will also be aborted if your editor returns a failure status.

    If you commit to multiple files at once, separate changes will be
    registered for each one, and you may get a separate edit session for
    each (if you have not set the comment text with options, or have
    forced editing with '-e').  This is a major difference from other
    VCSes, which are usually designed to create changesets common to
    multiple files.

    'ci' is a synonym for 'commit'.
""",
    "amend": """
src amend [-|-m 'string'|-f 'file'| -e] ['revision'] ['file'...]

    Use this command to amend (modify) the change comment in a saved
    revision.  The commit date is not changed.

    Takes a singleton revision number, tag, or branch, defaulting to the
    latest revision on the current branch.

    The edit flags and EDITOR variable are interpreted are as for
    commit.  The only difference is that existing change comment is
    appended to any text you specify with switches as the initial
    comment passed to your editor.

    'am' is a synonym for 'amend'
""",
    "checkout": """
src checkout ['revision'] ['file'...]

    Refresh the working copies of the file(s) from their history files.

    Takes a single revision number, tag, or branch name.  The default if
    you give none is the tip revision of the current branch.

    This command is how you discard the contents of a modified workfile.

    You can also use it to revert the workfile to match a previous
    stored revision.  Doing so may, as a side effect, change your
    current branch.

    'co' is a synonym for 'checkout'.
""",
    "cat": """
src cat ['revision'] ['file'...]

    Send the specified revision of each file to standard output.  This
    is not normally very useful with more than one file argument, but
    SRC does not prevent that.

    Takes a single revision number, tag, or branch name.  The default if
    you give none is the tip revision of the current branch.

    This command is mainly intended for use in scripts.
""",
    "tag": """
src tag [list|-l|create|-c|delete|del|-d] ['name'] ['revision'] ['file'...]

    List tags (with '-l'), create tags (with '-c'), or delete tags (with
    '-d').

    Takes at most a singleton revision; the default is the current
    branch tip.

    Tag creation and deletion require a following name argument.  Tag
    creation will not step on an existing tag name, and a nonexistent
    branch cannot be deleted.
""",
    "branch": """
src branch [list|-l|create|-c|delete|del|-d] ['name'] ['file'...]

    List branches (with '-l'), create branches (with '-c'), or delete
    branches (with '-d').

    In the list produced by '-l', the active branch is first in the list.

    Branch creation and deletion require a following name argument.
    Branch creation will not step on an existing branch name, and a
    nonexistent branch cannot be deleted.
""",
    "log": """
src log [-v] [(-<n>|-l <n>)] [(-p|-u|-c) [-b|-w]] ['revision-range'] ['file'...]

    Sends log information about the specified commits of each file to
    standard output.  The log information includes the revision number,
    the date, and the log comment.

    With no revision, dumps a log of the entire current branch.

    The '--patch', '-p' or '-u' option additionally sends a unified
    format diff listing to standard output for each revision against its
    immediate ancestor revision; '-c' emits a context diff instead. When
    generating a diff, '-b' ignores changes in the amount of whitespace,
    and '-w' ignores all whitespace.

    The '-<n>' or '-l <n>' option, where <n> is a number, can be used to
    limit the listing length.

    Histories imported via 'fast-import' (when not using its '-p' option)
    have RFC-822-style headers inserted into the log comment to preserve
    metadata not otherwise representable in SRC, such as distinct author
    and committer identifications and dates.  These headers are normally
    suppressed by 'log', however, '-v' shows a summarized view of
    important headers; '-v -v' shows all headers as-is.
""",
    "list": """
src list [(-<n>|-l <n>)] [-f 'fmt'] ['revision-range'] ['file'...]

    Sends summary information about the specified commits of each file
    to standard output.  The summary information includes the revision
    number, the date, and the first line of the log comment.

    This command is provided assuming you will use the good practice of
    beginning each commit with a self-contained summary line.

    With no revision, dumps a log of the entire current branch.

    The '-f' option allows you to set a custom format string.  Available
    substitutions are:

    {0} - the file name
    {1} - the revision number
    {2} - the mark '*' if this is the currently checked out revision, else '-'.
    {3} - the date in RFC3339 format
    {4} - the summary line

    The '-<n>' or '-l <n>' option, where <n> is a number, can be used to
    limit the listing length.

    'li' is a synonym for 'list'.
""",
    "diff": """
src diff [(-u|-c) [-b|-w]] ['revision-range'] ['file'...]

    Sends a diff listing to standard output.

    With no revision spec, diffs the working copy against the last
    version checked in.  With one revno, diffs the working copy against
    that stored revision; with a range, diff between the beginning and
    end of the range.

    The actual difference generation is done with diff(1).  The default
    diff format is '-u' (unified), but if you specify a '-c' option
    after the verb a context diff will be emitted. '-b' ignores changes
    in the amount of whitespace, and '-w' ignores all whitespace.

    'di' is a synonym for 'diff'.
""",
    "fast-export": """
src fast-export ['revision-range'] ['file'...]

    Export one or more projects to standard output as a git fast-import
    stream.  This can be consumed by 'git fast-import' to create a Git
    repository containing the project history.

    It is possible (though probably not very useful) to fast-export a
    limited range of commits, producing an incremental dump.  In this
    case branch joins are done with the magic ^0 suffix.

    Fast-exporting multiple files produces a single stream with a joint
    history.

    If there is a .srcignore file, it is renamed to .gitignore in the
    stream.

    For a history originally imported from elsewhere, author and
    committer identification is gleaned from the RFC-822-style headers
    inserted into the commit comment by 'fast-import' (if its '-p'
    option was not used).  Otherwise, this information is copied from
    your Git configuration.

    The default range is all commits.
""",
    "srcify": """
src srcify

    Change the current directory with an RCS or SCCS subdirectory to be
    managed by src instead. Any RCS directory is renamed .src. Then all
    files with histories are checked out for editing.
""",
    "fast-import": """
src fast-import [-p] ['file'...]

    Parse a git-fast-import stream from standard input.  The
    modifications for each individual file become separate SRC
    histories.  Give arguments to restrict the files imported.

    The import is actually done with the rcs-fast-import(1) tool, which
    must be on your $PATH for this command to work.

    Some gitspace metadata cannot be represented in the SRC/RCS
    model of version control.  Mark, committer and author data, and
    mark cross-references to parent commits.  These are preserved in
    RFC-822-style headers on log comments unless the '-p' (plain) option
    is given, in which case this metadata is discarded.
""",
    "ignores": """
Making SRC Ignore Certain Files

    You can have a file named '.srcignore' containing the names of files
    that SRC should ignore, or more commonly patterns describing files
    to ignore.

    When SRC is told to ignore a file, it won't show up in 'src status'
    listings unless the '-a' (all) flag is used or you give it as an
    explicit argument.  It will also be ignored when commands that
    expect a list of registered files see it (which could easily happen
    when you use shell wildcards in SRC commands).

    Other version-control systems have these too.  The classic example
    of how to do this is using the pattern '*.o' to ignore C object
    files.  But if you need to do that, you should probably be using a
    multi-file VCS with changesets, not this one.

    Patterns that might be useful with single-file projects include
    '*~' to ignore editor backup files, or '*.html' if you're writing
    documents that render to HTML but aren't sourced in it.

    The repo subdirectory - normally '.src' - is always ignored, but
    '.srcignore' itself is not automatically ignored.

    SRC's pattern syntax is that of Unix glob(3), with initial '!'
    treated as a negation operator.  This is forward-compatible to Git's
    ignore syntax and is a superset of Unix glob(3) syntax.

    *   matches any string of characters.
    ?   matches any single character.
    []  brackets a character class; it matches any character in the
        class.  So, for example, [0123456789] would match any decimal
        digit.
    [-] can be used to match ranges, e.g. [a-z] matches any lowercase letter.
    [^] brackets a negated character class; [^0123456789] would match
        any character not a decimal digit.
    [!] also brackets a negated character class
""",
}


def help_method(*args):
    "Summarize src commands, or (with argument) show help for a single command."
    if not args:
        sys.stdout.write(help_topics["topics"])
    for arg in args:
        if arg in args:
            if arg in help_topics:
                if sys.stdout.isatty():
                    pydoc.pager(help_topics[arg])
                else:
                    sys.stdout.write(help_topics[arg])
            else:
                croak(
                    "%s is not a known help topic.\n%s" % (arg, help_topics["topics"])
                )


def parse_as_revspec(token):
    "Does this look like something that should be parsed as a revision spec?"
    if "/" in token:
        return False
    elif ".." in token:
        return True
    elif token.count("-") == 1 and "." not in token:
        return True
    elif token.isdigit():
        return True
    elif token.startswith("@"):  # Escape clause for tags that look like files
        return True
    else:
        return False


ignorable = None


def ignore(filename):
    "Should the specified file be ignored?"
    # pylint: disable=global-statement
    global ignorable
    if ignorable is None:
        ignorable = set()
        if os.path.exists(".srcignore"):
            with open(".srcignore", "rb") as fp:
                for line in fp:
                    line = polystr(line)
                    # Hack to make src a bit more compatible with
                    # other systems and POSIX glob(3).
                    line = line.replace("[^", "[!")
                    if line.startswith("#") or not line.strip():
                        continue
                    elif line.startswith("!"):
                        ignorable -= set(glob.glob(line[1:].strip()))
                    else:
                        ignorable |= set(glob.glob(line.strip()))
    return (filename == repodir) or (filename in ignorable)


# pycheck: disable=too-many-branches
class CommandContext:
    "Consume a revision specification or range from an argument list"
    # pylint: disable=too-many-arguments,too-many-branches,too-many-statements
    def __init__(
        self, cmd, args, require_empty=False, default_to=None, parse_revspec=True
    ):
        self.start = self.end = None
        self.seq = None
        self.branchwise = None
        if isinstance(args, tuple):
            args = list(args)
        self.args = list(args)
        self.default_to = default_to
        self.lo = self.start
        self.hi = self.end
        revspec = None
        if self.args:
            if self.args[0] == "--":
                parse_revspec = False
                self.args.pop(0)
            elif parse_revspec and parse_as_revspec(args[0]):
                revspec = self.args.pop(0)
                if revspec.startswith("@"):
                    revspec = revspec[1:]
                try:
                    if "-" in revspec or ".." in revspec:
                        self.branchwise = ".." in revspec
                        try:
                            (self.start, self.end) = revspec.split("-")
                        except ValueError:
                            try:
                                (self.start, self.end) = revspec.split("..")
                            except ValueError:  # pragma: no cover
                                croak("internal error - argument parser is confused")
                        try:
                            self.start = int(self.start)
                        except ValueError:  # pragma: no cover
                            pass
                        try:
                            self.end = int(self.end)
                        except ValueError:  # pragma: no cover
                            pass
                    else:
                        try:
                            self.end = self.start = int(revspec)
                        except ValueError:
                            self.end = self.start = revspec
                except ValueError:  # pragma: no cover
                    croak("malformed revision spec: %s" % revspec)
        if require_empty and not self.is_empty():
            croak("%s doesn't take a revision spec" % cmd)
        if not self.args:
            try:
                masters = [fn for fn in os.listdir(repodir) if backend.is_history(fn)]
                masters.sort()
            except OSError:
                croak("repo directory %s does not exist" % repodir)
            if masters:
                self.args += [backend.workfile(master) for master in masters]
            else:
                croak("%s requires at least one file argument" % cmd)
        if multidir and not quiet:
            announce("%s is selected." % repodir)

    def is_empty(self):
        "Is the spec empty?"
        return self.start is None

    # def is_singleton(self):
    #    "Is the spec a singleton?"
    #    return self.start is not None and self.start == self.end

    def is_range(self):
        "Is the spec a range?"
        return self.start is not None and self.start != self.end

    def select_all(self, metadata):
        "Set the range to all revisions."
        self.lo = 1
        self.hi = len(metadata)
        self.seq = [metadata.by_revno(i) for i in range(self.lo, self.hi + 1)]

    def select_tip(self, metadata):
        "Set the range to the tip revision."
        self.lo = len(metadata)
        self.hi = None
        self.seq = [metadata.by_revno(self.lo)]

    def __contains__(self, i):
        "Does the spec contain the given revno?"
        if self.seq is None:
            croak(
                "revision spec hasn't been resolved"
            )  # pragma: no cover (should never happen)
        return i in self.seq

    # pylint: disable=too-many-branches
    def resolve(self, metadata):
        "Resolve a revision spec that may contain tags into revnos."
        if debug >= DEBUG_SEQUENCE:
            logit("Entering resolve with start=%s, end=%s\n" % (self.start, self.end))
        if self.is_empty():
            if debug >= DEBUG_SEQUENCE:
                logit("Revision spec is empty\n")
            if self.default_to == "branch":
                self.seq = metadata.current_branch(backwards=False)
            elif self.default_to == "branch_reversed":
                self.seq = metadata.current_branch(backwards=True)
            else:
                self.seq = []
            if debug >= DEBUG_SEQUENCE:
                logit(
                    "Empty revision spec returns %s\n" % ([x.revno for x in self.seq],)
                )
            return self.seq

        def subresolve(token):
            part = token
            if isinstance(part, int):
                return part
            if token == "":  # User specified @
                current = metadata.current()
                if current is None:
                    croak(
                        "in {0}, no current revision".format(metadata.filename)
                    )  # pragma: no cover (should never happen)
                return current.revno
            if part not in metadata.symbols:
                croak(
                    "in {0}, can't resolve symbol {1}".format(metadata.filename, token)
                )
            else:
                part = metadata.symbols[part]
            if backend.isbranch(part):
                part = backend.branch_to_tip(part, metadata)
            return metadata.native_to_revno(part)

        self.lo = subresolve(self.start)
        self.hi = subresolve(self.end)
        if debug >= DEBUG_SEQUENCE:
            logit("Subresolved range: lo=%s, hi=%s\n" % (self.lo, self.hi))
        # pylint: disable=superfluous-parens
        mreversed = self.lo > self.hi
        if mreversed:
            swapme = self.hi
            self.hi = self.lo
            self.lo = swapme
        if self.hi > len(metadata):
            croak("{0} has no {1} revision".format(metadata.filename, self.hi))
        if not self.branchwise:
            self.seq = [metadata.by_revno(i) for i in range(self.lo, self.hi + 1)]
        else:
            self.seq = []
            e = metadata.by_revno(self.hi)
            while True:
                self.seq.append(e)
                if e.revno == self.lo:
                    break
                if e.parent is None:
                    croak("%s is not an ancestor of %s" % (self.lo, self.hi))
                else:
                    e = e.parent
        if debug >= DEBUG_SEQUENCE:
            logit(
                "selection: %s, branchwise is %s\n"
                % ([x.revno for x in self.seq], "on" if self.branchwise else "off")
            )
            for item in metadata.revlist:
                logit("%s\t%s\t%s\n" % (item.revno, item.date, item.native))
        # Because in the branchwise case the sequence is generated in reverse
        if self.branchwise:
            self.seq.reverse()
        # Range might have been reversed
        if mreversed:
            self.seq.reverse()
        return self.seq


class CommentContext:
    "Encapsulate comment part of a revision."
    COMMENT_CUTLINE = """\
.............................................................................
"""
    COMMENT_EXPLANATION = """\
The cut line and things below it will not become part of the comment text.
"""

    def __init__(self, legend, args):
        "Attempt to collect a comment from command line args."
        self.leader = ""
        self.comment = None
        self.force_edit = False
        self.parse_revspec = True
        if args:
            if args[0] == "--":
                self.parse_revspec = False
                args.pop(0)
            elif args[0] == "-":
                self.leader = sys.stdin.read()
                args.pop(0)
            elif args[0] == "-e":
                self.force_edit = True
            elif args[0] == "-m":
                args.pop(0)
                try:
                    self.leader = args[0] + "\n"
                    args.pop(0)
                except IndexError:  # pragma: no cover
                    croak("%s -m requires a following string" % legend)
            elif args[0].startswith("-m"):
                self.leader = args[2:] + "\n"
                args.pop(0)
            elif args[0] == "-f":
                args.pop(0)
                try:
                    # Read filesystem data as binary for robustness, but
                    # decode to Unicode for internal use
                    with open(args[0], "rb") as fp:
                        self.leader = polystr(fp.read())
                    args.pop(0)
                except IndexError:  # pragma: no cover
                    croak("%s -f requires a following filename argument" % legend)
                except OSError:  # pragma: no cover
                    croak("couldn't open %s." % args[1])
            elif args[0].startswith("-"):
                croak("unexpected %s option" % args[0])  # pragma: no cover

    def edit(self, content="", trailer="", diff=None):
        "Interactively edit a comment if required, then prepare for handoff."
        if self.leader and not self.force_edit:
            self.comment = self.leader
        else:
            orig_content = content
            if self.leader:
                content = self.leader + content
            if trailer or diff:
                content += (
                    "\n"
                    + CommentContext.COMMENT_CUTLINE
                    + CommentContext.COMMENT_EXPLANATION
                    + trailer
                )
            editor = os.getenv("EDITOR")
            if editor is None:  # pragma: no cover
                for editor in (
                    "emacsclient",
                    "emacs",
                    "vim",
                    "vi",
                    "nano",
                    "joe",
                    "jed",
                ):
                    try:
                        if shutil.which(editor):
                            break
                    except AttributeError:
                        croak(
                            "fallback editor discovery is not available under Python 2."
                        )
                else:
                    croak("can't find a text editor to launch")
            try:
                # Using latin-1 for passthrough isn't sufficient here.
                # The problem is that the trailer may contain real Unicode
                # characters rather than ASCII - this will happen if you
                # commit on a filename that Python decodes into Unicode.
                # Since we'll editing a comment and don't have to worry about
                # clobbering file content, temporatily enter UTF-8 land.
                with tempfile.NamedTemporaryFile(
                    prefix="src", suffix="tmp", delete=False
                ) as fp:
                    commentfile = fp.name
                    fp.write(polyutf8bytes(content))
                    if diff:
                        fp.write(b"\nChanges to be committed:\n")
                        for s in diff:
                            fp.write(polyutf8bytes(s))
                            fp.write(b"\n")
                do_or_die(editor + " " + commentfile, "edit", mute=False)
                with open(commentfile, "rb") as fp:
                    self.comment = polyutf8str(fp.read())
                    os.unlink(commentfile)
            except IOError:  # pragma: no cover
                croak("edit aborted.")
            where = self.comment.find(CommentContext.COMMENT_CUTLINE)
            if where != -1:
                self.comment = self.comment[:where]
            self.comment = self.comment.strip()
            if self.comment == orig_content.strip() or not self.comment:
                return False
            # Can be removed if we ever parse RCS/SCCS files directly
            for badnews in backend.delimiters:
                if badnews in self.comment:
                    croak("malformed comment")  # pragma: no cover
        if not self.comment.endswith("\n"):
            self.comment += "\n"
        return True

    def content(self):
        "Return the edited comment."
        return self.comment


# pylint: disable=too-many-arguments
def external_diff(file0, s0, file1, s1, unified=True, ignore_ws=None):
    "Compute diff using external program."

    def writetmp(s):
        with tempfile.NamedTemporaryFile(
            prefix="src", suffix="tmp", delete=False
        ) as fp:
            fp.write(polybytes(s))
            return fp.name

    if unified:
        opts, tok0, tok1 = "-u", "-", "+"
    else:
        opts, tok0, tok1 = "-c", "*", "-"
    if ignore_ws:
        opts += " " + ignore_ws
    tmp0 = writetmp(s0)
    tmp1 = writetmp(s1)
    with popen_or_die(
        'diff %s "%s" "%s" || :' % (opts, tmp0, tmp1), "external diff"
    ) as fp:
        diff = polystr(fp.read())
    os.unlink(tmp0)
    os.unlink(tmp1)
    diff = re.sub(r"(?m)^([%s]{3} ).+$" % tok0, r"\1" + file0, diff, 1)
    diff = re.sub(r"(?m)^([%s]{3} ).+$" % tok1, r"\1" + file1, diff, 1)
    return diff.split("\n")


def compute_diff(metadata, lo, hi, differ, ignore_ws=None):
    """Compute diff between two revs of a file.
    If 'lo' is None, then this is a "creation event" in which 'hi'
    materializes fully formed from nothing.
    If 'hi' is None, then diff 'lo' against the working file.
    File must already have been "lifted"."""
    name = metadata.filename
    if lo is None:
        file0 = "/dev/null"
        old_content = ""
    else:
        file0 = name + " (r" + str(lo) + ")"
        with backend.cat(name, metadata.revno_to_native(lo)) as fp:
            old_content = fp.read()  # this data will be binary
    if hi is None:
        file1 = name + " (workfile)"
        with open(name, "rb") as fp:
            new_content = fp.read()
    else:
        file1 = name + " (r" + str(hi) + ")"
        with backend.cat(name, metadata.revno_to_native(hi)) as fp:
            new_content = fp.read()  # this data will be binary
    # Don't list identical files (comparison uses binary data
    # for maximum accuracy).
    if old_content == new_content:
        return ()
    if ignore_ws:
        return external_diff(
            file0,
            old_content,
            file1,
            new_content,
            differ == difflib.unified_diff,
            ignore_ws,
        )
    lines0 = polystr(old_content).split("\n")
    lines1 = polystr(new_content).split("\n")
    return differ(lines0, lines1, fromfile=file0, tofile=file1, lineterm="")


def colorize_unified(s):
    for x in colorize_unified.colors:
        if s.startswith(x[0]):
            return x[1] + s + RESET
    return s


colorize_unified.colors = (
    ("+++ ", BOLD),
    ("--- ", BOLD),
    ("@@ ", CCYAN),
    ("+", CGREEN),
    ("-", CRED),
)


def print_diff(metadata, lo, hi, differ, ignore_ws=None):
    "Dump diff between revisions to standard output."
    if differ == difflib.unified_diff:
        colorizer = colorize_unified
    else:
        colorizer = lambda x: x
    with backend.manager(metadata.filename):
        for line in compute_diff(metadata, lo, hi, differ, ignore_ws):
            sys.stdout.write(colorizer(line) + "\n")


def exec_copy(source, target):
    if os.path.exists(target):
        oldtargetmode = newtargetmode = os.stat(target).st_mode
        sourcemode = os.stat(source).st_mode
        for bitmask in (stat.S_IXUSR, stat.S_IXGRP, stat.S_IXOTH):
            if bitmask & sourcemode:
                newtargetmode |= bitmask
            else:
                newtargetmode &= ~bitmask
        if newtargetmode != oldtargetmode:
            os.chmod(target, newtargetmode)


def checkout_method(*args):
    "Refresh the working copy from the history file."
    ctx = CommandContext("checkout", args)
    if ctx.is_range():
        croak("checkout needs an empty or singleton revision spec")
    for arg in ctx.args:
        metadata = History(arg)
        ctx.resolve(metadata)
        revision = None  # pacify pylint
        if ctx.is_empty():
            ctx.select_tip(metadata)
            revision = ctx.seq[0].native
        elif ctx.lo > len(metadata):
            croak("%s has only %d revisions" % (arg, len(metadata)))
        else:
            revision = metadata.revno_to_native(ctx.lo)
        with backend.manager(arg) as xc:
            backend.checkout(xc.pathbase, revision)
            backend.set_branch(backend.revision_to_branch(revision), xc.pathbase)
        if not quiet and len(args) > 1:
            announce("%s <- %d" % (arg, ctx.lo))


# pylint: disable=unused-argument
def init_method(*args):
    "Initialize a repository directory."
    # pylint: disable=unnecessary-pass
    pass


# pylint: disable=too-many-branches,too-many-statements
def commit_method(*args):
    "Commit changes to files."
    args = list(args)
    register_only = False
    parse_revspec = True
    branch = None
    differ = difflib.unified_diff
    while args:
        if args[0] == "--":
            args.pop(0)
            parse_revspec = False
            break
        elif args[0] == "-a":
            # Perform error check, but don't actually do a commit.
            # The Emacs VC-mode support for SRC was written early,
            # before 1.0, when I hadn't quite figured out what the
            # most efficient method for file registration would be.
            # VC-mode wants to have a registration as well as a
            # checkin method. This is no longer needed for normal SRC
            # operation, but it's better to leave this in place than
            # risk causing hassles for people running old Emacs versions.
            register_only = True
            parse_revspec = False
            args.pop(0)
        elif args[0] == "-b":
            args.pop(0)
            branch = args.pop(0)
        else:
            break
    comment = None  # pacify pylint
    if not register_only:
        comment = CommentContext("commit", args)
    ctx = CommandContext(
        "commit",
        args,
        require_empty=True,
        parse_revspec=parse_revspec and comment.parse_revspec,
    )
    for arg in ctx.args:
        if not os.path.exists(arg):
            croak("I see no '%s' here." % arg)
        if os.path.isdir(arg):
            croak("cannot commit directory '%s'" % arg)
    for arg in ctx.args:
        trailer = None  # Pacify pylint
        diff = None  # Pacify pylint
        if not registered(arg):
            trailer = "Committing initial revision of {0}.\n".format(arg)
            revcount = 0
            metadata = None
            diff = compute_diff(type("", (), {"filename": arg}), None, None, differ)
        elif register_only:
            croak("attempt to re-add a registered file failed")
        else:
            metadata = History(arg)
            ctx.resolve(metadata)
            if metadata and ctx.is_empty():
                ctx.select_tip(metadata)
            revcount = len(metadata)
            trailer = "Committing {0} revision {1}.\n".format(arg, revcount + 1)
            with backend.manager(arg):
                diff = compute_diff(metadata, ctx.lo, None, differ)
        if not register_only and not diff:
            announce("in %s, no changes to commit" % arg)
            continue
        if not register_only and not comment.edit("", trailer, diff):
            announce("in %s, commit cancelled" % arg)
        else:
            has_history = registered(arg)
            if not has_history:
                if debug >= DEBUG_COMMANDS:
                    logit("registration phase:\n")
                # We can't use the manager here, it wants to go clear down
                # to a repository directory.
                try:
                    d = os.path.dirname(arg)
                    if d:
                        chdir(d, "before registering")
                    backend.register(os.path.basename(arg))
                finally:
                    if d:
                        chdir(startdir, "after registering")
            if debug >= DEBUG_COMMANDS:
                logit("commit phase:\n")
            if not register_only:
                with backend.manager(arg) as xc:
                    # If the user changed the executable bit while
                    # modifying the workfile, propagate this change to
                    # the master.  Without this hack, the sequence (1)
                    # Commit workfile (2) Make workfile executable, (3)
                    # checkin workfile fails to work as expected because
                    # the VCS doesn't propagate the changed executable
                    # bit to the master, leading to misbehavior on the
                    # next checkout.
                    exec_copy(xc.pathbase, backend.history(xc.pathbase))
                    if branch is not None:
                        if not has_history:
                            croak("can't set branch on unregistered file.")
                        if branch not in metadata.symbols:
                            croak("can't switch to nonexistent branch %s." % branch)
                        elif not backend.isbranch(metadata.symbols[branch]):
                            croak("%s is not a branch." % branch)
                        backend.set_branch(metadata.symbols[branch], metadata.filename)
                    backend.checkin(xc.pathbase, comment.content())
            if metadata is None:
                metadata = History(arg)
            if not quiet and len(args) > 1:
                announce("%s -> %d" % (arg, revcount))


def add_method(*args):
    "For Emacs VC compatibility."
    commit_method("-a", *args)


def amend_method(*args):
    "Amend comments in stored revisions."
    if not os.path.exists(repodir):
        croak("repository subdirectory %s does not exist" % repodir)
    args = list(args)
    differ = difflib.unified_diff
    comment = CommentContext("amend", args)
    ctx = CommandContext("amend", args, parse_revspec=comment.parse_revspec)
    if ctx.is_range():
        croak("amend cannot take a range")
    for arg in ctx.args:
        if not os.path.exists(arg):
            croak("I see no '%s' here." % arg)
        elif not registered(arg):
            croak("%s is not registered." % arg)
    for arg in ctx.args:
        metadata = History(arg)
        ctx.resolve(metadata)
        if ctx.is_empty():
            ctx.lo = metadata.tip().revno
        trailer = "Amending {0} revision {1}.\n".format(arg, ctx.lo)
        item = metadata.by_revno(ctx.lo)
        parent = item.parent.revno if item.parent else None
        with backend.manager(arg):
            diff = compute_diff(metadata, parent, ctx.lo, differ)
        if not comment.edit(metadata.by_revno(ctx.lo).log, trailer, diff):
            announce("in %s, amend cancelled" % arg)
        else:
            with backend.manager(arg) as xc:
                backend.amend(
                    xc.pathbase, metadata.revno_to_native(ctx.lo), comment.content()
                )
    if not quiet and len(args) > 1:
        announce("%s : %d" % (arg, ctx.lo))


def list_method(*args):
    "Generate a summary listing of commits, one line per commit."
    args = list(args)
    custom = None
    limit = None
    parse_revspec = True
    while args and args[0].startswith("-"):
        if args[0] == "--":
            parse_revspec = False
            args.pop(0)
            break
        elif args[0] == "-f":
            args.pop(0)
            try:
                custom = args[0]
                args.pop(0)
            except IndexError:  # pragma: no cover
                croak("list -f requires a following string")
        elif args[0].startswith("-f"):
            # This case is used internally by Emacs VC mode. Don't remove it!
            custom = args[0][2:]
            args.pop(0)
        elif args[0] == "-l":
            args.pop(0)
            try:
                limit = args[0]
                args.pop(0)
                limit = int(limit)
            except IndexError:  # pragma: no cover
                croak("list -l requires a following integer")
            except ValueError:  # pragma: no cover
                croak("%s is not an integer" % limit)
        elif args[0][1:].isdigit():
            limit = int(args.pop(0)[1:])  # it's all digits, so no ValueError
        else:
            croak("unexpected %s option" % args[0])
    ctx = CommandContext(
        "list", args, default_to="branch_reversed", parse_revspec=parse_revspec
    )
    for arg in ctx.args:
        if ignore(arg) or os.path.isdir(arg) or not registered(arg):
            continue
        if custom is None:
            sys.stdout.write("= %s %s\n" % (arg, ((WIDTH - len(arg) - 3) * "=")))
        for item in ctx.resolve(History(arg)):
            # Must allow enough room for revno and date
            if item.selected():
                mark = "*"
            else:
                mark = "-"
            summary = item.log.split("\n")[0]
            if custom is None:
                summary = summary[: WIDTH - 34]
                sys.stdout.write(
                    "%-4d  %s %s %s\n"
                    % (item.revno, mark, item.getdate("author"), summary)
                )
            else:
                sys.stdout.write(
                    custom.format(
                        arg, item.revno, mark, item.getdate("author"), summary
                    )
                    + "\n"
                )
            if limit is not None:
                limit -= 1
                if limit <= 0:
                    break


def log_method(*args):
    "Report revision logs"
    limit = None
    args = list(args)
    parse_revspec = True
    differ = None
    ignore_ws = None
    verbose = 0
    while args and args[0].startswith("-"):
        if args[0] == "--":
            parse_revspec = False
            args.pop(0)
            break
        elif args[0] == "-l":
            args.pop(0)
            try:
                limit = args[0]
                args.pop(0)
                limit = int(limit)
            except IndexError:  # pragma: no cover
                croak("list -l requires a following integer")
            except ValueError:  # pragma: no cover
                croak("%s is not an integer" % limit)
        elif args[0][1:].isdigit():
            limit = int(args.pop(0)[1:])  # it's all digits, so no ValueError
        elif args[0] in ("--patch", "-p", "-u"):
            differ = difflib.unified_diff
            args.pop(0)
        elif args[0] == "-c":
            differ = difflib.context_diff
            args.pop(0)
        elif args[0] in ("-b", "-w"):
            ignore_ws = args.pop(0)
        elif args[0] == "-v":
            verbose += 1
            args.pop(0)
        else:
            croak("unexpected %s option" % args[0])
    ctx = CommandContext(
        "log", args, default_to="branch_reversed", parse_revspec=parse_revspec
    )
    # pylint: disable=too-many-nested-blocks
    for arg in ctx.args:
        if ignore(arg) or os.path.isdir(arg) or not registered(arg):
            continue
        sys.stdout.write("= %s %s\n" % (arg, ((WIDTH - len(arg) - 3) * "=")))
        metadata = History(arg)
        for item in ctx.resolve(metadata):
            sys.stdout.write(
                "%s%-4d%s | %s%s%s | %s%s%s\n"
                % (
                    BOLD + CCYAN,
                    item.revno,
                    RESET,
                    CYELLOW,
                    item.getdate("author"),
                    RESET,
                    BOLD + CGREEN,
                    item.branch,
                    RESET,
                )
            )
            if verbose and item.headers:
                headers = item.headers
                if verbose == 1:
                    headers = {}
                    for k in ("author", "committer"):
                        if k in item.headers:
                            v = item.headers[k]
                            if k + "-date" in item.headers:
                                v += " " + item.headers[k + "-date"]
                            headers[k] = v
                for k in sorted(headers.keys()):
                    sys.stdout.write(
                        "%s%s%s: %s\n" % (BOLD, k.title(), RESET, headers[k])
                    )
                sys.stdout.write("\n")
            sys.stdout.write("%s" % item.log)
            if differ:
                if item.parent:
                    parent = item.parent.revno
                    pdesc = "r%d/%s" % (parent, arg)
                else:
                    parent = None
                    pdesc = "/dev/null"
                sys.stdout.write(
                    "\n%sdiff %s r%s/%s%s\n" % (BOLD, pdesc, item.revno, arg, RESET)
                )
                print_diff(metadata, parent, item.revno, differ, ignore_ws)
            sys.stdout.write(("-" * WIDTH) + "\n")
            if limit is not None:
                limit -= 1
                if limit <= 0:
                    break


def status_method(*args):
    "Get status of some or all files."
    args = list(args)
    allflag = False
    qflag = False
    if args:
        if args[0] == "--":
            args.pop(0)
        elif args[0] == "-a":
            allflag = True
            args.pop(0)
        elif args[0] == "-q":
            qflag = True
            args.pop(0)
    # No command context is created, so we do this explicitly
    if multidir and not quiet:
        announce("%s is selected." % repodir)
    if args:
        candidates = args
    else:
        candidates = []
        for dirpath, _, fnames in os.walk("./"):
            # This prevents the search from blowing up on large directories that have a lot
            # of subdirectories that aren't SRC-controlled.
            if (
                (not os.path.exists(os.path.join(dirpath, ".src")))
                and (not os.path.exists(os.path.join(dirpath, "RCS")))
                and (not os.path.exists(os.path.join(dirpath, "SCCS")))
            ):
                continue
            for f in fnames:
                candidates.append(os.path.join(dirpath, f)[2:])
    pairs = []
    for fn in candidates:
        if backend.is_history(fn):
            if not os.path.isfile(backend.workfile(fn)):
                pairs.append((fn, "!"))
        elif ignore(fn):
            if allflag or fn in args:
                pairs.append((fn, "I"))
        elif not os.path.isfile(backend.history(fn)):
            if not qflag:
                pairs.append((fn, "?"))
        elif not os.path.exists(fn):
            pairs.append((fn, "!"))
        elif modified(fn):
            pairs.append((fn, "M"))
        elif not os.access(fn, os.W_OK):
            pairs.append((fn, "L"))
        elif not backend.has_revisions(fn):
            pairs.append((fn, "A"))
        else:
            pairs.append((fn, "="))
    pairs.sort()
    for (fn, status) in pairs:
        sys.stdout.write(status + "  " + fn + "\n")


def cat_method(*args):
    "Dump revision content to standard output."
    ctx = CommandContext("cat", args)
    if ctx.is_range():
        croak("cat refuses to cough up a hairball")
    elif ctx.args[0] == "--":
        # FIXME: Shouldn't be needed, see the -- skip in CommandContext init.
        ctx.args.pop(0)
    for arg in ctx.args:
        metadata = History(arg)
        ctx.resolve(metadata)
        if ctx.is_empty():
            ctx.select_tip(metadata)
        with backend.manager(arg) as xc:
            for item in ctx.seq:
                with backend.cat(xc.pathbase, item.native) as fp:
                    sys.stdout.write(polystr(fp.read()))


def diff_method(*args):
    "Dump diffs between revisions to standard output."
    if isinstance(args, tuple):
        args = list(args)
    differ = difflib.unified_diff
    ignore_ws = None
    while args and args[0] != "--" and args[0].startswith("-"):
        if args[0] == "-u":
            differ = difflib.unified_diff
            args.pop(0)
        elif args[0] == "-c":
            differ = difflib.context_diff
            args.pop(0)
        elif args[0] in ("-b", "-w"):
            ignore_ws = args.pop(0)
        else:
            croak("unexpected %s option" % args[0])
    ctx = CommandContext("diff", args)
    for arg in ctx.args:
        metadata = History(arg)
        ctx.resolve(metadata)
        if ctx.is_empty():
            ctx.select_tip(metadata)
        print_diff(metadata, ctx.lo, ctx.hi, differ, ignore_ws)


# pylint: disable=too-many-locals,too-many-nested-blocks
def tag_helper(args, legend, validation_hook, delete_method, set_method):
    "Dispatch to handlers for tag and branch manipulation."
    if not os.path.exists(repodir):
        croak("repository subdirectory %s does not exist" % repodir)
    args = list(args)
    if not args:
        args = ["list"] + args
    if args[0] == "--":
        args.pop(0)
    else:
        if args[0] in ("-d", "del", "delete"):
            args.pop(0)
            if not args:
                croak("%s deletion requires a name argument" % legend)
            name = args.pop(0)
            ctx = CommandContext(legend, args)
            if not ctx.is_empty():
                croak(
                    "can't accept a revision-spec when deleting a %s." % legend
                )  # pragma: no cover (should never happen)
            for arg in ctx.args:
                metadata = History(arg)
                if name not in metadata.symbols:
                    croak("in %s, %s is not a symbol" % (arg, name))
                elif backend.isbranch(metadata.symbols[name]) != (legend == "branch"):
                    croak("in %s, %s is not a %s" % (arg, name, legend))
                else:
                    if legend == "branch":
                        current_branch = metadata.symbols[name]
                        for lock in metadata.lockrevs:
                            if backend.revision_to_branch(lock) == current_branch:
                                croak("can't delete the current branch")
                    status = 0
                    with backend.manager(arg) as xc:
                        status = delete_method(name, metadata)
                    if status != 0:
                        croak("%s deletion failed." % legend)
                    if not quiet and len(args) > 1:
                        announce("in %s, %s %s removed" % (xc.pathbase, legend, name))
                return
        if args[0] in ("-l", "list"):
            args.pop(0)
            ctx = CommandContext(legend + " listing", args, require_empty=True)
            for arg in ctx.args:
                metadata = History(arg)
                ctx.resolve(metadata)
                if ctx.is_empty():
                    prepend = [0]
                    ctx.select_all(metadata)
                else:
                    prepend = []
                revisions = prepend + [item.revno for item in ctx.seq]
                sys.stdout.write("= %s %s\n" % (arg, ((WIDTH - len(arg) - 5) * "=")))
                keys = list(metadata.symbols.keys())
                if metadata.tipbranch in keys:
                    keys.remove(metadata.tipbranch)
                    keys.sort()
                    keys = [metadata.tipbranch] + keys
                for key in keys:
                    value = metadata.symbols[key]
                    selected = ""
                    if legend == "branch":
                        # Note!  This code relies on
                        # backend.branch_to_parent() returning an empty
                        # string when called on a trunk revision.
                        displaystr = backend.branch_to_parent(value)
                        if not displaystr:
                            display = 0
                        else:
                            display = metadata.native_to_revno(displaystr)
                        selected = "* " if key == metadata.tipbranch else "- "
                    else:
                        display = metadata.native_to_revno(value)
                    if display in revisions and backend.isbranch(value) == (
                        legend == "branch"
                    ):
                        sys.stdout.write("%4s\t%s%s\n" % (display, selected, key))
            return
        if args[0] in ("-c", "create"):
            args.pop(0)
            if not args:
                croak("%s setting requires a name argument" % legend)
            name = args.pop(0)
            ctx = CommandContext(legend, args)
            if ctx.is_range():
                croak("can't accept a range when setting a %s" % legend)
            for arg in ctx.args:
                metadata = History(arg)
                revision = validation_hook(ctx, metadata, name)
                with backend.manager(arg) as xc:
                    set_method(name, revision, metadata)
                    if not quiet and len(args) > 1:
                        announce(
                            "in %s, %s %s = %s" % (xc.pathbase, legend, name, ctx.start)
                        )
            return


def tag_method(*args):
    "Inspect, create, and delete tags."

    def tag_set_validate(ctx, metadata, name):
        ctx.resolve(metadata)
        if name in metadata.symbols:
            croak("tag %s already set." % name)
        if ctx.is_empty():
            ctx.select_tip(metadata)
        return metadata.revno_to_native(ctx.lo)

    tag_helper(args, "tag", tag_set_validate, backend.delete_tag, backend.set_tag)


def branch_method(*args):
    "Inspect, create, and delete branches."

    def branch_set_validate(ctx, _metadata, _name):
        if not ctx.is_empty():
            croak("cannot accept a revision after a branch name")

    tag_helper(
        args, "branch", branch_set_validate, backend.delete_branch, backend.make_branch
    )


def rename_method(*args):
    "Rename a branch or tag."
    args = list(args)
    if not args or args[0] not in ("tag", "branch"):
        croak("rename requires a following 'tag' or 'branch'")
    legend = args.pop(0)
    if not args:
        croak("rename requires a source name argument")
    name = args.pop(0)
    if not args:
        croak("rename requires a target name argument")
    newname = args.pop(0)
    ctx = CommandContext(legend + " renaming", args, require_empty=True)
    for arg in ctx.args:
        metadata = History(arg)
        if name not in metadata.symbols:
            croak("in %s, cannot rename nonexistent %s %s" % (arg, legend, name))
        if newname in metadata.symbols:
            croak("in %s, cannot rename to existing %s %s" % (arg, legend, name))
        ctx = CommandContext(legend, args)
        if not ctx.is_empty():
            croak("can't accept a revision-spec when renaming a %s." % legend)
        # In the case of a branch, we want to change only the
        # tag reference.
        with backend.manager(arg):
            backend.set_tag(newname, metadata.symbols[name], metadata)
            backend.delete_tag(name, metadata)
        if not quiet and len(args) > 1:
            announce("in %s, %s -> %s" % (arg, name, newname))


def filecmd(legend, hook, args):
    CommandContext(legend, args, require_empty=True)
    if len(args) != 2:
        croak("%s requires exactly two arguments" % legend)
    (source, target) = args
    if not os.path.exists(source):
        croak("I see no '%s' here." % source)
    elif os.sep in target and not os.path.exists(os.path.dirname(target)):
        croak("directory '%s' does not exist." % target)
    elif not registered(source):
        croak("%s is not registered" % source)
    elif registered(target):
        croak("%s is registered, I won't step on it" % source)
    elif os.path.exists(target):
        croak(
            "%s exists, please delete manually if you want it gone" % target
        )  # pragma: no cover
    else:
        hook(source, target)


def move_method(*args):
    "Move a file and its history."
    filecmd("move", backend.move, args)


def copy_method(*args):
    "Copy a file and its history."
    filecmd("copy", backend.copy, args)


def release_method(*args):  # pragma: no cover
    "Release locks."
    ctx = CommandContext("release", args, require_empty=True)
    for arg in ctx.args:
        if not os.path.exists(arg):
            croak("I see no '%s' here." % arg)
        elif not registered(arg):
            croak("%s is not registered, skipping" % arg)
        else:
            with backend.manager(arg) as xc:
                backend.release(xc.pathbase)


def srcify_method(*args):
    "Move an RCS or SCCS directory into SRC management."
    if os.path.exists(".src"):
        croak("A %s directory already exists." % repodir)
    if args:
        croak("lift cannot accept arguments")
    if not os.path.isdir("RCS") and not os.path.isdir("SCCS"):
        croak("no RCS or SCCS directory")
    candidates = [
        f for f in os.listdir(".") if os.path.isfile(f) and not os.path.islink(f)
    ]
    for fn in candidates:
        if registered(fn) and (not os.path.exists(fn) or not modified(fn)):
            with backend.manager(fn) as xc:
                backend.checkout(xc.pathbase, "")
    if os.path.isdir("RCS"):
        rename("RCS", ".src", "in srcify")


def ls_method(*args):
    "List registered files."
    if args:
        croak("ls cannot accept arguments")
    try:
        masters = [fn for fn in os.listdir(repodir) if backend.is_history(fn)]
    except OSError:
        croak("repo directory %s does not exist" % repodir)
    masters.sort()
    for master in masters:
        sys.stdout.write(backend.workfile(master) + "\n")


def visualize_method(*args):
    "Generate (and possibly display) a DOT visualization of repo structure."
    if not os.path.exists(repodir):
        croak("repository subdirectory %s does not exist" % repodir)
    args = list(args)
    comment = CommentContext("visualize", args)
    ctx = CommandContext("visualize", args, parse_revspec=comment.parse_revspec)
    for arg in ctx.args:
        # if not os.path.exists(arg):
        #    croak("I see no '%s' here." % arg)
        if not registered(arg):
            croak("%s is not registered." % arg)
    for arg in ctx.args:
        metadata = History(arg)
        ctx.resolve(metadata)
        if ctx.is_empty():
            ctx.select_all(metadata)
        sys.stdout.write("digraph {\n")
        if len(ctx.args) > 1:
            pref = arg + ":"
        else:
            pref = ""
        for item in ctx.seq:
            if item.parent:
                sys.stdout.write(
                    "\t%s%d -> %s%d;\n" % (pref, item.parent.revno, pref, item.revno)
                )
            summary = htmlescape(item.log.split("\n")[0][:42])
            sys.stdout.write(
                '\t%s%s [shape=box,width=5,label=<<table cellspacing="0" border="0" cellborder="0"><tr><td><font color="blue">%s%s</font></td><td>%s</td></tr></table>>];\n'
                % (pref, item.revno, pref, item.revno, summary)
            )
            if metadata.tip(item.native) == item:
                sys.stdout.write(
                    '\t"%s%s" [shape=oval,width=2];\n' % (pref, item.branch)
                )
                sys.stdout.write(
                    '\t"%s%s" -> "%s%s" [style=dotted];\n'
                    % (pref, item.revno, pref, item.branch)
                )
        keys = sorted(metadata.symbols.keys())
        for name in keys:
            native = metadata.symbols[name]
            branch_label = backend.isbranch(native)
            if branch_label:
                native = backend.branch_to_tip(native, metadata)
            revno = metadata.native_to_revno(native)
            if not branch_label:
                sys.stdout.write(
                    '\t{rank=same; "%s%s"; "%s%s"}\n' % (pref, name, pref, revno)
                )
                sys.stdout.write(
                    '\t"%s%s" -> "%s%s" [style=dotted];\n' % (pref, name, pref, revno)
                )
        sys.stdout.write("}\n")


# pylint: disable=too-many-locals
def fast_export_method(*args):
    "Dump revision content to standard output."

    def attribute(item, who, fallback):
        s = fallback
        if item.headers and who in item.headers:
            s = item.headers[who]
        t, o = item.unixtime(who)
        return "%s %s %d %s%02d%02d\n" % (
            (who, s, t, "-" if o < 0 else "+") + divmod(abs(o), 3600)
        )

    ctx = CommandContext("fast-export", args)
    mark = 0
    if pseudotime:
        username = "J. Random Hacker"
        useremail = "jrh@nowhere.man"
    else:
        username = polystr(capture_or_die("git config --get user.name")).strip()
        useremail = polystr(capture_or_die("git config --get user.email")).strip()
    attribution = "%s <%s>" % (username, useremail)
    markmap = {}
    tips = {}
    last_commit_mark = 0

    # This is meant to be consumed by reposurgeon's importer
    sys.stdout.write(
        "#sourcetype %s\n" % {"RCS": "rcs", "SCCS": "sccs"}.get(repodir, "src")
    )
    for arg in ctx.args:
        if not registered(arg):
            croak("%s is not registered" % arg)
        executable = os.stat(backend.history(arg)).st_mode & stat.S_IXUSR
        if executable:
            perms = "100755"
        else:
            perms = "100644"
        metadata = History(arg)
        ctx.resolve(metadata)
        if ctx.is_empty():
            ctx.select_all(metadata)
        with backend.manager(arg) as xc:
            for i in range(ctx.lo, ctx.hi + 1):
                item = metadata.by_revno(i)
                with backend.cat(xc.pathbase, item.native) as fp:
                    content = fp.read()  # this data will be binary
                size = len(content)  # size will be # of bytes, as desired
                mark += 1
                markmap[item.revno] = mark
                sys.stdout.write("blob\nmark :%d\ndata %d\n" % (mark, size))
                sys.stdout.write(polystr(content) + "\n")
                # Ideally this would be in Git canonical even with tags.
                # This is tricky; see reposurgeon's rules for branch coloring.
                # It's not really worth the extra complexity as long at these
                # streams round-trip properly.
                branch = item.branch
                if branch == "trunk":
                    branch = "master"
                oldbranch = branch
                for c in "~^\\*?":
                    branch = branch.replace(c, "")
                if not branch:
                    croak("branch name %s is ill-formed" % oldbranch)
                elif branch != oldbranch:
                    announce("branch name %s sanitized to %s" % (oldbranch, branch))
                if branch not in tips:
                    sys.stdout.write("reset refs/heads/" + branch + "\n")
                sys.stdout.write("commit refs/heads/%s\n" % branch)
                # Hidden magic for cluing in reposurgeon
                if "--reposurgeon" in args:
                    oid = item.revno
                    if repodir != ".src":
                        oid = item.native
                    sys.stdout.write("#legacy-id %s\n" % oid)
                sys.stdout.write("mark :%d\n" % (mark + 1))
                sys.stdout.write(attribute(item, "author", attribution))
                sys.stdout.write(attribute(item, "committer", attribution))
                sys.stdout.write("data %s\n%s" % (len(item.log), item.log))
                if last_commit_mark:
                    sys.stdout.write("from :%d\n" % last_commit_mark)
                arg = xc.pathbase
                if arg == ".srcignore":
                    arg = ".gitignore"
                if len(arg.split()) > 1:
                    arg = '"' + arg + '"'
                sys.stdout.write("M %s :%d %s\n\n" % (perms, mark, arg))
                mark += 1
                last_commit_mark = mark
                markmap[item.revno] = mark
                tips[branch] = mark
            for (key, val) in list(metadata.symbols.items()):
                val = metadata.native_to_revno(val)
                if val in ctx:
                    sys.stdout.write(
                        "reset refs/tags/%s\nfrom :%d\n\n" % (key, markmap[val])
                    )
    # At some point git-fast-export stopped issuing branch-tip resets.
    # for branch in tips:
    #    sys.stdout.write("reset refs/heads/%s\nfrom :%d\n\n" % (branch, tips[branch]))


def fast_import_method(*args):
    "Accept a git fast-import stream on stdin, turn it into file histories."
    if not isinstance(backend, RCS):
        croak("fast-import is only supported with the RCS backend")
    if os.path.exists("RCS"):
        croak("refusing to unpack into existing RCS directory!")
    # Force -l to fit SRC's lockless interface.
    do_or_die(
        r"rcs-fast-import -l " + " ".join(args),
        "fast_import_method",
        missing="rcs-fast-import",
    )
    try:
        os.makedirs(repodir)
    except OSError:
        pass
    for fn in os.listdir("RCS"):
        corresponding = os.path.join("RCS", os.path.basename(fn))
        fn = os.path.join(repodir, os.path.basename(fn))
        if os.path.exists(fn):
            croak("%s exists, aborting leaving RCS in place!" % corresponding)
        rename(corresponding, fn, "fast-import")
    shutil.rmtree("RCS")


# pylint: disable=unused-argument
def version_method(*args):
    "Report SRC's version"
    sys.stdout.write("src: %s\n" % version)
    (major, minor, micro, _releaselevel, _serial) = sys.version_info
    sys.stdout.write("python: %s.%s.%s\n" % (major, minor, micro))
    sys.stdout.write("%s: %s\n" % (backend.__class__.__name__, backend.version()))
    sys.stdout.write("platform: %s\n" % sys.platform)
    if os.path.exists(".git"):  # pragma: no cover
        sys.stdout.write("revision: %s\n" % capture_or_die("git rev-parse HEAD"))


dispatch = {
    "help": help_method,
    "commit": commit_method,
    "ci": commit_method,
    "add": add_method,
    "amend": amend_method,
    "am": amend_method,
    "init": init_method,
    "list": list_method,
    "li": list_method,
    "log": log_method,
    "checkout": checkout_method,
    "co": checkout_method,
    "status": status_method,
    "st": status_method,
    "cat": cat_method,
    "diff": diff_method,
    "di": diff_method,
    "tag": tag_method,
    "branch": branch_method,
    "rn": rename_method,
    "rename": rename_method,
    "ls": ls_method,
    "move": move_method,
    "mv": move_method,
    "copy": copy_method,
    "cp": copy_method,
    "visualize": visualize_method,
    "vis": visualize_method,
    "fast-export": fast_export_method,
    "fast-import": fast_import_method,
    "release": release_method,
    "srcify": srcify_method,
    "version": version_method,
}

# Interpreting branch and revision numbers
#
# SCCS and RCS were originally designed on the assumption that a revision
# within a branch is named by a major and minor release number. The
# terminology used for these parts has varied.  When you check in a change
# without specifing a revision, the minor number is incremented from the one
# on the tip of the current branch and the major number is left unchanged.
#
# RCS conventions are better documented. Examples from
# the GNU RCS manual follow; see
# https://www.gnu.org/software/rcs/manual/rcs.html
# sections 1.2.3 and  3.1.2 for details.
#
# 1.1         -- revision number for initial checkin (typically);
#                branch number: 1
#                next higher branch number:   2
#                next higher revision number: 1.2
#
# 9.4.1.42    -- more complicated (perhaps after much gnarly hacking);
#                branch number: 9.4.1
#                next higher branch number:   9.4.2
#                next higher revision number: 9.4.1.43
#
# 33.333.333  -- not a valid revision number;
#                however, a perfectly valid branch number
#                next higher branch number:   333.333.334
#                next higher revision number: 333.333.333.1
#
# A revision ID may have any (even) number of components. Branches are designated
# by IDs with an odd number of components. Revision and branch numbers never
# contain zero (the manual says "All integers are positive.").
#
# The manual says: "The branch point of a non-trunk branch is the
# revision number formed by removing the branch’s trailing integer. To
# compute the next higher branch or revision number, add one to the
# trailing integer. The highest-numbered revision on a branch is
# called the tip of the branch (or branch tip)."
#
# SCCS numbering (not supported yet) works differently from RCS
# numbering.  Details at http://osr507doc.sco.com/en/tools/SCCS_delta_numbering.html
# Unfortunately, he official GNU SCCS documentation at
# https://www.gnu.org/software/cssc/manual/index.html
# has almost nothing useful to say about it.
#
# SCCS node IDs have at most 4 parts in the form R.B.L.S (release, branch,
# level, sequence - slightly different terminology than RCS would later use).
# Branch IDs are distinguished by an explicit trailing zero.
#
# 1.0 - Trunk banch ID
# 1.1 - First checkin on trunk
# 1.1.1.0 - ID of first branch from trunk v1.1
# 1.1.1.1 - Next checkin on that branch
# 1.1.2.0 - Second branch from v1.1
# 1.2 - Next checkin on trunk.
#
# The main difference is that in original AT&T SCCS you could not
# branch from a branch, only from trunk. This restriction was removed
# in at least some later versions, including CSSC and the Schilling
# fork.  In section 3.5.3 the CSSC manual says
#
# "When a branch is created from an existing sid, the release and level
# numbers are copied, the branch number is set to the lowest unused
# value for that release and level, and the sequence number is set to
# one. Hence the first branch from version 1.1 will be version 1.1.1.1,
# and if a branch is made from that, its sid will be 1.1.2.1."
#
# Jorg Schilling writes, 2018-11-29: "I cannot speak for RCS, but the
# naming conventions used for branches in SCCS are not engraved into
# the sources but rather a convention that is encouraged by the way
# "get -e -b" works with or without -rSID option. SCCS internally uses
# serial numbers and for this reason it is currently limited to 2G
# deltas even though the R.B.L.S scheme could allow more. You could
# even edit the p.file and control the SID that is used for the next
# delget(1) as long as you don't violate basic rules."
#
# In both SCCS and RCS, you normally construct branch numbers to pass them
# to the checkin command to make the checkin happen on a new branch.
# The actual ID generated for that revision will be different;
# in RCS it will have a 1 appended, in RCS the trailing 0 will be
# replaced with a 1.
#
# In SCCS, it is documented in one SCO version that passing a branch
# number to a retrieval command will retrieve the branch tip revision.
# This is not documented in Solaris or GNU SCCS.  Nor is it explictly
# documented in GNU RCS, though there are hints in various parts related
# to revision numbers and it actually works there.
#
# Interpreting symbol values
#
# SCCS doesn't have symbols (name-to-revision or name-to-branch
# associations) at all. RCS has them and stores them in a header
# section of the master file.
#
# A weird curveball that RCS tosses is that the values of branch symbols are
# sometimes (always?) stored in masters with a zero inserted as the second
# to last component.  That is, for example, "1.3.1" is stored as "1.3.0.1"
# and even displayed that way in rlog output. I have seen, but cannot find,
# an RCS document that muttered this was an "efficiency hack". SRC never
# had to notice this quirk, as it always refers to branches by name.
#
# The release-numbering problem
#
# In all of the above examples except two deliberately odd ones from the GNU
# manual, the major part of a revision ID is always 1. It is possible to
# change the major part by specifying a revision when you check in, but this
# has seldom actually been done. SRC itself never does this, but it's a
# possibility (if a remote one) in CVS, RCS, and SCCS collections.
#
# This possibility matters when we are trying to find the branch tip
# or base associated with a particular revision. Breaks introduced
# by major-number changes will screw up the traversal.
#
# Note that SRC uses the empty string as the predecessor of the first
# (1.1) revision.


class RevisionMixin:
    "Express common operations on RCS and SCCS revisions."

    @staticmethod
    def splitrev(rev):
        "Native revision to numeric tuple."
        return [int(d) for d in rev.split(".")]

    @staticmethod
    def joinrev(rev):
        "Numeric tuple to native revision."
        return ".".join([str(d) for d in rev])

    def pred(self, rev):
        "Our predecessor. Walks up parent branch."
        # Assumes the release number has never beem bumped.
        n = self.splitrev(rev)
        if n[-1] > 1:
            n[-1] -= 1
            rev = self.joinrev(n)
        else:
            rev = self.joinrev(n[:-2])
        return rev

    def succ(self, rev):
        "Our successor node, in any back end."
        # Assumes the release number is never bumped.
        if rev:
            n = self.splitrev(rev)
            n[-1] += 1
            return self.joinrev(n)
        else:
            return "1.1"

    def branch_to_base(self, revid):
        "Go from a branch ID tag to the first revision of its branch."
        rev = self.branch_to_parent(revid)
        if rev:
            rev += ".1.1"
        else:
            rev = "1.1"
        return rev

    def branch_to_tip(self, revid, metadata):
        "Go from a branch ID tag to the tip revision of its branch."
        rev = self.branch_to_base(revid)
        while True:
            nxt = self.succ(rev)
            if metadata.native_to_revno(nxt) is None:
                return rev
            else:
                rev = nxt
        croak("internal error: couldn't find branch tip of %s" % rev)

    def branch_child(self, name, revision, metadata):
        "Compute a base revision for a named branch."
        if name in metadata.symbols:
            return metadata.symbols[name]
        else:

            def branchfrom(c, p):
                "Is c a branch child (not direct descendant) of parent p?"
                c = self.splitrev(c)
                p = str(p)
                return len(c) == len(p) + 2 and c[len(p) :] == p

            baserev = metadata.current()
            newsib = len(
                [
                    item
                    for item in metadata.revlist
                    if branchfrom(item.native, baserev.revno)
                ]
            )
            newsib += 1
            base = baserev.native + "." + str(newsib)
            return base


def makerepodir(target):
    "Make a repo subdirectory if it does not exist."
    targetdir = os.path.dirname(target)
    subrepodir = os.path.join(targetdir, repodir)
    if targetdir and not os.path.isdir(subrepodir):
        os.mkdir(subrepodir)


class RCS(RevisionMixin):
    "Encapsulate RCS back end methods."
    delimiters = (
        "----------------------------",
        "=============================================================================",
    )
    RCS_SAVE = "RCS-save"

    class RCSManager:
        "Execution context for backend methods."

        def __init__(self, path):
            self.path = path
            self.pathbase = os.path.basename(path)
            self.__where = os.getcwd()
            self.__deferred = []
            self.__previous_handlers = {}

        def defer_signal(
            self, sig_num, stack_frame
        ):  # pragma: no cover (passed as hook)
            self.__deferred.append(sig_num)

        def __enter__(self):
            # Replace existing signal handlers with deferred handler
            for sig_num in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM):
                # signal.signal returns None when no handler has been
                # set in Python, which is the same as the default
                # handler (SIG_DFL) being set
                self.__previous_handlers[sig_num] = (
                    signal.signal(sig_num, self.defer_signal) or signal.SIG_DFL
                )
            if os.path.dirname(self.path):
                dirname = os.path.dirname(self.path)
                chdir(dirname, "enter from %s" % (caller(2) if debug else None))
            if not os.path.exists(repodir):
                croak("repository subdirectory %s does not exist" % relative(repodir))
            elif repodir != "RCS" and os.path.exists(repodir):
                if os.path.exists("RCS"):
                    rename("RCS", RCS.RCS_SAVE, "stashing")
                rename(repodir, "RCS", "setting up for RCS")
            return self

        def __exit__(self, extype, value, traceback_unused):
            if repodir != "RCS" and not os.path.exists(repodir):
                rename("RCS", repodir, "restoring")
                if os.path.exists(RCS.RCS_SAVE):
                    rename(RCS.RCS_SAVE, "RCS", "unstashing")
            chdir(self.__where, "within %s exit" % (caller(2) if debug else None))
            if extype and debug > 0:
                raise extype(value)
            # Restore handlers
            for sig_num, handler in self.__previous_handlers.items():
                signal.signal(sig_num, handler)
            # Send deferred signals
            while self.__deferred:
                sig_num = self.__deferred.pop(0)
                os.kill(os.getpid(), sig_num)
            return True

    @staticmethod
    def manager(path):
        return RCS.RCSManager(path)

    @staticmethod
    def history(arg):
        "History file corresponding to an RCS workfile."
        # The reason this is required is that we might not be within the
        # manager context when this function is called.  Thus we have to
        # check both possible locations for the master.
        for d in (backend.__class__.__name__, repodir):
            p = os.path.join(os.path.dirname(arg), d, os.path.basename(arg) + ",v")
            if os.path.exists(p):
                return p
        return p  # Use repodir as a default for nonexistent targets

    @staticmethod
    def workfile(arg):
        "Workfile corresponding to an RCS master"
        arg = arg[:-2]
        parts = arg.split(os.path.sep)
        if len(parts) > 1 and repodir in parts:
            parts.remove(repodir)
            arg = os.path.sep.join(parts)
        return arg

    @staticmethod
    def isbranch(revid):
        "Is this a branch symbol?"
        return (revid.count(".")) % 2 == 0

    def revision_to_branch(self, revid):
        "Go from a revision to its branch."
        return self.joinrev(self.splitrev(revid)[:-1])

    def branch_to_parent(self, revid):
        "Go from a revision or branch ID tag to the revision it was based on."
        remove = 1 if self.isbranch(revid) else 2
        return self.joinrev(self.splitrev(revid)[:-remove])

    @staticmethod
    def is_history(path):
        return path.endswith(",v")

    def has_revisions(self, arg):
        "Does the master for this file have any revisions"
        # The magic number 105 is the size of an empty RCS file (no
        # metadata, no revisions) at 76 bytes, plus 29 bytes.  We assume
        # that this size has stayed constant or increased since ancient
        # times.  In fact the size of an RCS file with revisions goes up
        # more - by the 78 bytes for the final, fixed line of the log
        # display.  This gives us plenty of slack to cope with minor
        # format differences.
        #
        # The motivation here is to make "src status" faster by avoiding
        # the need for an entire log parse when checking for "A" status.
        return os.path.getsize(self.history(arg)) > 105

    @staticmethod
    def register(arg):
        "Register a file. *Not* called from a manager context."
        rcs_master = os.path.join("RCS", arg + ",v")
        master = os.path.join(repodir, arg + ",v")
        if repodir != "RCS" and os.path.exists(rcs_master):
            croak("name collision with a pre-existing RCS directory.")
        # repodir could be .src or RCS or something random; cope
        if not os.path.isdir(repodir):
            if debug >= DEBUG_COMMANDS:
                logit("mkdir(%s)\n" % repodir)
            os.mkdir(repodir)
        # Key choices here: -b suppresses all keyword expansion, -U sets
        # non-strict locking (which makes branch appends less painful).
        do_or_die(
            "rcs {1} -U -kb -i {0} </dev/null".format(
                shellquote(arg), "" if debug else "-q"
            ),
            caller(1, "register") if debug else None,
        )
        # Depending on whether the RCS directory exists, the master can be
        # created either in the current directory or in the RCS directory.
        # Handle both cases. he move in the second case is safe because
        # we bailed out earlier rather than have a name collision here.
        arg += ",v"
        if os.path.exists(arg):
            rename(arg, master, caller(1, "register A case") if debug else None)
        elif os.path.exists(rcs_master):
            if repodir != "RCS":
                rename(
                    rcs_master, master, caller(1, "register B case") if debug else None
                )
        else:
            croak("failed to create master at %s." % master)  # pragma: no cover

    def checkin(self, arg, comment):
        "Check in a commit, with comment."
        # The ci -l option makes the file writeable (and locked) after checkin.
        # By unlocking the file *before* checkin with rcs -u we invoke the
        # following property described on the rcs(1) manual page: "If rev is
        # omitted and the caller has no lock, but owns the file and
        # locking is not set to strict, then the revision is appended to
        # the default branch (normally the trunk; see the -b option of
        # rcs(1))."  This is the behavior we want and why locking is set
        # to non-strict.
        do_or_die(
            "rcs {2} -U -u {0},v && ci -l -m{1} {0}".format(
                shellquote(arg), shellquote(comment), "" if debug else "-q"
            ),
            caller(1, "checkin") if debug else None,
        )

    def checkout(self, arg, revision):
        "Check out a revision. Leaves it writeable."
        # The operation sequence is: Remove workfile, remove the current lock,
        # checkout the required revision locked.
        do_or_die(
            "rm -f {0} && rcs {2} -u {0},v && co {2} -l{1} {0}".format(
                shellquote(arg), revision, "" if debug else "-q"
            ),
            caller(1, "checkout") if debug else None,
        )

    def amend(self, arg, rev, comment):
        "Amend a commit comment."
        do_or_die(
            "rcs -m{0}:{1} {2}".format(rev, shellquote(comment), shellquote(arg)),
            caller(1, "amend") if debug else None,
        )

    def cat(self, arg, revision):
        "Ship the contents of a revision to stdout or a named file."
        return popen_or_die(
            "co {2} -p -r{1} {0}".format(
                shellquote(arg), revision, "" if debug else "-q"
            ),
            caller(1, "cat") if debug else None,
        )

    def delete_tag(self, tagname, metadata):
        "Delete a specified tag."
        return do_or_die(
            "rcs -n{0} {1}".format(shellquote(tagname), shellquote(metadata.filename)),
            "",
        )

    def set_tag(self, tagname, revision, metadata):
        "Set a specified tag."
        return do_or_die(
            "rcs -N{0}:{1} {2}".format(
                shellquote(tagname), revision, shellquote(metadata.filename)
            ),
            caller(1, "set_tag") if debug else None,
        )

    def delete_branch(self, branchname, metadata):
        "Delete a specified branch."
        # From rcs(1): -orange deletes ("outdates") the revisions given
        # by range.  A range consisting of a single revision number
        # means that revision.  A range consisting of a branch number
        # means the latest revision on that branch.  A range of the form
        # rev1:rev2 means revisions rev1 to rev2 on the same branch,
        # :rev means from the beginning of the branch containing rev
        # up to and including rev, and rev: means from revision rev to
        # the end of the branch containing rev.  None of the outdated
        # revisions can have branches or locks.
        status = do_or_die(
            "rcs -o{0}:{1} {2}".format(
                self.branch_to_base(metadata.symbols[branchname]),
                self.branch_to_tip(metadata.symbols[branchname], metadata),
                shellquote(metadata.filename),
            ),
            caller(1, "delete_branch") if debug else None,
            fatal=False,
        )
        if status != 0:
            return status
        self.delete_tag(branchname, metadata)
        return 0

    def set_branch(self, revision, filename):
        "Set the specified branch to be default."
        do_or_die(
            "rcs -b%s %s"
            % (
                revision,
                shellquote(filename),
            ),
            caller(1, "set_branch") if debug else None,
        )

    def make_branch(self, name, revision, metadata):
        "Set the specified branch to be default, creating it if required."
        base = self.branch_child(name, revision, metadata)
        # Bind symbol for child branch. Internally, RCS might hack the
        # symbol into the "efficiency hack" form, e.g. 1.3.1 becoming
        # 1.3.0.1, but we don't need to care about that here. Relies
        # on being able to rebind a symbol to the value it currently
        # has without creating a duplicate definition.
        do_or_die(
            "rcs -n{0}:{1} '{2}'".format(name, base, shellquote(metadata.filename)),
            caller(1, "make_branch (symbol bind)") if debug else None,
        )
        # Set new default branch
        do_or_die(
            "rcs -b%s %s" % (base, shellquote(metadata.filename)),
            caller(1, "make_branch (change default)") if debug else None,
        )

    def move(self, source, target):
        "Move a file and its history."
        # Not called under RCSManager
        makerepodir(target)
        do_or_die(
            "mv {0} {1} && mv {2} {3}".format(
                shellquote(source),
                shellquote(target),
                shellquote(self.history(source)),
                shellquote(self.history(target)),
            ),
            caller(1, "move") if debug else None,
        )

    def copy(self, source, target):
        "Copy a file and its history."
        # Not called under RCSManager
        makerepodir(target)
        do_or_die(
            "cp {0} {1} && cp {2} {3}".format(
                shellquote(source),
                shellquote(target),
                shellquote(self.history(source)),
                shellquote(self.history(target)),
            ),
            caller(1, "copy") if debug else None,
        )

    def release(self, arg):
        "Release locks."
        do_or_die(
            "rcs {1} -u {0},v".format(shellquote(arg), "" if debug else "-q"),
            caller(1, "release") if debug else None,
        )

    @staticmethod
    def version():
        # rcs --version fails under OS X
        # rcs -V throws an obsolescence warning under GNU RCS 5.9.4
        # We choose the more portable option here.
        rawversion = capture_or_die("rcs -V 2>/dev/null")
        m = re.search(r"[0-9]+\.[0-9]+\.[0-9]+".encode("ascii"), rawversion)
        return m and polystr(m.group(0))

    def parse(self, metadata, basename):
        "Get and parse the RCS log output for this file."

        def sortkey(rev):
            return rev.date + ".".join("%010d" % int(n) for n in rev.native.split("."))

        def degrottify(rev):
            # Undo RCS's "efficiency hack" (that's what the manual called it).
            parts = rev.split(".")
            if len(parts) > 3 and parts[-2] == "0":
                parts = parts[:-2] + parts[-1:]
            return self.joinrev(parts)

        metadata.symbols["trunk"] = "1"
        metadata.tipbranch = "trunk"
        with popen_or_die(
            "cd %s >/dev/null; rlog '%s' 2>/dev/null; cd ..>/dev/null"
            % (shellquote(repodir), shellquote(basename)),
            caller(1, "metadata parse") if debug else None,
        ) as fp:
            if debug >= DEBUG_PARSE:
                logit("\t-> init\n")
            state = "init"
            for line in fp:
                line = polystr(line)
                if debug >= DEBUG_PARSE:
                    logit("in: %s\n" % repr(line))
                if state == "init":
                    if line.startswith("locks:"):
                        if debug >= DEBUG_PARSE:
                            logit("\t-> locks\n")
                        state = "locks"
                    elif line.startswith("symbolic names:"):
                        if debug >= DEBUG_PARSE:
                            logit("\t-> symbols\n")
                        state = "symbols"
                    elif line.startswith("branch:"):
                        branch = line.split(":")[1].strip()
                        # Undocumented fact about RCS: The branch "1"
                        # is the same as the blank branch.  Significant
                        # because you can't reset to the blank branch
                        # using rcs -b, that resets to the dynamically
                        # highest branch.
                        if not branch or branch == "1":
                            metadata.tipbranch = "trunk"
                        else:
                            metadata.tipbranch = degrottify(branch)
                    elif line.startswith("description:"):
                        state = "description"
                elif state == "description":
                    if line.startswith("============================"):
                        break
                    elif line.startswith("----------------------------"):
                        if debug >= DEBUG_PARSE:
                            logit("\t-> logheader\n")
                        state = "logheader"
                        metadata.revlist.append(HistoryEntry(metadata))
                        metadata.description = metadata.description[:-1]
                    else:
                        metadata.description += line
                elif state == "locks":
                    if not line[0].isspace():
                        if debug >= DEBUG_PARSE:
                            logit("\t-> init\n")
                        state = "init"
                    else:
                        fields = line.strip().split()
                        metadata.lockrevs.append(fields[1])
                elif state == "symbols":
                    if not line[0].isspace():
                        if debug >= DEBUG_PARSE:
                            logit("\t-> init\n")
                        state = "init"
                    else:
                        fields = line.strip().split()
                        name = fields[0]
                        if name.endswith(":"):
                            name = name[:-1]
                        rev = fields[1]
                        metadata.symbols[name] = degrottify(rev)
                elif state == "logheader":
                    if line.startswith("revision "):
                        fields = line.split()
                        metadata.revlist[-1].native = fields[1]
                    elif line.startswith("----------------------------"):
                        metadata.revlist.append(HistoryEntry(metadata))
                    elif line.startswith("date: "):
                        fields = line.split()
                        date = fields[1] + " " + fields[2]
                        if date.endswith(";"):
                            date = date[:-1]
                        date = date.replace("/", "-").replace(" ", "T") + "Z"
                        metadata.revlist[-1].date = date
                    elif line.startswith("branches:"):
                        continue
                    elif line.startswith("======================="):
                        # This deals with RCS v5.7 issuing a log header
                        # divider just before the terminator, something
                        # v5.8 does not do.
                        if not metadata.revlist[-1].native:
                            metadata.revlist.pop()
                        elif not metadata.revlist[-1].log.endswith("\n"):
                            metadata.revlist[-1].log += "\n"
                        break
                    elif line.strip() == "*** empty log message ***":
                        continue
                    elif metadata.revlist:
                        metadata.revlist[-1].log += line
            # Now that we have the symbol table, set the tip branch by name.
            if metadata.tipbranch != "trunk":
                for (k, v) in list(metadata.symbols.items()):
                    if v == metadata.tipbranch:
                        metadata.tipbranch = k
                        break
                else:
                    croak("unrecognized branch ID '%s'" % metadata.tipbranch)
            metadata.revlist.sort(key=sortkey)
            for (i, item) in enumerate(metadata.revlist):
                if pseudotime:
                    # Artificial date one day after the epoch
                    # to avoid timezone issues.
                    item.date = rfc3339(86400 + i * 60)
                item.revno = i + 1
            metadata.revlist.reverse()
            if debug >= DEBUG_PARSE:
                # sys.stdout.write("\t%d revisions\n" % len(metadata.revlist)
                logit("\tlockrevs: %s\n" % metadata.lockrevs)
                logit("\tsymbols: %s\n" % metadata.symbols)
            metadata.build_indices()


class SCCS(RevisionMixin):
    "Encapsulate SCCS back end methods."
    delimiters = ("-X-X-X-X-X--X-X-X-X-X--X-X-X-X-X-",)

    class SCCSManager:
        "Execution context for backend methods."

        def __init__(self, path):
            self.path = path
            self.pathbase = os.path.basename(path)
            self.__where = os.getcwd()
            if not os.path.isdir("SCCS"):
                croak("no SCCS directory.")
            self.__deferred = []
            self.__previous_handlers = {}

        def defer_signal(
            self, sig_num, stack_frame
        ):  # pragma: no cover (passed as hook)
            self.__deferred.append(sig_num)

        def __enter__(self):
            # Replace existing signal handlers with deferred handler
            for sig_num in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM):
                # signal.signal returns None when no handler has been
                # set in Python, which is the same as the default
                # handler (SIG_DFL) being set
                self.__previous_handlers[sig_num] = (
                    signal.signal(sig_num, self.defer_signal) or signal.SIG_DFL
                )
            if os.path.dirname(self.path):
                dirname = os.path.dirname(self.path)
                chdir(dirname, "within %s enter" % (caller(2) if debug else None))
            if not os.path.exists(repodir):
                croak("repository subdirectory %s does not exist" % relative(repodir))
            return self

        def __exit__(self, extype, value, traceback_unused):
            chdir(self.__where, "within %s exit" % (caller(2) if debug else None))
            # Restore handlers
            for sig_num, handler in self.__previous_handlers.items():
                signal.signal(sig_num, handler)
            # Send deferred signals
            while self.__deferred:
                sig_num = self.__deferred.pop(0)
                os.kill(os.getpid(), sig_num)
            return True

    @staticmethod
    def manager(path):
        return SCCS.SCCSManager(path)

    @staticmethod
    def __sccsfile(arg, pref):
        return os.path.join(
            os.path.dirname(arg), "SCCS", pref + "." + os.path.basename(arg)
        )

    @staticmethod
    def history(arg):
        "History file corresponding to an SCCS workfile."
        return SCCS.__sccsfile(arg, "s")

    @staticmethod
    def workfile(arg):
        "Workfile corresponding to an SCCS master"
        if "SCCS" in arg:
            arg = arg.replace("SCCS/s.", "")
        elif arg.startswith("s."):
            arg = arg[2:]
        return arg

    @staticmethod
    def isbranch(revid):
        "Is this a branch symbol?"
        return revid.endswith(".0")

    def revision_to_branch(self, revid):
        "Go from a revision to its branch."
        return self.joinrev(self.splitrev(revid)[:-1]) + ".0"

    def branch_to_parent(self, revid):
        "Go from a revisiob or branch ID tag to the revision it was based on."
        return self.joinrev(self.splitrev(revid)[:-2])

    @staticmethod
    def is_history(path):
        return os.path.basename(path).startswith("s.")

    @staticmethod
    def has_revisions(arg):
        "Does the master for this file have any revisions"
        # It's not possible to create an SCCS file without at least one
        # revision.
        return True

    @staticmethod
    def register(arg):
        "Register a file"
        if not os.path.isdir("SCCS"):
            os.mkdir("SCCS")

    def checkin(self, arg, comment):
        "Check in a commit, with comment."
        if os.path.exists(self.history(arg)):
            cmd = "delta -s -y{1} {0}".format(shellquote(arg), shellquote(comment))
        else:
            # Yuck - 2>/dev/null is required to banish the message
            # admin: warning: SCCS/XXXXX: No id keywords.
            cmd = "admin -fb -i {0} -y{1} <{0} 2>/dev/null".format(
                shellquote(arg), shellquote(comment)
            )
        do_or_die("TZ=UTC sccs " + cmd, caller(1, "checkin") if debug else None)
        # After checkin, make it writeable (and locked) again.
        do_or_die(
            "rm -f {0} && sccs get -e -s {0} >/dev/null".format(shellquote(arg)),
            caller(1, "get after checkin") if debug else None,
        )

    def checkout(self, arg, revision):
        "Check out a revision. Leaves it writeable."
        do_or_die("rm -f 'SCCS/p.{0}'".format(arg), caller(1) if debug else None)
        if revision:
            do_or_die(
                "rm -f {0} && sccs get -s -e -r{1} {0} >/dev/null".format(
                    shellquote(arg), revision
                ),
                caller(1, "checkout (revision)") if debug else None,
            )
        else:
            do_or_die(
                "rm -f '{0}' && sccs get -s -e {0} >/dev/null".format(shellquote(arg)),
                caller(1, "checkout (no revision)") if debug else None,
            )

    def amend(self, arg, rev, comment):
        "Amend a commit comment."
        comment = "'" + comment.replace("'", r"'\''") + "'"
        do_or_die(
            "sccs cdc -r{1} -y{2} {0}".format(
                shellquote(arg), rev, shellquote(comment)
            ),
            caller(1, "amend") if debug else None,
        )

    def cat(self, arg, revision):
        "Ship the contents of a revision to stdout or a named file."
        if revision:
            return popen_or_die(
                "sccs get -s -p -r{1} {0} 2>/dev/null".format(
                    shellquote(arg), revision
                ),
                caller(1, "metadata parse (revision)") if debug else None,
            )
        else:
            return popen_or_die(
                "sccs get -p {0}".format(shellquote(arg)),
                caller(1, "metadata parse (no revision)") if debug else None,
            )

    def delete_tag(self, tagname, metadata):
        "Delete a specified tag."
        croak("tags are not supported in the SCCS back end")  # pragma: no cover

    def set_tag(self, tagname, revision, metadata):
        "Set a specified tag."
        croak("tags are not supported in the SCCS back end")  # pragma: no cover

    def delete_branch(self, _branchname, _metadata):
        "Delete a specified branch."
        croak("branches are not supported in the SCCS back end")  # pragma: no cover

    def set_branch(self, _revision, _filename):
        "Set the specified branch to be default, creating it if required."
        croak("branches are not supported in the SCCS back end")  # pragma: no cover

    def make_branch(self, name, revision, metadata):
        "Set the specified branch to be default, creating it if required."
        croak("branches are not supported in the SCCS back end")  # pragma: no cover

    def move(self, source, target):
        "Move a file and its history."
        # Not called under SCCSManager
        makerepodir(target)
        do_or_die(
            "mv {0} {1} && mv {2} {3}".format(
                shellquote(source),
                shellquote(target),
                shellquote(self.history(source)),
                shellquote(self.history(target)),
            ),
            caller(1, "move") if debug else None,
        )

    def copy(self, source, target):
        "Copy a file and its history."
        # Not called under SCCSManager
        makerepodir(target)
        do_or_die(
            "cp {0} {1} && cp {2} {3}".format(
                shellquote(source),
                shellquote(target),
                shellquote(self.history(source)),
                shellquote(self.history(target)),
            ),
            caller(1, "copy") if debug else None,
        )

    @staticmethod
    def release(arg):
        "Release locks."
        do_or_die(
            "sccs admin -dla {0}".format(shellquote(arg)),
            caller(1, "release") if debug else None,
        )

    @staticmethod
    def version():
        rawversion = capture_or_die("sccs --version 2>&1")
        m = re.search(r"[0-9]+\.[0-9]+\.[0-9]+".encode("ascii"), rawversion)
        return m and polystr(m.group(0))

    def parse(self, metadata, basename):
        "Get and parse the SCCS log output for this file."
        metadata.symbols["trunk"] = "1.0"
        with popen_or_die(
            "sccs prs -e -d':FD::Dt:\n:C:{1}' {0} 2>/dev/null".format(
                shellquote(basename), SCCS.delimiters[0]
            ),
            caller(1, "metadata parse") if debug else None,
        ) as fp:
            if debug >= DEBUG_PARSE:
                logit("\t-> init\n")
            state = "init"
            for line in fp:
                line = polystr(line)
                if debug >= DEBUG_PARSE:
                    logit("in %s: %s\n" % (state, repr(line)))
                if state == "init":
                    if line == "none\n":
                        line = ""
                    metadata.description = line
                    state = "header"
                elif state == "header":
                    comment = ""
                    if line.startswith("D "):
                        try:
                            (_, rev, yymmdd, hhmmss) = line.split()[:4]
                            metadata.revlist.append(HistoryEntry(metadata))
                            metadata.revlist[-1].native = rev
                            yymmdd = yymmdd.replace("/", "-")
                            # In Schilling's SCCS the year has a century part,
                            # in CSSC it does not (yet, as of 2023).  Sun says:
                            #
                            # 'The X/Open standard states that old dates held in
                            # ("yy/mm/dd") format does not change in "s." files, but
                            # the values "yy" which range from 69 - 99 are to be
                            # interpreted as 1969 - 1999 respectively. Values of "yy"
                            # which range from 00 - 68 are to be interpreted as 2000
                            # - 2068 respectively.'
                            #
                            # This disambiguates out to 2068.  Note that on 32-bit
                            # platforms there will be a year-2038 problem sooner
                            # than that.
                            year = yymmdd.split("-")[0]
                            if len(year) < 4:
                                if year <= "68":
                                    yymmdd = str(20) + yymmdd
                                else:
                                    yymmdd = str(19) + yymmdd  # pragma: no cover
                            metadata.revlist[-1].date = yymmdd + "T" + hhmmss + "Z"
                        except ValueError:  # pragma: no cover
                            croak(
                                "ill-formed delta line"
                            )  # pragma: no cover (should never happen)
                        if debug >= DEBUG_PARSE:
                            logit("\t-> header\n")
                        state = "comment"
                elif state == "comment":
                    if line == SCCS.delimiters[0] + "\n":
                        metadata.revlist[-1].log = comment.rstrip() + "\n"
                        if debug >= DEBUG_PARSE:
                            logit("\t-> init\n")
                        state = "header"
                    else:
                        comment += line
            metadata.revlist.sort(key=lambda x: x.date)
            for (i, item) in enumerate(metadata.revlist):
                if pseudotime:
                    # Artificial date one day after the epoch
                    # to avoid timezone issues.
                    item.date = rfc3339(86400 + i * 60)
                item.revno = i + 1
            metadata.revlist.reverse()
            try:
                with open(self.__sccsfile(metadata.filename, "p"), "rb") as fp:
                    for line in fp:
                        metadata.lockrevs.append(polystr(line).split()[0])
            except IOError:
                pass
            metadata.build_indices()


backends = (RCS, SCCS)

if __name__ == "__main__":
    try:
        commandline = list(sys.argv[1:])
        repodir = ".src"
        backend = RCS
        multidir = os.path.exists(".src") and os.path.exists("RCS")
        startdir = os.getcwd()

        # If there's no .src directory, use the history
        # directory of whichever back end is active.
        if not os.path.exists(".src"):
            for vcs in backends:
                if os.path.exists(vcs.__name__):
                    repodir = vcs.__name__
                    backend = vcs
                    break

        while commandline and commandline[0].startswith("-"):
            if commandline[0] == "-d":
                debug += 1
            elif commandline[0] == "-q":
                quiet = True
            elif commandline[0] == "-T":
                pseudotime = True
            elif commandline[0] == "-S":
                repodir = commandline[1]
                commandline.pop(0)
            elif commandline[0] == "-L":
                logstream = open(commandline[1], "a", encoding=master_encoding)
                commandline.pop(0)
            else:
                croak(
                    "unknown option %s before command verb" % commandline[0]
                )  # pragma: no cover
            commandline.pop(0)

        if debug >= DEBUG_COMMANDS:
            logit("Starting at %s\n" % startdir)
            time.sleep(0.1)  # Prevents some kind of weird buffering screwup.

        # User might want to force the back end
        for vcs in backends:
            if commandline and commandline[0] == vcs.__name__.lower():
                backend = vcs
                commandline.pop(0)
                break

        if not commandline:
            help_method()
            raise SystemExit(0)  # pragma: no cover

        # Ugly constraint...
        if backend.__name__ == "SCCS":
            multidir = False
            repodir = "SCCS"
        elif backend.__name__ == "RCS":
            # In theory we could do this check only when .src exists. In practice,
            # we prefer making the program's behavior safer and easier for a human
            # to reason about - in doubtful cases it should just bail out rather than
            # trying to be overly clever.
            if os.path.exists(RCS.RCS_SAVE):
                croak(
                    "%s exists: a previous SRC must have crashed hard." % RCS.RCS_SAVE
                )

        backend = backend()

        if commandline[0] in dispatch:
            dispatch[commandline[0]](*commandline[1:])
        else:
            croak("no such command as '%s'.  Try 'src help'" % commandline[0])
    except KeyboardInterrupt:  # pragma: no cover
        pass

# The following sets edit modes for GNU EMACS
# Local Variables:
# mode:python
# End: