File: __init__.py

package info (click to toggle)
python-dunamai 1.23.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 504 kB
  • sloc: python: 3,535; sh: 7; makefile: 6
file content (2373 lines) | stat: -rw-r--r-- 86,496 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
__all__ = [
    "bump_version",
    "check_version",
    "get_version",
    "serialize_pep440",
    "serialize_pvp",
    "serialize_semver",
    "Style",
    "Vcs",
    "Version",
]

import copy
import datetime as dt
import inspect
import json
import re
import shlex
import shutil
import subprocess
from collections import OrderedDict
from enum import Enum
from functools import total_ordering
from pathlib import Path
from typing import (
    Any,
    Callable,
    List,
    Mapping,
    NamedTuple,
    Optional,
    Sequence,
    Set,
    Tuple,
    TypeVar,
    Union,
)
from xml.etree import ElementTree

VERSION_SOURCE_PATTERN = r"""
    (?x)                                                        (?# ignore whitespace)
    ^v((?P<epoch>\d+)!)?(?P<base>\d+(\.\d+)*)                   (?# v1.2.3 or v1!2000.1.2)
    ([-._]?((?P<stage>[a-zA-Z]+)[-._]?(?P<revision>\d+)?))?     (?# b0)
    (\+(?P<tagged_metadata>.+))?$                               (?# +linux)
""".strip()

# Preserve old/private name for now in case it exists in the wild
_VERSION_PATTERN = VERSION_SOURCE_PATTERN

_VALID_PEP440 = r"""
    (?x)
    ^(\d+!)?
    \d+(\.\d+)*
    ((a|b|rc)\d+)?
    (\.post\d+)?
    (\.dev\d+)?
    (\+([a-zA-Z0-9]|[a-zA-Z0-9]{2}|[a-zA-Z0-9][a-zA-Z0-9.]+[a-zA-Z0-9]))?$
""".strip()
_VALID_SEMVER = r"""
    (?x)
    ^\d+\.\d+\.\d+
    (\-[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)*)?
    (\+[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)*)?$
""".strip()
_VALID_PVP = r"^\d+(\.\d+)*(-[a-zA-Z0-9]+)*$"

_TIMESTAMP_GENERIC = "%Y-%m-%dT%H:%M:%S.%f%z"
_TIMESTAMP_GENERIC_SPACE = "%Y-%m-%d %H:%M:%S.%f%z"
_TIMESTAMP_GIT_ISO_STRICT = "%Y-%m-%dT%H:%M:%S%z"
_TIMESTAMP_GIT_ISO = "%Y-%m-%d %H:%M:%S %z"

_T = TypeVar("_T")


class Style(Enum):
    """
    Standard styles for serializing a version.
    """

    Pep440 = "pep440"
    """PEP 440"""
    SemVer = "semver"
    """Semantic Versioning"""
    Pvp = "pvp"
    """Haskell Package Versioning Policy"""


class Vcs(Enum):
    """
    Version control systems.
    """

    Any = "any"
    """Automatically determine the VCS."""
    Git = "git"
    """Git"""
    Mercurial = "mercurial"
    """Mercurial"""
    Darcs = "darcs"
    """Darcs"""
    Subversion = "subversion"
    """Subversion"""
    Bazaar = "bazaar"
    """Bazaar"""
    Fossil = "fossil"
    """Fossil"""
    Pijul = "pijul"
    """Pijul"""


class Pattern(Enum):
    """
    Regular expressions used to parse tags as versions.
    """

    Default = "default"
    """Default pattern, including `v` prefix."""
    DefaultUnprefixed = "default-unprefixed"
    """Default pattern, but without `v` prefix."""

    def regex(self, prefix: Optional[str] = None) -> str:
        """
        Get the regular expression for this preset pattern.

        :param prefix: Insert this after the pattern's start anchor (`^`).
        :returns: Regular expression.
        """
        variants = {
            Pattern.Default: VERSION_SOURCE_PATTERN,
            Pattern.DefaultUnprefixed: VERSION_SOURCE_PATTERN.replace("^v", "^v?", 1),
        }

        out = variants[self]
        if prefix:
            out = out.replace("^", "^{}".format(prefix), 1)

        return out

    @staticmethod
    def parse(pattern: Union[str, "Pattern"], prefix: Optional[str] = None) -> str:
        """
        Parse a pattern string into a regular expression.

        If the pattern contains the capture group `?P<base>`, then it is
        returned as-is. Otherwise, it is interpreted as a variant of the
        `Pattern` enum.

        :param pattern: Pattern to parse.
        :param prefix: Insert this after the pattern's start anchor (`^`).
        :returns: Regular expression.
        """
        if isinstance(pattern, str) and "?P<base>" in pattern:
            if prefix:
                return pattern.replace("^", "^{}".format(prefix), 1)
            else:
                return pattern

        try:
            pattern = Pattern(pattern)
        except ValueError:
            raise ValueError(
                _pattern_error(
                    (
                        "The pattern does not contain the capture group '?P<base>'"
                        " and is not a known preset like '{}'".format(Pattern.Default.value)
                    ),
                    pattern,
                )
            )
        return pattern.regex(prefix)


class Concern(Enum):
    """
    A concern/warning discovered while producing the version.
    """

    ShallowRepository = "shallow-repository"
    """Repository does not contain full history"""

    def message(self) -> str:
        """
        Produce a human-readable description of the concern.

        :returns: Concern description.
        """

        if self == Concern.ShallowRepository:
            return "This is a shallow repository, so Dunamai may not produce the correct version."
        else:
            return ""


def _pattern_error(primary: str, pattern: Union[str, Pattern], tags: Optional[Sequence[str]] = None) -> str:
    parts = [primary, "Pattern:\n{}".format(pattern)]

    if tags is not None:
        parts.append("Tags:\n{}".format(tags))

    return "\n\n".join(parts)


def _run_cmd(
    command: str,
    where: Optional[Path],
    codes: Sequence[int] = (0,),
    shell: bool = False,
    env: Optional[dict] = None,
) -> Tuple[int, str]:
    result = subprocess.run(
        shlex.split(command),
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        cwd=str(where) if where is not None else None,
        shell=shell,
        env=env,
    )
    output = result.stdout.decode().strip()
    if codes and result.returncode not in codes:
        raise RuntimeError("The command '{}' returned code {}. Output:\n{}".format(command, result.returncode, output))
    return (result.returncode, output)


_MatchedVersionPattern = NamedTuple(
    "_MatchedVersionPattern",
    [
        ("matched_tag", str),
        ("base", str),
        ("stage_revision", Optional[Tuple[str, Optional[int]]]),
        ("newer_tags", Sequence[str]),
        ("tagged_metadata", Optional[str]),
        ("epoch", Optional[int]),
    ],
)


def _match_version_pattern(
    pattern: Union[str, Pattern],
    sources: Sequence[str],
    latest_source: bool,
    strict: bool,
    pattern_prefix: Optional[str],
) -> Optional[_MatchedVersionPattern]:
    """
    :returns: Tuple of:
        * matched tag
        * base segment
        * tuple of:
          * stage
          * revision
        * any newer unmatched tags
        * tagged_metadata matched section
    """
    pattern_match = None
    base = None
    stage_revision = None
    newer_unmatched_tags = []
    tagged_metadata = None
    epoch = None  # type: Optional[Union[str, int]]

    pattern = Pattern.parse(pattern, pattern_prefix)

    for source in sources[:1] if latest_source else sources:
        try:
            pattern_match = re.search(pattern, source)
        except re.error as e:
            raise re.error(
                _pattern_error(
                    "The pattern is an invalid regular expression: {}".format(e.msg),  # type: ignore
                    pattern,
                ),
                e.pattern,  # type: ignore
                e.pos,  # type: ignore
            )
        if pattern_match is None:
            newer_unmatched_tags.append(source)
            continue
        try:
            base = pattern_match.group("base")
            if base is not None:
                break
        except IndexError:
            raise ValueError(_pattern_error("The pattern did not include required capture group 'base'", pattern))
    if pattern_match is None or base is None:
        if latest_source:
            raise ValueError(
                _pattern_error(
                    "The pattern did not match the latest tag '{}'".format(sources[0]),
                    pattern,
                    sources,
                )
            )
        elif strict:
            raise ValueError(_pattern_error("The pattern did not match any tags", pattern, sources))
        else:
            return None

    stage = pattern_match.groupdict().get("stage")
    revision = pattern_match.groupdict().get("revision")
    tagged_metadata = pattern_match.groupdict().get("tagged_metadata")
    epoch = pattern_match.groupdict().get("epoch")
    if stage is not None:
        try:
            stage_revision = (stage, None if revision is None else int(revision))
        except ValueError:
            raise ValueError("Revision '{}' is not a valid number".format(revision))
    if epoch is not None:
        try:
            epoch = int(epoch)
        except ValueError:
            raise ValueError("Epoch '{}' is not a valid number".format(epoch))

    return _MatchedVersionPattern(source, base, stage_revision, newer_unmatched_tags, tagged_metadata, epoch)


def _blank(value: Optional[_T], default: _T) -> _T:
    return value if value is not None else default


def _escape_branch(value: str) -> str:
    return re.sub(r"[^a-zA-Z0-9]", "", value)


def _equal_if_set(x: _T, y: Optional[_T], unset: Sequence[Any] = (None,)) -> bool:
    if y in unset:
        return True
    return x == y


def _get_git_version() -> List[int]:
    _, msg = _run_cmd("git version", where=None)
    result = re.search(r"git version (\d+(\.\d+)*)", msg.strip())
    if result is not None:
        parts = result.group(1).split(".")
        return [int(x) for x in parts]
    return []


def _git_log(git_version: List[int]) -> str:
    if git_version < [2, 10]:
        return "git log"
    else:
        return "git -c log.showsignature=false log"


def _detect_vcs(expected_vcs: Optional[Vcs], path: Optional[Path]) -> Vcs:
    checks = OrderedDict(
        [
            (Vcs.Git, "git status"),
            (Vcs.Mercurial, "hg status"),
            (Vcs.Darcs, "darcs log"),
            (Vcs.Subversion, "svn log"),
            (Vcs.Bazaar, "bzr status"),
            (Vcs.Fossil, "fossil status"),
            (Vcs.Pijul, "pijul log"),
        ]
    )

    dubious_ownership_flag = "detected dubious ownership"
    dubious_ownership_error = "Detected Git repository, but failed because of dubious ownership"

    if expected_vcs:
        command = checks[expected_vcs]
        program = command.split()[0]
        if not shutil.which(program):
            raise RuntimeError("Unable to find '{}' program".format(program))
        code, msg = _run_cmd(command, path, codes=[])
        if code != 0:
            if expected_vcs == Vcs.Git and dubious_ownership_flag in msg:
                raise RuntimeError(dubious_ownership_error)
            raise RuntimeError("This does not appear to be a {} project".format(expected_vcs.value.title()))
        return expected_vcs
    else:
        disproven = []
        unavailable = []
        for vcs, command in checks.items():
            if shutil.which(command.split()[0]):
                code, msg = _run_cmd(command, path, codes=[])
                if code == 0:
                    return vcs
                elif vcs == Vcs.Git and dubious_ownership_flag in msg:
                    raise RuntimeError(dubious_ownership_error)
                disproven.append(vcs.name)
            else:
                unavailable.append(vcs.name)

        error_parts = ["Unable to detect version control system."]
        if disproven:
            error_parts.append("Checked: {}.".format(", ".join(disproven)))
        if unavailable:
            error_parts.append("Not installed: {}.".format(", ".join(unavailable)))
        raise RuntimeError(" ".join(error_parts))


def _detect_vcs_from_archival(path: Optional[Path]) -> Optional[Vcs]:
    archival = _find_higher_file(".git_archival.json", path, ".git")
    if archival is not None:
        content = archival.read_text("utf8")
        if "$Format:" not in content:
            return Vcs.Git

    archival = _find_higher_file(".hg_archival.txt", path, ".hg")
    if archival is not None:
        return Vcs.Mercurial

    return None


def _find_higher_file(name: str, start: Optional[Path], limit: Optional[str] = None) -> Optional[Path]:
    """
    :param name: Bare name of a file we'd like to find.
    :param limit: Give up if we find a file/folder with this name.
    :param start: Begin recursing from this folder (default: `.`).
    """

    if start is None:
        start = Path.cwd()
    for level in [start, *start.parents]:
        if (level / name).is_file():
            return level / name
        if limit is not None and (level / limit).exists():
            return None
    return None


class _GitRefInfo:
    def __init__(self, ref: str, commit: str, creatordate: str, committerdate: str, taggerdate: str):
        self.fullref = ref
        self.commit = commit
        self.creatordate = self.normalize_git_dt(creatordate)
        self.committerdate = self.normalize_git_dt(committerdate)
        self.taggerdate = self.normalize_git_dt(taggerdate)
        self.tag_topo_lookup = {}  # type: Mapping[str, int]

    def with_tag_topo_lookup(self, lookup: Mapping[str, int]) -> "_GitRefInfo":
        self.tag_topo_lookup = lookup
        return self

    @staticmethod
    def normalize_git_dt(timestamp: str) -> Optional[dt.datetime]:
        if timestamp == "":
            return None
        else:
            return _parse_git_timestamp_iso_strict(timestamp)

    def __repr__(self):
        return ("_GitRefInfo(ref={!r}, commit={!r}, creatordate={!r}, committerdate={!r}, taggerdate={!r})").format(
            self.fullref, self.commit_offset, self.creatordate, self.committerdate, self.taggerdate
        )

    def best_date(self) -> Optional[dt.datetime]:
        if self.taggerdate is not None:
            return self.taggerdate
        elif self.committerdate is not None:
            return self.committerdate
        else:
            return self.creatordate

    @property
    def commit_offset(self) -> int:
        try:
            return self.tag_topo_lookup[self.fullref]
        except KeyError:
            raise RuntimeError(
                "Unable to determine commit offset for ref {} in data: {}".format(self.fullref, self.tag_topo_lookup)
            )

    @property
    def sort_key(self) -> Tuple[int, Optional[dt.datetime]]:
        return (-self.commit_offset, self.best_date())

    @property
    def ref(self) -> str:
        return self.fullref.replace("refs/tags/", "")

    @staticmethod
    def normalize_tag_ref(ref: str) -> str:
        if ref.startswith("refs/tags/"):
            return ref
        else:
            return "refs/tags/{}".format(ref)

    @staticmethod
    def from_git_tag_topo_order(tag_branch: str, git_version: List[int], path: Optional[Path]) -> Mapping[str, int]:
        cmd = ('{} --simplify-by-decoration --topo-order --decorate=full {} "--format=%H%d"').format(
            _git_log(git_version), tag_branch
        )
        if git_version >= [2, 16]:
            cmd += " --decorate-refs=refs/tags/"
        code, logmsg = _run_cmd(cmd, path)

        filtered_lines = [x for x in logmsg.strip().splitlines(keepends=False) if " (" not in x or "tag: " in x]

        tag_lookup = {}
        for tag_offset, line in enumerate(filtered_lines):
            # lines have the pattern
            # <gitsha1>  (tag: refs/tags/v1.2.0b1, tag: refs/tags/v1.2.0)
            commit, _, tags = line.partition("(")
            commit = commit.strip()
            if tags:
                # remove trailing ')'
                tags = tags[:-1]
                taglist = [tag.strip() for tag in tags.split(", ") if tag.strip().startswith("tag: ")]
                taglist = [tag.split()[-1] for tag in taglist]
                taglist = [_GitRefInfo.normalize_tag_ref(tag) for tag in taglist]
                for tag in taglist:
                    tag_lookup[tag] = tag_offset
        return tag_lookup


@total_ordering
class Version:
    """
    A dynamic version.

    :ivar base: Release segment.
    :vartype base: str
    :ivar stage: Alphabetical part of prerelease segment.
    :vartype stage: Optional[str]
    :ivar revision: Numerical part of prerelease segment.
    :vartype revision: Optional[int]
    :ivar distance: Number of commits since the last tag.
    :vartype distance: int
    :ivar commit: Commit ID.
    :vartype commit: Optional[str]
    :ivar dirty: Whether there are uncommitted changes.
    :vartype dirty: Optional[bool]
    :ivar tagged_metadata: Any metadata segment from the tag itself.
    :vartype tagged_metadata: Optional[str]
    :ivar epoch: Optional PEP 440 epoch.
    :vartype epoch: Optional[int]
    :ivar branch: Name of the current branch.
    :vartype branch: Optional[str]
    :ivar timestamp: Timestamp of the current commit.
    :vartype timestamp: Optional[dt.datetime]
    :ivar concerns: Any concerns regarding the version.
    :vartype concerns: Optional[Set[Concern]]
    :ivar vcs: Version control system from which the version was detected.
    :vartype vcs: Vcs
    """

    def __init__(
        self,
        base: str,
        *,
        stage: Optional[Tuple[str, Optional[int]]] = None,
        distance: int = 0,
        commit: Optional[str] = None,
        dirty: Optional[bool] = None,
        tagged_metadata: Optional[str] = None,
        epoch: Optional[int] = None,
        branch: Optional[str] = None,
        timestamp: Optional[dt.datetime] = None,
        concerns: Optional[Set[Concern]] = None,
        # fmt: off
        vcs: Vcs = Vcs.Any
        # fmt: on
    ) -> None:
        """
        :param base: Release segment, such as 0.1.0.
        :param stage: Pair of release stage (e.g., "a", "alpha", "b", "rc")
            and an optional revision number.
        :param distance: Number of commits since the last tag.
        :param commit: Commit hash/identifier.
        :param dirty: True if the working directory does not match the commit.
        :param epoch: Optional PEP 440 epoch.
        :param branch: Name of the current branch.
        :param timestamp: Timestamp of the current commit.
        :param concerns: Any concerns regarding the version.
        """
        self.base = base
        self.stage = None
        self.revision = None
        if stage is not None:
            self.stage, self.revision = stage
        self.distance = distance
        self.commit = commit
        self.dirty = dirty
        self.tagged_metadata = tagged_metadata
        self.epoch = epoch
        self.branch = branch
        try:
            self.timestamp = timestamp.astimezone(dt.timezone.utc) if timestamp else None
        except ValueError:
            # Will fail for naive timestamps before Python 3.6.
            self.timestamp = timestamp
        self.concerns = concerns or set()
        self.vcs = vcs

        self._matched_tag = None  # type: Optional[str]
        self._newer_unmatched_tags = None  # type: Optional[Sequence[str]]
        self._smart_bumped = False

    def __str__(self) -> str:
        return self.serialize()

    def __repr__(self) -> str:
        return (
            "Version(base={!r}, stage={!r}, revision={!r}, distance={!r}, commit={!r},"
            " dirty={!r}, tagged_metadata={!r}, epoch={!r}, branch={!r}, timestamp={!r})"
        ).format(
            self.base,
            self.stage,
            self.revision,
            self.distance,
            self.commit,
            self.dirty,
            self.tagged_metadata,
            self.epoch,
            self.branch,
            self.timestamp,
        )

    def __eq__(self, other: Any) -> bool:
        if not isinstance(other, Version):
            raise TypeError("Cannot compare Version with type {}".format(other.__class__.__qualname__))
        return (
            self.base == other.base
            and self.stage == other.stage
            and self.revision == other.revision
            and self.distance == other.distance
            and self.commit == other.commit
            and self.dirty == other.dirty
            and self.tagged_metadata == other.tagged_metadata
            and self.epoch == other.epoch
            and self.branch == other.branch
            and self.timestamp == other.timestamp
        )

    def _matches_partial(self, other: "Version") -> bool:
        """
        Compare this version to another version, but ignore None values in the other version.
        Distance is also ignored when `other.distance == 0`.

        :param other: The version to compare to.
        :returns: True if this version equals the other version.
        """
        return (
            _equal_if_set(self.base, other.base)
            and _equal_if_set(self.stage, other.stage)
            and _equal_if_set(self.revision, other.revision)
            and _equal_if_set(self.distance, other.distance, unset=[None, 0])
            and _equal_if_set(self.commit, other.commit)
            and _equal_if_set(self.dirty, other.dirty)
            and _equal_if_set(self.tagged_metadata, other.tagged_metadata)
            and _equal_if_set(self.epoch, other.epoch)
            and _equal_if_set(self.branch, other.branch)
            and _equal_if_set(self.timestamp, other.timestamp)
        )

    def __lt__(self, other: Any) -> bool:
        if not isinstance(other, Version):
            raise TypeError("Cannot compare Version with type {}".format(other.__class__.__qualname__))

        import packaging.version as pv

        return (
            pv.Version(self.base) < pv.Version(other.base)
            and _blank(self.stage, "") < _blank(other.stage, "")
            and _blank(self.revision, 0) < _blank(other.revision, 0)
            and _blank(self.distance, 0) < _blank(other.distance, 0)
            and _blank(self.commit, "") < _blank(other.commit, "")
            and bool(self.dirty) < bool(other.dirty)
            and _blank(self.tagged_metadata, "") < _blank(other.tagged_metadata, "")
            and _blank(self.epoch, 0) < _blank(other.epoch, 0)
            and _blank(self.branch, "") < _blank(other.branch, "")
            and _blank(self.timestamp, dt.datetime(0, 0, 0, 0, 0, 0))
            < _blank(other.timestamp, dt.datetime(0, 0, 0, 0, 0, 0))
        )

    def serialize(
        self,
        metadata: Optional[bool] = None,
        dirty: bool = False,
        format: Optional[Union[str, Callable[["Version"], str]]] = None,
        style: Optional[Style] = None,
        bump: bool = False,
        tagged_metadata: bool = False,
    ) -> str:
        """
        Create a string from the version info.

        :param metadata: Metadata (commit ID, dirty flag) is normally included
            in the metadata/local version part only if the distance is nonzero.
            Set this to True to always include metadata even with no distance,
            or set it to False to always exclude it.
            This is ignored when `format` is used.
        :param dirty: Set this to True to include a dirty flag in the
            metadata if applicable. Inert when metadata=False.
            This is ignored when `format` is used.
        :param format: Custom output format. It is either a formatted string or a
            callback. In the string you can use substitutions, such as "v{base}"
            to get "v0.1.0". Available substitutions:

            * {base}
            * {stage}
            * {revision}
            * {distance}
            * {commit}
            * {dirty} which expands to either "dirty" or "clean"
            * {tagged_metadata}
            * {epoch}
            * {branch}
            * {branch_escaped} which omits any non-letter/number characters
            * {timestamp} which expands to YYYYmmddHHMMSS as UTC
            * {major} (first part of `base` split on `.`, or 0)
            * {minor} (second part of `base` split on `.`, or 0)
            * {patch} (third part of `base` split on `.`, or 0)
        :param style: Built-in output formats. Will default to PEP 440 if not
            set and no custom format given. If you specify both a style and a
            custom format, then the format will be validated against the
            style's rules.
        :param bump: If true, increment the last part of the `base` by 1,
            unless `stage` is set, in which case either increment `revision`
            by 1 or set it to a default of 2 if there was no revision.
            Does nothing when on a commit with a version tag.
        :param tagged_metadata: If true, insert the `tagged_metadata` in the
            version as the first part of the metadata segment.
            This is ignored when `format` is used.
        :returns: Serialized version.
        """
        base = self.base
        revision = self.revision
        if bump:
            bumped = self.bump(smart=True)
            base = bumped.base
            revision = bumped.revision

        if format is not None:
            if callable(format):
                new_version = copy.deepcopy(self)
                new_version.base = base
                new_version.revision = revision
                out = format(new_version)
            else:
                try:
                    base_parts = base.split(".")

                    out = format.format(
                        base=base,
                        stage=_blank(self.stage, ""),
                        revision=_blank(revision, ""),
                        distance=_blank(self.distance, ""),
                        commit=_blank(self.commit, ""),
                        tagged_metadata=_blank(self.tagged_metadata, ""),
                        dirty="dirty" if self.dirty else "clean",
                        epoch=_blank(self.epoch, ""),
                        branch=_blank(self.branch, ""),
                        branch_escaped=_escape_branch(_blank(self.branch, "")),
                        timestamp=self.timestamp.strftime("%Y%m%d%H%M%S") if self.timestamp else "",
                        major=base_parts[0] if len(base_parts) > 0 else "0",
                        minor=base_parts[1] if len(base_parts) > 1 else "0",
                        patch=base_parts[2] if len(base_parts) > 2 else "0",
                    )
                except KeyError as e:
                    raise KeyError("Format contains invalid placeholder: {}".format(e))
                except ValueError as e:
                    raise ValueError("Format is invalid: {}".format(e))
            if style is not None:
                check_version(out, style)
            return out

        if style is None:
            style = Style.Pep440
        out = ""

        meta_parts = []
        if metadata is not False:
            if tagged_metadata and self.tagged_metadata:
                meta_parts.append(self.tagged_metadata)
            if (metadata or self.distance > 0) and self.commit is not None:
                meta_parts.append(self.commit)
            if dirty and self.dirty:
                meta_parts.append("dirty")

        pre_parts = []
        if self.stage is not None:
            pre_parts.append(self.stage)
            if revision is not None:
                pre_parts.append(str(revision))
        if self.distance > 0:
            pre_parts.append("pre" if bump or self._smart_bumped else "post")
            pre_parts.append(str(self.distance))

        if style == Style.Pep440:
            stage = self.stage
            post = None
            dev = None
            if stage == "post":
                stage = None
                post = revision
            elif stage == "dev":
                stage = None
                dev = revision
            if self.distance > 0:
                if bump or self._smart_bumped:
                    if dev is None:
                        dev = self.distance
                    else:
                        dev += self.distance
                else:
                    if post is None and dev is None:
                        post = self.distance
                        dev = 0
                    elif dev is None:
                        dev = self.distance
                    else:
                        dev += self.distance

            out = serialize_pep440(
                base,
                stage=stage,
                revision=revision,
                post=post,
                dev=dev,
                metadata=meta_parts,
                epoch=self.epoch,
            )
        elif style == Style.SemVer:
            out = serialize_semver(base, pre=pre_parts, metadata=meta_parts)
        elif style == Style.Pvp:
            out = serialize_pvp(base, metadata=[*pre_parts, *meta_parts])

        check_version(out, style)
        return out

    @classmethod
    def parse(cls, version: str, pattern: Union[str, Pattern] = Pattern.Default) -> "Version":
        """
        Attempt to parse a string into a Version instance.

        This uses inexact heuristics, so its output may vary slightly between
        releases. Consider this a "best effort" conversion.

        :param version: Full version, such as 0.3.0a3+d7.gb6a9020.dirty.
        :param pattern: Regular expression matched against the version.
            Refer to `from_any_vcs` for more info.
        :returns: Parsed version.
        """
        normalized = version
        if not version.startswith("v") and pattern in [VERSION_SOURCE_PATTERN, Pattern.Default]:
            normalized = "v{}".format(version)

        failed = False
        try:
            matched_pattern = _match_version_pattern(pattern, [normalized], True, strict=True, pattern_prefix=None)
        except ValueError:
            failed = True

        if failed or matched_pattern is None:
            replaced = re.sub(r"(\.post(\d+)\.dev\d+)", r".dev\2", version, 1)
            if replaced != version:
                alt = Version.parse(replaced, pattern)
                if alt.base != replaced:
                    return alt

            return cls(version)

        base = matched_pattern.base
        stage = matched_pattern.stage_revision
        distance = None
        commit = None
        dirty = None
        tagged_metadata = matched_pattern.tagged_metadata
        epoch = matched_pattern.epoch

        if tagged_metadata:
            pop = []  # type: list
            parts = tagged_metadata.split(".")

            for i, value in enumerate(parts):
                if dirty is None:
                    if value == "dirty":
                        dirty = True
                        pop.append(i)
                        continue
                    elif value == "clean":
                        dirty = False
                        pop.append(i)
                        continue
                if distance is None:
                    match = re.match(r"d?(\d+)", value)
                    if match:
                        distance = int(match.group(1))
                        pop.append(i)
                        continue
                if commit is None:
                    match = re.match(r"g?([\da-z]+)", value)
                    if match:
                        commit = match.group(1)
                        pop.append(i)
                        continue

            for i in reversed(sorted(pop)):
                parts.pop(i)

            tagged_metadata = ".".join(parts)

        if distance is None:
            distance = 0
        if tagged_metadata is not None and tagged_metadata.strip() == "":
            tagged_metadata = None

        if stage is not None and stage[0] == "dev" and stage[1] is not None:
            distance += stage[1]
            stage = None

        return cls(
            base,
            stage=stage,
            distance=distance,
            commit=commit,
            dirty=dirty,
            tagged_metadata=tagged_metadata,
            epoch=epoch,
        )

    def bump(self, index: int = -1, increment: int = 1, smart: bool = False) -> "Version":
        """
        Increment the version.

        The base is bumped unless there is a stage defined, in which case,
        the revision is bumped instead.

        :param index: Numerical position to increment in the base.
            This follows Python indexing rules, so positive numbers start from
            the left side and count up from 0, while negative numbers start from
            the right side and count down from -1.
            Only has an effect when the base is bumped.
        :param increment: By how much to increment the relevant position.
        :param smart: If true, only bump when distance is not 0.
            This will also make `Version.serialize()` use pre-release formatting automatically,
            like calling `Version.serialize(bump=True)`.
        :returns: Bumped version.
        """
        bumped = copy.deepcopy(self)

        if smart:
            if bumped.distance == 0:
                return bumped
            bumped._smart_bumped = True

        if bumped.stage is None:
            bumped.base = bump_version(bumped.base, index, increment)
        else:
            if bumped.revision is None:
                bumped.revision = 2
            else:
                bumped.revision += increment
        return bumped

    @classmethod
    def _fallback(
        cls,
        strict: bool,
        *,
        stage: Optional[Tuple[str, Optional[int]]] = None,
        distance: int = 0,
        commit: Optional[str] = None,
        dirty: Optional[bool] = None,
        tagged_metadata: Optional[str] = None,
        epoch: Optional[int] = None,
        branch: Optional[str] = None,
        timestamp: Optional[dt.datetime] = None,
        concerns: Optional[Set[Concern]] = None,
        # fmt: off
        vcs: Vcs = Vcs.Any
        # fmt: on
    ):
        if strict:
            raise RuntimeError("No tags available and fallbacks disabled by strict mode")
        return cls(
            "0.0.0",
            stage=stage,
            distance=distance,
            commit=commit,
            dirty=dirty,
            tagged_metadata=tagged_metadata,
            epoch=epoch,
            branch=branch,
            timestamp=timestamp,
            concerns=concerns,
            vcs=vcs,
        )

    @classmethod
    def from_git(
        cls,
        pattern: Union[str, Pattern] = Pattern.Default,
        latest_tag: bool = False,
        tag_branch: Optional[str] = None,
        full_commit: bool = False,
        strict: bool = False,
        path: Optional[Path] = None,
        pattern_prefix: Optional[str] = None,
        ignore_untracked: bool = False,
        commit_length: Optional[int] = None,
    ) -> "Version":
        r"""
        Determine a version based on Git tags.

        :param pattern: Regular expression matched against the version source.
            Refer to `from_any_vcs` for more info.
        :param latest_tag: If true, only inspect the latest tag on the latest
            tagged commit for a pattern match. If false, keep looking at tags
            until there is a match.
        :param tag_branch: Branch on which to find tags, if different than the
            current branch.
        :param full_commit: Get the full commit hash instead of the short form.
        :param strict: Elevate warnings to errors.
            When there are no tags, fail instead of falling back to 0.0.0.
        :param path: Directory to inspect, if not the current working directory.
        :param pattern_prefix: Insert this after the pattern's start anchor (`^`).
        :param ignore_untracked:
            Ignore untracked files when determining whether the repository is dirty.
        :param commit_length:
            Use this many characters from the start of the full commit hash.
        :returns: Detected version.
        """
        vcs = Vcs.Git
        full_commit = full_commit or commit_length is not None

        archival = _find_higher_file(".git_archival.json", path, ".git")
        if archival is not None:
            content = archival.read_text("utf8")
            if "$Format:" not in content:
                data = json.loads(content)

                if full_commit:
                    commit = data.get("hash-full")
                else:
                    commit = data.get("hash-short")

                if commit is not None:
                    commit = commit[:commit_length]

                timestamp = None
                raw_timestamp = data.get("timestamp")
                if raw_timestamp:
                    timestamp = _parse_git_timestamp_iso_strict(raw_timestamp)

                branch = None
                refs = data.get("refs")
                if refs:
                    parts = refs.split(" -> ")
                    if len(parts) == 2:
                        branch = parts[1].split(", ")[0]

                tag = None
                distance = 0
                dirty = None
                describe = data.get("describe")
                if describe:
                    if describe.endswith("-dirty"):
                        dirty = True
                        describe = describe[:-6]
                    else:
                        dirty = False
                    parts = describe.rsplit("-", 2)
                    tag = parts[0]
                    if len(parts) > 1:
                        distance = int(parts[1])

                if tag is None:
                    return cls._fallback(
                        strict,
                        distance=distance,
                        commit=commit,
                        dirty=dirty,
                        branch=branch,
                        timestamp=timestamp,
                        vcs=vcs,
                    )

                matched_pattern = _match_version_pattern(pattern, [tag], latest_tag, strict, pattern_prefix)
                if matched_pattern is None:
                    return cls._fallback(
                        strict,
                        distance=distance,
                        commit=commit,
                        dirty=dirty,
                        branch=branch,
                        timestamp=timestamp,
                        vcs=vcs,
                    )
                tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern

                version = cls(
                    base,
                    stage=stage,
                    distance=distance,
                    commit=commit,
                    dirty=dirty,
                    tagged_metadata=tagged_metadata,
                    epoch=epoch,
                    branch=branch,
                    timestamp=timestamp,
                    vcs=vcs,
                )
                version._matched_tag = tag
                version._newer_unmatched_tags = unmatched
                return version

        _detect_vcs(vcs, path)
        concerns = set()  # type: Set[Concern]
        if tag_branch is None:
            tag_branch = "HEAD"

        git_version = _get_git_version()

        if git_version < [2, 15]:
            flag_file = _find_higher_file(".git/shallow", path)
            if flag_file:
                concerns.add(Concern.ShallowRepository)
        else:
            code, msg = _run_cmd("git rev-parse --is-shallow-repository", path)
            if msg.strip() == "true":
                concerns.add(Concern.ShallowRepository)

        if strict and concerns:
            raise RuntimeError("\n".join(x.message() for x in concerns))

        code, msg = _run_cmd("git symbolic-ref --short HEAD", path, codes=[0, 128])
        if code == 128:
            branch = None
        else:
            branch = msg

        code, msg = _run_cmd(
            '{} -n 1 --format="format:{}"'.format(_git_log(git_version), "%H" if full_commit else "%h"),
            path,
            codes=[0, 128],
        )
        if code == 128:
            return cls._fallback(strict, distance=0, dirty=True, branch=branch, concerns=concerns, vcs=vcs)
        commit = msg[:commit_length]

        timestamp = None
        if git_version < [2, 2]:
            code, msg = _run_cmd('{} -n 1 --pretty=format:"%ci"'.format(_git_log(git_version)), path)
            timestamp = _parse_git_timestamp_iso(msg)
        else:
            code, msg = _run_cmd('{} -n 1 --pretty=format:"%cI"'.format(_git_log(git_version)), path)
            timestamp = _parse_git_timestamp_iso_strict(msg)

        code, msg = _run_cmd("git describe --always --dirty", path)
        dirty = msg.endswith("-dirty")

        if not dirty and not ignore_untracked:
            code, msg = _run_cmd("git status --porcelain", path)
            if msg.strip() != "":
                dirty = True

        if git_version < [2, 7]:
            code, msg = _run_cmd('git for-each-ref "refs/tags/**" --format "%(refname)" --sort -creatordate', path)
            if not msg:
                try:
                    code, msg = _run_cmd("git rev-list --count HEAD", path)
                    distance = int(msg)
                except Exception:
                    distance = 0
                return cls._fallback(
                    strict,
                    distance=distance,
                    commit=commit,
                    dirty=dirty,
                    branch=branch,
                    timestamp=timestamp,
                    concerns=concerns,
                    vcs=vcs,
                )
            tags = [line.replace("refs/tags/", "") for line in msg.splitlines()]
            matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)
        else:
            code, msg = _run_cmd(
                'git for-each-ref "refs/tags/**" --merged {}'.format(tag_branch) + ' --format "%(refname)'
                "@{%(objectname)"
                "@{%(creatordate:iso-strict)"
                "@{%(*committerdate:iso-strict)"
                "@{%(taggerdate:iso-strict)"
                '"',
                path,
            )
            if not msg:
                try:
                    code, msg = _run_cmd("git rev-list --count HEAD", path)
                    distance = int(msg)
                except Exception:
                    distance = 0
                return cls._fallback(
                    strict,
                    distance=distance,
                    commit=commit,
                    dirty=dirty,
                    branch=branch,
                    timestamp=timestamp,
                    concerns=concerns,
                    vcs=vcs,
                )

            detailed_tags = []  # type: List[_GitRefInfo]
            tag_topo_lookup = _GitRefInfo.from_git_tag_topo_order(tag_branch, git_version, path)

            for line in msg.strip().splitlines():
                parts = line.split("@{")
                if len(parts) != 5:
                    continue
                detailed_tags.append(_GitRefInfo(*parts).with_tag_topo_lookup(tag_topo_lookup))

            tags = [t.ref for t in sorted(detailed_tags, key=lambda x: x.sort_key, reverse=True)]
            matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)

        if matched_pattern is None:
            try:
                code, msg = _run_cmd("git rev-list --count HEAD", path)
                distance = int(msg)
            except Exception:
                distance = 0

            return cls._fallback(
                strict,
                distance=distance,
                commit=commit,
                dirty=dirty,
                branch=branch,
                timestamp=timestamp,
                concerns=concerns,
                vcs=vcs,
            )
        tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern

        code, msg = _run_cmd("git rev-list --count refs/tags/{}..HEAD".format(tag), path)
        distance = int(msg)

        version = cls(
            base,
            stage=stage,
            distance=distance,
            commit=commit,
            dirty=dirty,
            tagged_metadata=tagged_metadata,
            epoch=epoch,
            branch=branch,
            timestamp=timestamp,
            concerns=concerns,
            vcs=vcs,
        )
        version._matched_tag = tag
        version._newer_unmatched_tags = unmatched
        return version

    @classmethod
    def from_mercurial(
        cls,
        pattern: Union[str, Pattern] = Pattern.Default,
        latest_tag: bool = False,
        full_commit: bool = False,
        strict: bool = False,
        path: Optional[Path] = None,
        pattern_prefix: Optional[str] = None,
        commit_length: Optional[int] = None,
    ) -> "Version":
        r"""
        Determine a version based on Mercurial tags.

        :param pattern: Regular expression matched against the version source.
            Refer to `from_any_vcs` for more info.
        :param latest_tag: If true, only inspect the latest tag on the latest
            tagged commit for a pattern match. If false, keep looking at tags
            until there is a match.
        :param full_commit: Get the full commit hash instead of the short form.
        :param strict: Elevate warnings to errors.
            When there are no tags, fail instead of falling back to 0.0.0.
        :param path: Directory to inspect, if not the current working directory.
        :param pattern_prefix: Insert this after the pattern's start anchor (`^`).
        :param commit_length:
            Use this many characters from the start of the full commit hash.
        :returns: Detected version.
        """
        vcs = Vcs.Mercurial
        full_commit = full_commit or commit_length is not None

        archival = _find_higher_file(".hg_archival.txt", path, ".hg")
        if archival is not None:
            content = archival.read_text("utf8")
            data = {}
            for line in content.splitlines():
                parts = line.split(":", 1)
                if len(parts) != 2:
                    continue
                data[parts[0].strip()] = parts[1].strip()

            tag = data.get("latesttag")
            # The distance is 1 on a new repo or on a tagged commit.
            distance = int(data.get("latesttagdistance", 1)) - 1
            commit = data.get("node")
            if commit is not None:
                commit = commit[:commit_length]
            branch = data.get("branch")

            if tag is None or tag == "null":
                return cls._fallback(strict, distance=distance, commit=commit, branch=branch, vcs=vcs)

            all_tags_file = _find_higher_file(".hgtags", path, ".hg")
            if all_tags_file is None:
                all_tags = [tag]
            else:
                all_tags = []
                all_tags_content = all_tags_file.read_text("utf8")
                for line in reversed(all_tags_content.splitlines()):
                    parts = line.split(" ", 1)
                    if len(parts) != 2:
                        continue
                    all_tags.append(parts[1])

            matched_pattern = _match_version_pattern(pattern, all_tags, latest_tag, strict, pattern_prefix)
            if matched_pattern is None:
                return cls._fallback(
                    strict,
                    distance=distance,
                    commit=commit,
                    branch=branch,
                    vcs=vcs,
                )
            tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern

            version = cls(
                base,
                stage=stage,
                distance=distance,
                commit=commit,
                tagged_metadata=tagged_metadata,
                epoch=epoch,
                branch=branch,
                vcs=vcs,
            )
            version._matched_tag = tag
            version._newer_unmatched_tags = unmatched
            return version

        _detect_vcs(vcs, path)

        code, msg = _run_cmd("hg summary", path)
        dirty = "commit: (clean)" not in msg.splitlines()

        code, msg = _run_cmd("hg branch", path)
        branch = msg

        code, msg = _run_cmd('hg id --template "{}"'.format("{id}" if full_commit else "{id|short}"), path)
        commit = msg[:commit_length] if set(msg) != {"0"} else None

        code, msg = _run_cmd('hg log --limit 1 --template "{date|rfc3339date}"', path)
        timestamp = _parse_git_timestamp_iso_strict(msg) if msg != "" else None

        code, msg = _run_cmd(
            'hg log -r "sort(tag(){}, -rev)" --template "{{join(tags, \':\')}}\\n"'.format(
                " and ancestors({})".format(commit) if commit is not None else ""
            ),
            path,
        )
        if not msg:
            try:
                code, msg = _run_cmd("hg id --num --rev tip", path)
                distance = int(msg) + 1
            except Exception:
                distance = 0
            return cls._fallback(
                strict,
                distance=distance,
                commit=commit,
                dirty=dirty,
                branch=branch,
                timestamp=timestamp,
                vcs=vcs,
            )
        tags = [tag for tags in [line.split(":") for line in msg.splitlines()] for tag in tags]

        matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)
        if matched_pattern is None:
            return cls._fallback(
                strict,
                distance=distance,
                commit=commit,
                dirty=dirty,
                branch=branch,
                timestamp=timestamp,
                vcs=vcs,
            )
        tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern

        code, msg = _run_cmd('hg log -r "{0}::{1} - {0}" --template "."'.format(tag, commit), path)
        # The tag itself is in the list, so offset by 1.
        distance = max(len(msg) - 1, 0)

        version = cls(
            base,
            stage=stage,
            distance=distance,
            commit=commit,
            dirty=dirty,
            tagged_metadata=tagged_metadata,
            epoch=epoch,
            branch=branch,
            timestamp=timestamp,
            vcs=vcs,
        )
        version._matched_tag = tag
        version._newer_unmatched_tags = unmatched
        return version

    @classmethod
    def from_darcs(
        cls,
        pattern: Union[str, Pattern] = Pattern.Default,
        latest_tag: bool = False,
        strict: bool = False,
        path: Optional[Path] = None,
        pattern_prefix: Optional[str] = None,
        commit_length: Optional[int] = None,
    ) -> "Version":
        r"""
        Determine a version based on Darcs tags.

        :param pattern: Regular expression matched against the version source.
            Refer to `from_any_vcs` for more info.
        :param latest_tag: If true, only inspect the latest tag on the latest
            tagged commit for a pattern match. If false, keep looking at tags
            until there is a match.
        :param strict: Elevate warnings to errors.
            When there are no tags, fail instead of falling back to 0.0.0.
        :param path: Directory to inspect, if not the current working directory.
        :param pattern_prefix: Insert this after the pattern's start anchor (`^`).
        :param commit_length:
            Use this many characters from the start of the full commit hash.
        :returns: Detected version.
        """
        vcs = Vcs.Darcs
        _detect_vcs(vcs, path)

        code, msg = _run_cmd("darcs status", path, codes=[0, 1])
        dirty = msg != "No changes!"

        code, msg = _run_cmd("darcs log --last 1 --xml-output", path)
        root = ElementTree.fromstring(msg)
        if len(root) == 0:
            commit = None
            timestamp = None
        else:
            commit = root[0].attrib["hash"]
            if commit is not None:
                commit = commit[:commit_length]
            timestamp = dt.datetime.strptime(root[0].attrib["date"] + "+0000", "%Y%m%d%H%M%S%z")

        code, msg = _run_cmd("darcs show tags", path)
        if not msg:
            try:
                code, msg = _run_cmd("darcs log --count", path)
                distance = int(msg)
            except Exception:
                distance = 0
            return cls._fallback(strict, distance=distance, commit=commit, dirty=dirty, timestamp=timestamp, vcs=vcs)
        tags = msg.splitlines()

        matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)
        if matched_pattern is None:
            return cls._fallback(
                strict,
                distance=distance,
                commit=commit,
                dirty=dirty,
                timestamp=timestamp,
                vcs=vcs,
            )
        tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern

        code, msg = _run_cmd("darcs log --from-tag {} --count".format(tag), path)
        # The tag itself is in the list, so offset by 1.
        distance = int(msg) - 1

        version = cls(
            base,
            stage=stage,
            distance=distance,
            commit=commit,
            dirty=dirty,
            tagged_metadata=tagged_metadata,
            epoch=epoch,
            timestamp=timestamp,
            vcs=vcs,
        )
        version._matched_tag = tag
        version._newer_unmatched_tags = unmatched
        return version

    @classmethod
    def from_subversion(
        cls,
        pattern: Union[str, Pattern] = Pattern.Default,
        latest_tag: bool = False,
        tag_dir: str = "tags",
        strict: bool = False,
        path: Optional[Path] = None,
        pattern_prefix: Optional[str] = None,
        commit_length: Optional[int] = None,
    ) -> "Version":
        r"""
        Determine a version based on Subversion tags.

        :param pattern: Regular expression matched against the version source.
            Refer to `from_any_vcs` for more info.
        :param latest_tag: If true, only inspect the latest tag on the latest
            tagged commit for a pattern match. If false, keep looking at tags
            until there is a match.
        :param tag_dir: Location of tags relative to the root.
        :param strict: Elevate warnings to errors.
            When there are no tags, fail instead of falling back to 0.0.0.
        :param path: Directory to inspect, if not the current working directory.
        :param pattern_prefix: Insert this after the pattern's start anchor (`^`).
        :param commit_length:
            Use this many characters from the start of the full commit hash.
        :returns: Detected version.
        """
        vcs = Vcs.Subversion
        _detect_vcs(vcs, path)

        tag_dir = tag_dir.strip("/")

        code, msg = _run_cmd("svn status", path)
        dirty = bool(msg)

        code, msg = _run_cmd("svn info --show-item repos-root-url", path)
        url = msg.strip("/")

        code, msg = _run_cmd("svn info --show-item revision", path)
        if not msg or msg == "0":
            commit = None
        else:
            commit = msg[:commit_length]

        timestamp = None
        if commit:
            code, msg = _run_cmd("svn info --show-item last-changed-date", path)
            timestamp = _parse_timestamp(msg)

        if not commit:
            return cls._fallback(strict, distance=0, commit=commit, dirty=dirty, timestamp=timestamp, vcs=vcs)
        code, msg = _run_cmd('svn ls -v -r {} "{}/{}"'.format(commit, url, tag_dir), path)
        lines = [line.split(maxsplit=5) for line in msg.splitlines()[1:]]
        tags_to_revs = {line[-1].strip("/"): int(line[0]) for line in lines}
        if not tags_to_revs:
            try:
                distance = int(commit)
            except Exception:
                distance = 0
            return cls._fallback(strict, distance=distance, commit=commit, dirty=dirty, timestamp=timestamp, vcs=vcs)
        tags_to_sources_revs = {}
        for tag, rev in tags_to_revs.items():
            code, msg = _run_cmd('svn log -v "{}/{}/{}" --stop-on-copy'.format(url, tag_dir, tag), path)
            for line in msg.splitlines():
                match = re.search(r"A /{}/{} \(from .+?:(\d+)\)".format(tag_dir, tag), line)
                if match:
                    source = int(match.group(1))
                    tags_to_sources_revs[tag] = (source, rev)
        tags = sorted(tags_to_sources_revs, key=lambda x: tags_to_sources_revs[x], reverse=True)

        matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)
        if matched_pattern is None:
            return cls._fallback(
                strict,
                distance=distance,
                commit=commit,
                dirty=dirty,
                timestamp=timestamp,
                vcs=vcs,
            )
        tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern

        source, rev = tags_to_sources_revs[tag]
        # The tag itself is in the list, so offset by 1.
        distance = int(commit) - 1 - source

        version = cls(
            base,
            stage=stage,
            distance=distance,
            commit=commit,
            dirty=dirty,
            tagged_metadata=tagged_metadata,
            epoch=epoch,
            timestamp=timestamp,
            vcs=vcs,
        )
        version._matched_tag = tag
        version._newer_unmatched_tags = unmatched
        return version

    @classmethod
    def from_bazaar(
        cls,
        pattern: Union[str, Pattern] = Pattern.Default,
        latest_tag: bool = False,
        strict: bool = False,
        path: Optional[Path] = None,
        pattern_prefix: Optional[str] = None,
        commit_length: Optional[int] = None,
    ) -> "Version":
        r"""
        Determine a version based on Bazaar tags.

        :param pattern: Regular expression matched against the version source.
            Refer to `from_any_vcs` for more info.
        :param latest_tag: If true, only inspect the latest tag on the latest
            tagged commit for a pattern match. If false, keep looking at tags
            until there is a match.
        :param strict: Elevate warnings to errors.
            When there are no tags, fail instead of falling back to 0.0.0.
        :param path: Directory to inspect, if not the current working directory.
        :param pattern_prefix: Insert this after the pattern's start anchor (`^`).
        :param commit_length:
            Use this many characters from the start of the full commit hash.
        :returns: Detected version.
        """
        vcs = Vcs.Bazaar
        _detect_vcs(vcs, path)

        code, msg = _run_cmd("bzr status", path)
        dirty = msg != ""

        code, msg = _run_cmd("bzr log --limit 1", path)
        commit = None
        branch = None
        timestamp = None
        for line in msg.splitlines():
            info = line.split("revno: ", maxsplit=1)
            if len(info) == 2:
                commit = info[1][:commit_length]

            info = line.split("branch nick: ", maxsplit=1)
            if len(info) == 2:
                branch = info[1]

            info = line.split("timestamp: ", maxsplit=1)
            if len(info) == 2:
                timestamp = dt.datetime.strptime(info[1], "%a %Y-%m-%d %H:%M:%S %z")

        code, msg = _run_cmd("bzr tags", path)
        if not msg or not commit:
            try:
                distance = int(commit) if commit is not None else 0
            except Exception:
                distance = 0
            return cls._fallback(
                strict,
                distance=distance,
                commit=commit,
                dirty=dirty,
                branch=branch,
                timestamp=timestamp,
                vcs=vcs,
            )
        tags_to_revs = {line.split()[0]: int(line.split()[1]) for line in msg.splitlines() if line.split()[1] != "?"}
        tags = [x[1] for x in sorted([(v, k) for k, v in tags_to_revs.items()], reverse=True)]

        matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)
        if matched_pattern is None:
            return cls._fallback(
                strict,
                distance=distance,
                commit=commit,
                dirty=dirty,
                branch=branch,
                timestamp=timestamp,
                vcs=vcs,
            )
        tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern

        distance = int(commit) - tags_to_revs[tag]

        version = cls(
            base,
            stage=stage,
            distance=distance,
            commit=commit,
            dirty=dirty,
            tagged_metadata=tagged_metadata,
            epoch=epoch,
            branch=branch,
            timestamp=timestamp,
            vcs=vcs,
        )
        version._matched_tag = tag
        version._newer_unmatched_tags = unmatched
        return version

    @classmethod
    def from_fossil(
        cls,
        pattern: Union[str, Pattern] = Pattern.Default,
        latest_tag: bool = False,
        strict: bool = False,
        path: Optional[Path] = None,
        pattern_prefix: Optional[str] = None,
        commit_length: Optional[int] = None,
    ) -> "Version":
        r"""
        Determine a version based on Fossil tags.

        :param pattern: Regular expression matched against the version source.
            Refer to `from_any_vcs` for more info.
        :param latest_tag: If true, only inspect the latest tag for a pattern
            match. If false, keep looking at tags until there is a match.
        :param strict: Elevate warnings to errors.
            When there are no tags, fail instead of falling back to 0.0.0.
        :param path: Directory to inspect, if not the current working directory.
        :param pattern_prefix: Insert this after the pattern's start anchor (`^`).
        :param commit_length:
            Use this many characters from the start of the full commit hash.
        :returns: Detected version.
        """
        vcs = Vcs.Fossil
        _detect_vcs(vcs, path)

        code, msg = _run_cmd("fossil changes --differ", path)
        dirty = bool(msg)

        code, msg = _run_cmd("fossil branch current", path)
        branch = msg

        code, msg = _run_cmd("fossil sql \"SELECT value FROM vvar WHERE name = 'checkout-hash' LIMIT 1\"", path)
        commit = msg.strip("'")[:commit_length]

        code, msg = _run_cmd(
            'fossil sql "'
            "SELECT DATETIME(mtime) FROM event JOIN blob ON event.objid=blob.rid WHERE type = 'ci'"
            " AND uuid = (SELECT value FROM vvar WHERE name = 'checkout-hash' LIMIT 1) LIMIT 1\"",
            path,
        )
        timestamp = dt.datetime.strptime(msg.strip("'") + "+0000", "%Y-%m-%d %H:%M:%S%z")

        code, msg = _run_cmd("fossil sql \"SELECT count() FROM event WHERE type = 'ci'\"", path)
        # The repository creation itself counts as a commit.
        total_commits = int(msg) - 1
        if total_commits <= 0:
            return cls._fallback(
                strict,
                distance=0,
                commit=commit,
                dirty=dirty,
                branch=branch,
                timestamp=timestamp,
                vcs=vcs,
            )

        # Based on `compute_direct_ancestors` from descendants.c in the
        # Fossil source code:
        query = """
            CREATE TEMP TABLE IF NOT EXISTS
                dunamai_ancestor(
                    rid INTEGER UNIQUE NOT NULL,
                    generation INTEGER PRIMARY KEY
                );
            DELETE FROM dunamai_ancestor;
            WITH RECURSIVE g(x, i)
                AS (
                    VALUES((SELECT value FROM vvar WHERE name = 'checkout' LIMIT 1), 1)
                    UNION ALL
                    SELECT plink.pid, g.i + 1 FROM plink, g
                    WHERE plink.cid = g.x AND plink.isprim
                )
                INSERT INTO dunamai_ancestor(rid, generation) SELECT x, i FROM g;
            SELECT tag.tagname, dunamai_ancestor.generation
                FROM tag
                JOIN tagxref ON tag.tagid = tagxref.tagid
                JOIN event ON tagxref.origid = event.objid
                JOIN dunamai_ancestor ON tagxref.origid = dunamai_ancestor.rid
                WHERE tagxref.tagtype = 1
                ORDER BY event.mtime DESC, tagxref.mtime DESC;
        """
        code, msg = _run_cmd('fossil sql "{}"'.format(" ".join(query.splitlines())), path)
        if not msg:
            try:
                distance = int(total_commits)
            except Exception:
                distance = 0
            return cls._fallback(
                strict,
                distance=distance,
                commit=commit,
                dirty=dirty,
                branch=branch,
                timestamp=timestamp,
                vcs=vcs,
            )

        tags_to_distance = [
            (line.rsplit(",", 1)[0][5:-1], int(line.rsplit(",", 1)[1]) - 1) for line in msg.splitlines()
        ]

        matched_pattern = _match_version_pattern(
            pattern, [t for t, d in tags_to_distance], latest_tag, strict, pattern_prefix
        )
        if matched_pattern is None:
            return cls._fallback(
                strict,
                distance=distance,
                commit=commit,
                dirty=dirty,
                branch=branch,
                timestamp=timestamp,
                vcs=vcs,
            )
        tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern

        distance = dict(tags_to_distance)[tag]

        version = cls(
            base,
            stage=stage,
            distance=distance,
            commit=commit,
            dirty=dirty,
            tagged_metadata=tagged_metadata,
            epoch=epoch,
            branch=branch,
            timestamp=timestamp,
            vcs=vcs,
        )
        version._matched_tag = tag
        version._newer_unmatched_tags = unmatched
        return version

    @classmethod
    def from_pijul(
        cls,
        pattern: Union[str, Pattern] = Pattern.Default,
        latest_tag: bool = False,
        strict: bool = False,
        path: Optional[Path] = None,
        pattern_prefix: Optional[str] = None,
        commit_length: Optional[int] = None,
    ) -> "Version":
        r"""
        Determine a version based on Pijul tags.

        :param pattern: Regular expression matched against the version source.
            Refer to `from_any_vcs` for more info.
        :param latest_tag: If true, only inspect the latest tag on the latest
            tagged commit for a pattern match. If false, keep looking at tags
            until there is a match.
        :param strict: Elevate warnings to errors.
            When there are no tags, fail instead of falling back to 0.0.0.
        :param path: Directory to inspect, if not the current working directory.
        :param pattern_prefix: Insert this after the pattern's start anchor (`^`).
        :param commit_length:
            Use this many characters from the start of the full commit hash.
        :returns: Detected version.
        """
        vcs = Vcs.Pijul
        _detect_vcs(vcs, path)

        code, msg = _run_cmd("pijul diff --short", path)
        dirty = msg.strip() != ""

        code, msg = _run_cmd("pijul channel", path)
        branch = "main"
        for line in msg.splitlines():
            if line.startswith("* "):
                branch = line.split("* ", 1)[1]
                break

        code, msg = _run_cmd("pijul log --limit 1 --output-format json", path)
        limited_commits = json.loads(msg)
        if len(limited_commits) == 0:
            return cls._fallback(strict, dirty=dirty, branch=branch, vcs=vcs)

        commit = limited_commits[0]["hash"][:commit_length]
        timestamp = _parse_timestamp(limited_commits[0]["timestamp"])

        code, msg = _run_cmd("pijul log --output-format json", path)
        channel_commits = json.loads(msg)

        code, msg = _run_cmd("pijul tag", path)
        if not msg:
            # The channel creation is in the list, so offset by 1.
            distance = len(channel_commits) - 1
            return cls._fallback(
                strict,
                distance=distance,
                commit=commit,
                dirty=dirty,
                branch=branch,
                timestamp=timestamp,
                vcs=vcs,
            )

        tag_meta = []  # type: List[dict]
        tag_state = ""
        tag_timestamp = dt.datetime.now()
        tag_message = ""
        tag_after_header = False
        for line in msg.splitlines():
            if not tag_after_header:
                if line.startswith("State "):
                    tag_state = line.split("State ", 1)[1]
                elif line.startswith("Date:"):
                    tag_timestamp = _parse_timestamp(
                        line.split("Date: ", 1)[1].replace(" UTC", "Z"), format=_TIMESTAMP_GENERIC_SPACE
                    )
                elif line.startswith("    "):
                    tag_message += line[4:]
                    tag_after_header = True
            else:
                if line.startswith("State "):
                    tag_meta.append(
                        {
                            "state": tag_state,
                            "timestamp": tag_timestamp,
                            "message": tag_message.strip(),
                        }
                    )

                    tag_state = line.split("State ", 1)[1]
                    tag_timestamp = dt.datetime.now()
                    tag_message = ""
                    tag_after_header = False
                else:
                    tag_message += line
        if tag_after_header:
            tag_meta.append({"state": tag_state, "timestamp": tag_timestamp, "message": tag_message.strip()})

        tag_meta_by_msg = {}  # type: dict
        for meta in tag_meta:
            if (
                meta["message"] not in tag_meta_by_msg
                or meta["timestamp"] > tag_meta_by_msg[meta["message"]]["timestamp"]
            ):
                tag_meta_by_msg[meta["message"]] = meta

        tags = [t["message"] for t in sorted(tag_meta_by_msg.values(), key=lambda x: x["timestamp"], reverse=True)]

        matched_pattern = _match_version_pattern(pattern, tags, latest_tag, strict, pattern_prefix)
        if matched_pattern is None:
            return cls._fallback(
                strict,
                distance=distance,
                commit=commit,
                dirty=dirty,
                branch=branch,
                timestamp=timestamp,
                vcs=vcs,
            )
        tag, base, stage, unmatched, tagged_metadata, epoch = matched_pattern

        tag_id = tag_meta_by_msg[tag]["state"]
        _run_cmd("pijul tag checkout {}".format(tag_id), path, codes=[0, 1])
        code, msg = _run_cmd("pijul log --output-format json --channel {}".format(tag_id), path)
        if msg.strip() == "":
            tag_commits = []  # type: list
        else:
            tag_commits = json.loads(msg)

        distance = len(channel_commits) - len(tag_commits)

        version = cls(
            base,
            stage=stage,
            distance=distance,
            commit=commit,
            dirty=dirty,
            tagged_metadata=tagged_metadata,
            epoch=epoch,
            branch=branch,
            timestamp=timestamp,
            vcs=vcs,
        )
        version._matched_tag = tag
        version._newer_unmatched_tags = unmatched
        return version

    @classmethod
    def from_any_vcs(
        cls,
        pattern: Union[str, Pattern] = Pattern.Default,
        latest_tag: bool = False,
        tag_dir: str = "tags",
        tag_branch: Optional[str] = None,
        full_commit: bool = False,
        strict: bool = False,
        path: Optional[Path] = None,
        pattern_prefix: Optional[str] = None,
        ignore_untracked: bool = False,
        commit_length: Optional[int] = None,
    ) -> "Version":
        r"""
        Determine a version based on a detected version control system.

        :param pattern: Regular expression matched against the version source.
            This must contain one capture group named `base` corresponding to
            the release segment of the source. Optionally, it may contain another
            two groups named `stage` and `revision` corresponding to a prerelease
            type (such as 'alpha' or 'rc') and number (such as in 'alpha-2' or 'rc3').
            It may also contain a group named `tagged_metadata` corresponding to extra
            metadata after the main part of the version (typically after a plus sign).
            There may also be a group named `epoch` for the PEP 440 concept.

            If the `base` group is not included, then this will be interpreted
            as the name of a variant of the `Pattern` enum. For example, passing
            `"default"` is the same as passing `Pattern.Default`.
        :param latest_tag: If true, only inspect the latest tag on the latest
            tagged commit for a pattern match. If false, keep looking at tags
            until there is a match.
        :param tag_dir: Location of tags relative to the root.
            This is only used for Subversion.
        :param tag_branch: Branch on which to find tags, if different than the
            current branch. This is only used for Git currently.
        :param full_commit: Get the full commit hash instead of the short form.
            This is only used for Git and Mercurial.
        :param strict: Elevate warnings to errors.
            When there are no tags, fail instead of falling back to 0.0.0.
        :param path: Directory to inspect, if not the current working directory.
        :param pattern_prefix: Insert this after the pattern's start anchor (`^`).
        :param ignore_untracked:
            Ignore untracked files when determining whether the repository is dirty.
            This is only used for Git currently.
        :param commit_length:
            Use this many characters from the start of the full commit hash.
        :returns: Detected version.
        """
        vcs = _detect_vcs_from_archival(path)
        if vcs is None:
            vcs = _detect_vcs(None, path)
        return cls._do_vcs_callback(
            vcs,
            pattern,
            latest_tag,
            tag_dir,
            tag_branch,
            full_commit,
            strict,
            path,
            pattern_prefix,
            ignore_untracked,
            commit_length,
        )

    @classmethod
    def from_vcs(
        cls,
        vcs: Vcs,
        pattern: Union[str, Pattern] = Pattern.Default,
        latest_tag: bool = False,
        tag_dir: str = "tags",
        tag_branch: Optional[str] = None,
        full_commit: bool = False,
        strict: bool = False,
        path: Optional[Path] = None,
        pattern_prefix: Optional[str] = None,
        ignore_untracked: bool = False,
        commit_length: Optional[int] = None,
    ) -> "Version":
        r"""
        Determine a version based on a specific VCS setting.

        This is primarily intended for other tools that want to generically
        use some VCS setting based on user configuration, without having to
        maintain a mapping from the VCS name to the appropriate function.

        :param pattern: Regular expression matched against the version source.
            Refer to `from_any_vcs` for more info.
        :param latest_tag: If true, only inspect the latest tag on the latest
            tagged commit for a pattern match. If false, keep looking at tags
            until there is a match.
        :param tag_dir: Location of tags relative to the root.
            This is only used for Subversion.
        :param tag_branch: Branch on which to find tags, if different than the
            current branch. This is only used for Git currently.
        :param full_commit: Get the full commit hash instead of the short form.
            This is only used for Git and Mercurial.
        :param strict: Elevate warnings to errors.
            When there are no tags, fail instead of falling back to 0.0.0.
        :param path: Directory to inspect, if not the current working directory.
        :param pattern_prefix: Insert this after the pattern's start anchor (`^`).
        :param ignore_untracked:
            Ignore untracked files when determining whether the repository is dirty.
            This is only used for Git currently.
        :param commit_length:
            Use this many characters from the start of the full commit hash.
        :returns: Detected version.
        """
        return cls._do_vcs_callback(
            vcs,
            pattern,
            latest_tag,
            tag_dir,
            tag_branch,
            full_commit,
            strict,
            path,
            pattern_prefix,
            ignore_untracked,
            commit_length,
        )

    @classmethod
    def _do_vcs_callback(
        cls,
        vcs: Vcs,
        pattern: Union[str, Pattern],
        latest_tag: bool,
        tag_dir: str,
        tag_branch: Optional[str],
        full_commit: bool,
        strict: bool,
        path: Optional[Path],
        pattern_prefix: Optional[str] = None,
        ignore_untracked: bool = False,
        commit_length: Optional[int] = None,
    ) -> "Version":
        mapping = {
            Vcs.Any: cls.from_any_vcs,
            Vcs.Git: cls.from_git,
            Vcs.Mercurial: cls.from_mercurial,
            Vcs.Darcs: cls.from_darcs,
            Vcs.Subversion: cls.from_subversion,
            Vcs.Bazaar: cls.from_bazaar,
            Vcs.Fossil: cls.from_fossil,
            Vcs.Pijul: cls.from_pijul,
        }  # type: Mapping[Vcs, Callable[..., "Version"]]
        kwargs = {}
        callback = mapping[vcs]
        for kwarg, value in [
            ("pattern", pattern),
            ("latest_tag", latest_tag),
            ("tag_dir", tag_dir),
            ("tag_branch", tag_branch),
            ("full_commit", full_commit),
            ("strict", strict),
            ("path", path),
            ("pattern_prefix", pattern_prefix),
            ("ignore_untracked", ignore_untracked),
            ("commit_length", commit_length),
        ]:
            if kwarg in inspect.getfullargspec(callback).args:
                kwargs[kwarg] = value
        return callback(**kwargs)


def check_version(version: str, style: Style = Style.Pep440) -> None:
    """
    Check if a version is valid for a style.

    :param version: Version to check.
    :param style: Style against which to check.
    :raises ValueError: If the version is invalid.
    """
    name, pattern = {
        Style.Pep440: ("PEP 440", _VALID_PEP440),
        Style.SemVer: ("Semantic Versioning", _VALID_SEMVER),
        Style.Pvp: ("PVP", _VALID_PVP),
    }[style]
    failure_message = "Version '{}' does not conform to the {} style".format(version, name)
    if not re.search(pattern, version):
        raise ValueError(failure_message)
    if style == Style.SemVer:
        parts = re.split(r"[.-]", version.split("+", 1)[0])
        if any(re.search(r"^0[0-9]+$", x) for x in parts):
            raise ValueError(failure_message)


def get_version(
    name: str,
    first_choice: Optional[Callable[[], Optional[Version]]] = None,
    third_choice: Optional[Callable[[], Optional[Version]]] = None,
    fallback: Version = Version("0.0.0"),
    ignore: Optional[Sequence[Version]] = None,
    parser: Callable[[str], Version] = Version,
) -> Version:
    """
    Check importlib-metadata info or a fallback function to determine the version.
    This is intended as a convenient default for setting your `__version__` if
    you do not want to include a generated version statically during packaging.

    :param name: Installed package name.
    :param first_choice: Callback to determine a version before checking
        to see if the named package is installed.
    :param third_choice: Callback to determine a version if the installed
        package cannot be found by name.
    :param fallback: If no other matches found, use this version.
    :param ignore: Ignore a found version if it is part of this list. When
        comparing the found version to an ignored one, fields with None in the ignored
        version are not taken into account. If the ignored version has distance=0,
        then that field is also ignored.
    :param parser: Callback to convert a string into a Version instance.
        This will be used for the second choice.
        For example, you can pass `Version.parse` here.
    :returns: First available version.
    """
    if ignore is None:
        ignore = []

    if first_choice:
        first_ver = first_choice()
        if first_ver and not any(first_ver._matches_partial(v) for v in ignore):
            return first_ver

    try:
        import importlib.metadata as ilm
    except ImportError:
        import importlib_metadata as ilm  # type: ignore
    try:
        ilm_version = parser(ilm.version(name))
        if not any(ilm_version._matches_partial(v) for v in ignore):
            return ilm_version
    except ilm.PackageNotFoundError:
        pass

    if third_choice:
        third_ver = third_choice()
        if third_ver and not any(third_ver._matches_partial(v) for v in ignore):
            return third_ver

    return fallback


def serialize_pep440(
    base: str,
    stage: Optional[str] = None,
    revision: Optional[int] = None,
    post: Optional[int] = None,
    dev: Optional[int] = None,
    epoch: Optional[int] = None,
    metadata: Optional[Sequence[Union[str, int]]] = None,
) -> str:
    """
    Serialize a version based on PEP 440.
    Use this instead of `Version.serialize()` if you want more control
    over how the version is mapped.

    :param base: Release segment, such as 0.1.0.
    :param stage: Pre-release stage ("a", "b", or "rc").
    :param revision: Pre-release revision (e.g., 1 as in "rc1").
        This is ignored when `stage` is None.
    :param post: Post-release number.
    :param dev: Developmental release number.
    :param epoch: Epoch number.
    :param metadata: Any local version label segments.
    :returns: Serialized version.
    """
    out = []  # type: list

    if epoch is not None:
        out.extend([epoch, "!"])

    out.append(base)

    if stage is not None:
        alternative_stages = {"alpha": "a", "beta": "b", "c": "rc", "pre": "rc", "preview": "rc"}
        out.append(alternative_stages.get(stage.lower(), stage.lower()))
        if revision is None:
            # PEP 440 does not allow omitting the revision, so assume 0.
            out.append(0)
        else:
            out.append(revision)

    if post is not None:
        out.extend([".post", post])

    if dev is not None:
        out.extend([".dev", dev])

    if metadata is not None and len(metadata) > 0:
        out.extend(["+", ".".join(map(str, metadata))])

    serialized = "".join(map(str, out))
    check_version(serialized, Style.Pep440)
    return serialized


def serialize_semver(
    base: str,
    pre: Optional[Sequence[Union[str, int]]] = None,
    metadata: Optional[Sequence[Union[str, int]]] = None,
) -> str:
    """
    Serialize a version based on Semantic Versioning.
    Use this instead of `Version.serialize()` if you want more control
    over how the version is mapped.

    :param base: Version core, such as 0.1.0.
    :param pre: Pre-release identifiers.
    :param metadata: Build metadata identifiers.
    :returns: Serialized version.
    """
    out = [base]

    if pre is not None and len(pre) > 0:
        out.extend(["-", ".".join(map(str, pre))])

    if metadata is not None and len(metadata) > 0:
        out.extend(["+", ".".join(map(str, metadata))])

    serialized = "".join(str(x) for x in out)
    check_version(serialized, Style.SemVer)
    return serialized


def serialize_pvp(base: str, metadata: Optional[Sequence[Union[str, int]]] = None) -> str:
    """
    Serialize a version based on the Haskell Package Versioning Policy.
    Use this instead of `Version.serialize()` if you want more control
    over how the version is mapped.

    :param base: Version core, such as 0.1.0.
    :param metadata: Version tag metadata.
    :returns: Serialized version.
    """
    out = [base]

    if metadata is not None and len(metadata) > 0:
        out.extend(["-", "-".join(map(str, metadata))])

    serialized = "".join(map(str, out))
    check_version(serialized, Style.Pvp)
    return serialized


def bump_version(base: str, index: int = -1, increment: int = 1) -> str:
    """
    Increment one of the numerical positions of a version.

    :param base: Version core, such as 0.1.0.
        Do not include pre-release identifiers.
    :param index: Numerical position to increment.
        This follows Python indexing rules, so positive numbers start from
        the left side and count up from 0, while negative numbers start from
        the right side and count down from -1.
    :param increment: By how much the `index` needs to increment.
    :returns: Bumped version.
    """
    bases = [int(x) for x in base.split(".")]
    bases[index] += increment

    limit = 0 if index < 0 else len(bases)
    i = index + 1
    while i < limit:
        bases[i] = 0
        i += 1

    return ".".join(str(x) for x in bases)


def _parse_git_timestamp_iso_strict(raw: str) -> dt.datetime:
    # Remove colon from timezone offset for pre-3.7 Python:
    compat = re.sub(r"(.*T.*[-+]\d+):(\d+)", r"\1\2", raw)
    return _parse_timestamp(compat, _TIMESTAMP_GIT_ISO_STRICT)


def _parse_git_timestamp_iso(raw: str) -> dt.datetime:
    # Remove colon from timezone offset for pre-3.7 Python:
    compat = re.sub(r"(.* .* [-+]\d+):(\d+)", r"\1\2", raw)
    return _parse_timestamp(compat, _TIMESTAMP_GIT_ISO)


def _parse_timestamp(raw: str, format: str = _TIMESTAMP_GENERIC) -> dt.datetime:
    # Normalize "Z" for pre-3.7 compatibility:
    normalized = re.sub(r"Z$", "+0000", raw)
    # Truncate %f to six digits:
    normalized = re.sub(r"\.(\d{6})\d+\+0000", r".\g<1>+0000", normalized)

    return dt.datetime.strptime(normalized, format)


__version__ = get_version("dunamai").serialize()