Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

versioneer.py 82 KB

You have to be logged in to leave a comment. Sign In
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
  1. # Version: 0.28
  2. """The Versioneer - like a rocketeer, but for versions.
  3. The Versioneer
  4. ==============
  5. * like a rocketeer, but for versions!
  6. * https://github.com/python-versioneer/python-versioneer
  7. * Brian Warner
  8. * License: Public Domain (Unlicense)
  9. * Compatible with: Python 3.7, 3.8, 3.9, 3.10 and pypy3
  10. * [![Latest Version][pypi-image]][pypi-url]
  11. * [![Build Status][travis-image]][travis-url]
  12. This is a tool for managing a recorded version number in setuptools-based
  13. python projects. The goal is to remove the tedious and error-prone "update
  14. the embedded version string" step from your release process. Making a new
  15. release should be as easy as recording a new tag in your version-control
  16. system, and maybe making new tarballs.
  17. ## Quick Install
  18. Versioneer provides two installation modes. The "classic" vendored mode installs
  19. a copy of versioneer into your repository. The experimental build-time dependency mode
  20. is intended to allow you to skip this step and simplify the process of upgrading.
  21. ### Vendored mode
  22. * `pip install versioneer` to somewhere in your $PATH
  23. * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is
  24. available, so you can also use `conda install -c conda-forge versioneer`
  25. * add a `[tool.versioneer]` section to your `pyproject.toml` or a
  26. `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md))
  27. * Note that you will need to add `tomli; python_version < "3.11"` to your
  28. build-time dependencies if you use `pyproject.toml`
  29. * run `versioneer install --vendor` in your source tree, commit the results
  30. * verify version information with `python setup.py version`
  31. ### Build-time dependency mode
  32. * `pip install versioneer` to somewhere in your $PATH
  33. * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is
  34. available, so you can also use `conda install -c conda-forge versioneer`
  35. * add a `[tool.versioneer]` section to your `pyproject.toml` or a
  36. `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md))
  37. * add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`)
  38. to the `requires` key of the `build-system` table in `pyproject.toml`:
  39. ```toml
  40. [build-system]
  41. requires = ["setuptools", "versioneer[toml]"]
  42. build-backend = "setuptools.build_meta"
  43. ```
  44. * run `versioneer install --no-vendor` in your source tree, commit the results
  45. * verify version information with `python setup.py version`
  46. ## Version Identifiers
  47. Source trees come from a variety of places:
  48. * a version-control system checkout (mostly used by developers)
  49. * a nightly tarball, produced by build automation
  50. * a snapshot tarball, produced by a web-based VCS browser, like github's
  51. "tarball from tag" feature
  52. * a release tarball, produced by "setup.py sdist", distributed through PyPI
  53. Within each source tree, the version identifier (either a string or a number,
  54. this tool is format-agnostic) can come from a variety of places:
  55. * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows
  56. about recent "tags" and an absolute revision-id
  57. * the name of the directory into which the tarball was unpacked
  58. * an expanded VCS keyword ($Id$, etc)
  59. * a `_version.py` created by some earlier build step
  60. For released software, the version identifier is closely related to a VCS
  61. tag. Some projects use tag names that include more than just the version
  62. string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool
  63. needs to strip the tag prefix to extract the version identifier. For
  64. unreleased software (between tags), the version identifier should provide
  65. enough information to help developers recreate the same tree, while also
  66. giving them an idea of roughly how old the tree is (after version 1.2, before
  67. version 1.3). Many VCS systems can report a description that captures this,
  68. for example `git describe --tags --dirty --always` reports things like
  69. "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the
  70. 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has
  71. uncommitted changes).
  72. The version identifier is used for multiple purposes:
  73. * to allow the module to self-identify its version: `myproject.__version__`
  74. * to choose a name and prefix for a 'setup.py sdist' tarball
  75. ## Theory of Operation
  76. Versioneer works by adding a special `_version.py` file into your source
  77. tree, where your `__init__.py` can import it. This `_version.py` knows how to
  78. dynamically ask the VCS tool for version information at import time.
  79. `_version.py` also contains `$Revision$` markers, and the installation
  80. process marks `_version.py` to have this marker rewritten with a tag name
  81. during the `git archive` command. As a result, generated tarballs will
  82. contain enough information to get the proper version.
  83. To allow `setup.py` to compute a version too, a `versioneer.py` is added to
  84. the top level of your source tree, next to `setup.py` and the `setup.cfg`
  85. that configures it. This overrides several distutils/setuptools commands to
  86. compute the version when invoked, and changes `setup.py build` and `setup.py
  87. sdist` to replace `_version.py` with a small static file that contains just
  88. the generated version data.
  89. ## Installation
  90. See [INSTALL.md](./INSTALL.md) for detailed installation instructions.
  91. ## Version-String Flavors
  92. Code which uses Versioneer can learn about its version string at runtime by
  93. importing `_version` from your main `__init__.py` file and running the
  94. `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can
  95. import the top-level `versioneer.py` and run `get_versions()`.
  96. Both functions return a dictionary with different flavors of version
  97. information:
  98. * `['version']`: A condensed version string, rendered using the selected
  99. style. This is the most commonly used value for the project's version
  100. string. The default "pep440" style yields strings like `0.11`,
  101. `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section
  102. below for alternative styles.
  103. * `['full-revisionid']`: detailed revision identifier. For Git, this is the
  104. full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac".
  105. * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the
  106. commit date in ISO 8601 format. This will be None if the date is not
  107. available.
  108. * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that
  109. this is only accurate if run in a VCS checkout, otherwise it is likely to
  110. be False or None
  111. * `['error']`: if the version string could not be computed, this will be set
  112. to a string describing the problem, otherwise it will be None. It may be
  113. useful to throw an exception in setup.py if this is set, to avoid e.g.
  114. creating tarballs with a version string of "unknown".
  115. Some variants are more useful than others. Including `full-revisionid` in a
  116. bug report should allow developers to reconstruct the exact code being tested
  117. (or indicate the presence of local changes that should be shared with the
  118. developers). `version` is suitable for display in an "about" box or a CLI
  119. `--version` output: it can be easily compared against release notes and lists
  120. of bugs fixed in various releases.
  121. The installer adds the following text to your `__init__.py` to place a basic
  122. version in `YOURPROJECT.__version__`:
  123. from ._version import get_versions
  124. __version__ = get_versions()['version']
  125. del get_versions
  126. ## Styles
  127. The setup.cfg `style=` configuration controls how the VCS information is
  128. rendered into a version string.
  129. The default style, "pep440", produces a PEP440-compliant string, equal to the
  130. un-prefixed tag name for actual releases, and containing an additional "local
  131. version" section with more detail for in-between builds. For Git, this is
  132. TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags
  133. --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the
  134. tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and
  135. that this commit is two revisions ("+2") beyond the "0.11" tag. For released
  136. software (exactly equal to a known tag), the identifier will only contain the
  137. stripped tag, e.g. "0.11".
  138. Other styles are available. See [details.md](details.md) in the Versioneer
  139. source tree for descriptions.
  140. ## Debugging
  141. Versioneer tries to avoid fatal errors: if something goes wrong, it will tend
  142. to return a version of "0+unknown". To investigate the problem, run `setup.py
  143. version`, which will run the version-lookup code in a verbose mode, and will
  144. display the full contents of `get_versions()` (including the `error` string,
  145. which may help identify what went wrong).
  146. ## Known Limitations
  147. Some situations are known to cause problems for Versioneer. This details the
  148. most significant ones. More can be found on Github
  149. [issues page](https://github.com/python-versioneer/python-versioneer/issues).
  150. ### Subprojects
  151. Versioneer has limited support for source trees in which `setup.py` is not in
  152. the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are
  153. two common reasons why `setup.py` might not be in the root:
  154. * Source trees which contain multiple subprojects, such as
  155. [Buildbot](https://github.com/buildbot/buildbot), which contains both
  156. "master" and "slave" subprojects, each with their own `setup.py`,
  157. `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI
  158. distributions (and upload multiple independently-installable tarballs).
  159. * Source trees whose main purpose is to contain a C library, but which also
  160. provide bindings to Python (and perhaps other languages) in subdirectories.
  161. Versioneer will look for `.git` in parent directories, and most operations
  162. should get the right version string. However `pip` and `setuptools` have bugs
  163. and implementation details which frequently cause `pip install .` from a
  164. subproject directory to fail to find a correct version string (so it usually
  165. defaults to `0+unknown`).
  166. `pip install --editable .` should work correctly. `setup.py install` might
  167. work too.
  168. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in
  169. some later version.
  170. [Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking
  171. this issue. The discussion in
  172. [PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the
  173. issue from the Versioneer side in more detail.
  174. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and
  175. [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve
  176. pip to let Versioneer work correctly.
  177. Versioneer-0.16 and earlier only looked for a `.git` directory next to the
  178. `setup.cfg`, so subprojects were completely unsupported with those releases.
  179. ### Editable installs with setuptools <= 18.5
  180. `setup.py develop` and `pip install --editable .` allow you to install a
  181. project into a virtualenv once, then continue editing the source code (and
  182. test) without re-installing after every change.
  183. "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a
  184. convenient way to specify executable scripts that should be installed along
  185. with the python package.
  186. These both work as expected when using modern setuptools. When using
  187. setuptools-18.5 or earlier, however, certain operations will cause
  188. `pkg_resources.DistributionNotFound` errors when running the entrypoint
  189. script, which must be resolved by re-installing the package. This happens
  190. when the install happens with one version, then the egg_info data is
  191. regenerated while a different version is checked out. Many setup.py commands
  192. cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into
  193. a different virtualenv), so this can be surprising.
  194. [Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes
  195. this one, but upgrading to a newer version of setuptools should probably
  196. resolve it.
  197. ## Updating Versioneer
  198. To upgrade your project to a new release of Versioneer, do the following:
  199. * install the new Versioneer (`pip install -U versioneer` or equivalent)
  200. * edit `setup.cfg` and `pyproject.toml`, if necessary,
  201. to include any new configuration settings indicated by the release notes.
  202. See [UPGRADING](./UPGRADING.md) for details.
  203. * re-run `versioneer install --[no-]vendor` in your source tree, to replace
  204. `SRC/_version.py`
  205. * commit any changed files
  206. ## Future Directions
  207. This tool is designed to make it easily extended to other version-control
  208. systems: all VCS-specific components are in separate directories like
  209. src/git/ . The top-level `versioneer.py` script is assembled from these
  210. components by running make-versioneer.py . In the future, make-versioneer.py
  211. will take a VCS name as an argument, and will construct a version of
  212. `versioneer.py` that is specific to the given VCS. It might also take the
  213. configuration arguments that are currently provided manually during
  214. installation by editing setup.py . Alternatively, it might go the other
  215. direction and include code from all supported VCS systems, reducing the
  216. number of intermediate scripts.
  217. ## Similar projects
  218. * [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time
  219. dependency
  220. * [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of
  221. versioneer
  222. * [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools
  223. plugin
  224. ## License
  225. To make Versioneer easier to embed, all its code is dedicated to the public
  226. domain. The `_version.py` that it creates is also in the public domain.
  227. Specifically, both are released under the "Unlicense", as described in
  228. https://unlicense.org/.
  229. [pypi-image]: https://img.shields.io/pypi/v/versioneer.svg
  230. [pypi-url]: https://pypi.python.org/pypi/versioneer/
  231. [travis-image]:
  232. https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg
  233. [travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer
  234. """
  235. # pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring
  236. # pylint:disable=missing-class-docstring,too-many-branches,too-many-statements
  237. # pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error
  238. # pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with
  239. # pylint:disable=attribute-defined-outside-init,too-many-arguments
  240. import configparser
  241. import errno
  242. import json
  243. import os
  244. import re
  245. import subprocess
  246. import sys
  247. from pathlib import Path
  248. from typing import Callable, Dict
  249. import functools
  250. have_tomllib = True
  251. if sys.version_info >= (3, 11):
  252. import tomllib
  253. else:
  254. try:
  255. import tomli as tomllib
  256. except ImportError:
  257. have_tomllib = False
  258. class VersioneerConfig:
  259. """Container for Versioneer configuration parameters."""
  260. def get_root():
  261. """Get the project root directory.
  262. We require that all commands are run from the project root, i.e. the
  263. directory that contains setup.py, setup.cfg, and versioneer.py .
  264. """
  265. root = os.path.realpath(os.path.abspath(os.getcwd()))
  266. setup_py = os.path.join(root, "setup.py")
  267. versioneer_py = os.path.join(root, "versioneer.py")
  268. if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
  269. # allow 'python path/to/setup.py COMMAND'
  270. root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))
  271. setup_py = os.path.join(root, "setup.py")
  272. versioneer_py = os.path.join(root, "versioneer.py")
  273. if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
  274. err = (
  275. "Versioneer was unable to run the project root directory. "
  276. "Versioneer requires setup.py to be executed from "
  277. "its immediate directory (like 'python setup.py COMMAND'), "
  278. "or in a way that lets it use sys.argv[0] to find the root "
  279. "(like 'python path/to/setup.py COMMAND')."
  280. )
  281. raise VersioneerBadRootError(err)
  282. try:
  283. # Certain runtime workflows (setup.py install/develop in a setuptools
  284. # tree) execute all dependencies in a single python process, so
  285. # "versioneer" may be imported multiple times, and python's shared
  286. # module-import table will cache the first one. So we can't use
  287. # os.path.dirname(__file__), as that will find whichever
  288. # versioneer.py was first imported, even in later projects.
  289. my_path = os.path.realpath(os.path.abspath(__file__))
  290. me_dir = os.path.normcase(os.path.splitext(my_path)[0])
  291. vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])
  292. if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals():
  293. print(
  294. "Warning: build in %s is using versioneer.py from %s"
  295. % (os.path.dirname(my_path), versioneer_py)
  296. )
  297. except NameError:
  298. pass
  299. return root
  300. def get_config_from_root(root):
  301. """Read the project setup.cfg file to determine Versioneer config."""
  302. # This might raise OSError (if setup.cfg is missing), or
  303. # configparser.NoSectionError (if it lacks a [versioneer] section), or
  304. # configparser.NoOptionError (if it lacks "VCS="). See the docstring at
  305. # the top of versioneer.py for instructions on writing your setup.cfg .
  306. root = Path(root)
  307. pyproject_toml = root / "pyproject.toml"
  308. setup_cfg = root / "setup.cfg"
  309. section = None
  310. if pyproject_toml.exists() and have_tomllib:
  311. try:
  312. with open(pyproject_toml, "rb") as fobj:
  313. pp = tomllib.load(fobj)
  314. section = pp["tool"]["versioneer"]
  315. except (tomllib.TOMLDecodeError, KeyError):
  316. pass
  317. if not section:
  318. parser = configparser.ConfigParser()
  319. with open(setup_cfg) as cfg_file:
  320. parser.read_file(cfg_file)
  321. parser.get("versioneer", "VCS") # raise error if missing
  322. section = parser["versioneer"]
  323. cfg = VersioneerConfig()
  324. cfg.VCS = section["VCS"]
  325. cfg.style = section.get("style", "")
  326. cfg.versionfile_source = section.get("versionfile_source")
  327. cfg.versionfile_build = section.get("versionfile_build")
  328. cfg.tag_prefix = section.get("tag_prefix")
  329. if cfg.tag_prefix in ("''", '""', None):
  330. cfg.tag_prefix = ""
  331. cfg.parentdir_prefix = section.get("parentdir_prefix")
  332. cfg.verbose = section.get("verbose")
  333. return cfg
  334. class NotThisMethod(Exception):
  335. """Exception raised if a method is not valid for the current scenario."""
  336. # these dictionaries contain VCS-specific tools
  337. LONG_VERSION_PY: Dict[str, str] = {}
  338. HANDLERS: Dict[str, Dict[str, Callable]] = {}
  339. def register_vcs_handler(vcs, method): # decorator
  340. """Create decorator to mark a method as the handler of a VCS."""
  341. def decorate(f):
  342. """Store f in HANDLERS[vcs][method]."""
  343. HANDLERS.setdefault(vcs, {})[method] = f
  344. return f
  345. return decorate
  346. def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
  347. """Call the given command(s)."""
  348. assert isinstance(commands, list)
  349. process = None
  350. popen_kwargs = {}
  351. if sys.platform == "win32":
  352. # This hides the console window if pythonw.exe is used
  353. startupinfo = subprocess.STARTUPINFO()
  354. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  355. popen_kwargs["startupinfo"] = startupinfo
  356. for command in commands:
  357. try:
  358. dispcmd = str([command] + args)
  359. # remember shell=False, so use git.cmd on windows, not just git
  360. process = subprocess.Popen(
  361. [command] + args,
  362. cwd=cwd,
  363. env=env,
  364. stdout=subprocess.PIPE,
  365. stderr=(subprocess.PIPE if hide_stderr else None),
  366. **popen_kwargs,
  367. )
  368. break
  369. except OSError:
  370. e = sys.exc_info()[1]
  371. if e.errno == errno.ENOENT:
  372. continue
  373. if verbose:
  374. print("unable to run %s" % dispcmd)
  375. print(e)
  376. return None, None
  377. else:
  378. if verbose:
  379. print("unable to find command, tried %s" % (commands,))
  380. return None, None
  381. stdout = process.communicate()[0].strip().decode()
  382. if process.returncode != 0:
  383. if verbose:
  384. print("unable to run %s (error)" % dispcmd)
  385. print("stdout was %s" % stdout)
  386. return None, process.returncode
  387. return stdout, process.returncode
  388. LONG_VERSION_PY[
  389. "git"
  390. ] = r'''
  391. # This file helps to compute a version number in source trees obtained from
  392. # git-archive tarball (such as those provided by githubs download-from-tag
  393. # feature). Distribution tarballs (built by setup.py sdist) and build
  394. # directories (produced by setup.py build) will contain a much shorter file
  395. # that just contains the computed version number.
  396. # This file is released into the public domain.
  397. # Generated by versioneer-0.28
  398. # https://github.com/python-versioneer/python-versioneer
  399. """Git implementation of _version.py."""
  400. import errno
  401. import os
  402. import re
  403. import subprocess
  404. import sys
  405. from typing import Callable, Dict
  406. import functools
  407. def get_keywords():
  408. """Get the keywords needed to look up the version information."""
  409. # these strings will be replaced by git during git-archive.
  410. # setup.py/versioneer.py will grep for the variable names, so they must
  411. # each be defined on a line of their own. _version.py will just call
  412. # get_keywords().
  413. git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s"
  414. git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s"
  415. git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s"
  416. keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
  417. return keywords
  418. class VersioneerConfig:
  419. """Container for Versioneer configuration parameters."""
  420. def get_config():
  421. """Create, populate and return the VersioneerConfig() object."""
  422. # these strings are filled in when 'setup.py versioneer' creates
  423. # _version.py
  424. cfg = VersioneerConfig()
  425. cfg.VCS = "git"
  426. cfg.style = "%(STYLE)s"
  427. cfg.tag_prefix = "%(TAG_PREFIX)s"
  428. cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s"
  429. cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s"
  430. cfg.verbose = False
  431. return cfg
  432. class NotThisMethod(Exception):
  433. """Exception raised if a method is not valid for the current scenario."""
  434. LONG_VERSION_PY: Dict[str, str] = {}
  435. HANDLERS: Dict[str, Dict[str, Callable]] = {}
  436. def register_vcs_handler(vcs, method): # decorator
  437. """Create decorator to mark a method as the handler of a VCS."""
  438. def decorate(f):
  439. """Store f in HANDLERS[vcs][method]."""
  440. if vcs not in HANDLERS:
  441. HANDLERS[vcs] = {}
  442. HANDLERS[vcs][method] = f
  443. return f
  444. return decorate
  445. def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
  446. env=None):
  447. """Call the given command(s)."""
  448. assert isinstance(commands, list)
  449. process = None
  450. popen_kwargs = {}
  451. if sys.platform == "win32":
  452. # This hides the console window if pythonw.exe is used
  453. startupinfo = subprocess.STARTUPINFO()
  454. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  455. popen_kwargs["startupinfo"] = startupinfo
  456. for command in commands:
  457. try:
  458. dispcmd = str([command] + args)
  459. # remember shell=False, so use git.cmd on windows, not just git
  460. process = subprocess.Popen([command] + args, cwd=cwd, env=env,
  461. stdout=subprocess.PIPE,
  462. stderr=(subprocess.PIPE if hide_stderr
  463. else None), **popen_kwargs)
  464. break
  465. except OSError:
  466. e = sys.exc_info()[1]
  467. if e.errno == errno.ENOENT:
  468. continue
  469. if verbose:
  470. print("unable to run %%s" %% dispcmd)
  471. print(e)
  472. return None, None
  473. else:
  474. if verbose:
  475. print("unable to find command, tried %%s" %% (commands,))
  476. return None, None
  477. stdout = process.communicate()[0].strip().decode()
  478. if process.returncode != 0:
  479. if verbose:
  480. print("unable to run %%s (error)" %% dispcmd)
  481. print("stdout was %%s" %% stdout)
  482. return None, process.returncode
  483. return stdout, process.returncode
  484. def versions_from_parentdir(parentdir_prefix, root, verbose):
  485. """Try to determine the version from the parent directory name.
  486. Source tarballs conventionally unpack into a directory that includes both
  487. the project name and a version string. We will also support searching up
  488. two directory levels for an appropriately named parent directory
  489. """
  490. rootdirs = []
  491. for _ in range(3):
  492. dirname = os.path.basename(root)
  493. if dirname.startswith(parentdir_prefix):
  494. return {"version": dirname[len(parentdir_prefix):],
  495. "full-revisionid": None,
  496. "dirty": False, "error": None, "date": None}
  497. rootdirs.append(root)
  498. root = os.path.dirname(root) # up a level
  499. if verbose:
  500. print("Tried directories %%s but none started with prefix %%s" %%
  501. (str(rootdirs), parentdir_prefix))
  502. raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
  503. @register_vcs_handler("git", "get_keywords")
  504. def git_get_keywords(versionfile_abs):
  505. """Extract version information from the given file."""
  506. # the code embedded in _version.py can just fetch the value of these
  507. # keywords. When used from setup.py, we don't want to import _version.py,
  508. # so we do it with a regexp instead. This function is not used from
  509. # _version.py.
  510. keywords = {}
  511. try:
  512. with open(versionfile_abs, "r") as fobj:
  513. for line in fobj:
  514. if line.strip().startswith("git_refnames ="):
  515. mo = re.search(r'=\s*"(.*)"', line)
  516. if mo:
  517. keywords["refnames"] = mo.group(1)
  518. if line.strip().startswith("git_full ="):
  519. mo = re.search(r'=\s*"(.*)"', line)
  520. if mo:
  521. keywords["full"] = mo.group(1)
  522. if line.strip().startswith("git_date ="):
  523. mo = re.search(r'=\s*"(.*)"', line)
  524. if mo:
  525. keywords["date"] = mo.group(1)
  526. except OSError:
  527. pass
  528. return keywords
  529. @register_vcs_handler("git", "keywords")
  530. def git_versions_from_keywords(keywords, tag_prefix, verbose):
  531. """Get version information from git keywords."""
  532. if "refnames" not in keywords:
  533. raise NotThisMethod("Short version file found")
  534. date = keywords.get("date")
  535. if date is not None:
  536. # Use only the last line. Previous lines may contain GPG signature
  537. # information.
  538. date = date.splitlines()[-1]
  539. # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant
  540. # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601
  541. # -like" string, which we must then edit to make compliant), because
  542. # it's been around since git-1.5.3, and it's too difficult to
  543. # discover which version we're using, or to work around using an
  544. # older one.
  545. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
  546. refnames = keywords["refnames"].strip()
  547. if refnames.startswith("$Format"):
  548. if verbose:
  549. print("keywords are unexpanded, not using")
  550. raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
  551. refs = {r.strip() for r in refnames.strip("()").split(",")}
  552. # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
  553. # just "foo-1.0". If we see a "tag: " prefix, prefer those.
  554. TAG = "tag: "
  555. tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
  556. if not tags:
  557. # Either we're using git < 1.8.3, or there really are no tags. We use
  558. # a heuristic: assume all version tags have a digit. The old git %%d
  559. # expansion behaves like git log --decorate=short and strips out the
  560. # refs/heads/ and refs/tags/ prefixes that would let us distinguish
  561. # between branches and tags. By ignoring refnames without digits, we
  562. # filter out many common branch names like "release" and
  563. # "stabilization", as well as "HEAD" and "master".
  564. tags = {r for r in refs if re.search(r'\d', r)}
  565. if verbose:
  566. print("discarding '%%s', no digits" %% ",".join(refs - tags))
  567. if verbose:
  568. print("likely tags: %%s" %% ",".join(sorted(tags)))
  569. for ref in sorted(tags):
  570. # sorting will prefer e.g. "2.0" over "2.0rc1"
  571. if ref.startswith(tag_prefix):
  572. r = ref[len(tag_prefix):]
  573. # Filter out refs that exactly match prefix or that don't start
  574. # with a number once the prefix is stripped (mostly a concern
  575. # when prefix is '')
  576. if not re.match(r'\d', r):
  577. continue
  578. if verbose:
  579. print("picking %%s" %% r)
  580. return {"version": r,
  581. "full-revisionid": keywords["full"].strip(),
  582. "dirty": False, "error": None,
  583. "date": date}
  584. # no suitable tags, so version is "0+unknown", but full hex is still there
  585. if verbose:
  586. print("no suitable tags, using unknown + full revision id")
  587. return {"version": "0+unknown",
  588. "full-revisionid": keywords["full"].strip(),
  589. "dirty": False, "error": "no suitable tags", "date": None}
  590. @register_vcs_handler("git", "pieces_from_vcs")
  591. def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
  592. """Get version from 'git describe' in the root of the source tree.
  593. This only gets called if the git-archive 'subst' keywords were *not*
  594. expanded, and _version.py hasn't already been rewritten with a short
  595. version string, meaning we're inside a checked out source tree.
  596. """
  597. GITS = ["git"]
  598. if sys.platform == "win32":
  599. GITS = ["git.cmd", "git.exe"]
  600. # GIT_DIR can interfere with correct operation of Versioneer.
  601. # It may be intended to be passed to the Versioneer-versioned project,
  602. # but that should not change where we get our version from.
  603. env = os.environ.copy()
  604. env.pop("GIT_DIR", None)
  605. runner = functools.partial(runner, env=env)
  606. _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root,
  607. hide_stderr=not verbose)
  608. if rc != 0:
  609. if verbose:
  610. print("Directory %%s not under git control" %% root)
  611. raise NotThisMethod("'git rev-parse --git-dir' returned error")
  612. # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
  613. # if there isn't one, this yields HEX[-dirty] (no NUM)
  614. describe_out, rc = runner(GITS, [
  615. "describe", "--tags", "--dirty", "--always", "--long",
  616. "--match", f"{tag_prefix}[[:digit:]]*"
  617. ], cwd=root)
  618. # --long was added in git-1.5.5
  619. if describe_out is None:
  620. raise NotThisMethod("'git describe' failed")
  621. describe_out = describe_out.strip()
  622. full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
  623. if full_out is None:
  624. raise NotThisMethod("'git rev-parse' failed")
  625. full_out = full_out.strip()
  626. pieces = {}
  627. pieces["long"] = full_out
  628. pieces["short"] = full_out[:7] # maybe improved later
  629. pieces["error"] = None
  630. branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
  631. cwd=root)
  632. # --abbrev-ref was added in git-1.6.3
  633. if rc != 0 or branch_name is None:
  634. raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
  635. branch_name = branch_name.strip()
  636. if branch_name == "HEAD":
  637. # If we aren't exactly on a branch, pick a branch which represents
  638. # the current commit. If all else fails, we are on a branchless
  639. # commit.
  640. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
  641. # --contains was added in git-1.5.4
  642. if rc != 0 or branches is None:
  643. raise NotThisMethod("'git branch --contains' returned error")
  644. branches = branches.split("\n")
  645. # Remove the first line if we're running detached
  646. if "(" in branches[0]:
  647. branches.pop(0)
  648. # Strip off the leading "* " from the list of branches.
  649. branches = [branch[2:] for branch in branches]
  650. if "master" in branches:
  651. branch_name = "master"
  652. elif not branches:
  653. branch_name = None
  654. else:
  655. # Pick the first branch that is returned. Good or bad.
  656. branch_name = branches[0]
  657. pieces["branch"] = branch_name
  658. # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
  659. # TAG might have hyphens.
  660. git_describe = describe_out
  661. # look for -dirty suffix
  662. dirty = git_describe.endswith("-dirty")
  663. pieces["dirty"] = dirty
  664. if dirty:
  665. git_describe = git_describe[:git_describe.rindex("-dirty")]
  666. # now we have TAG-NUM-gHEX or HEX
  667. if "-" in git_describe:
  668. # TAG-NUM-gHEX
  669. mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
  670. if not mo:
  671. # unparsable. Maybe git-describe is misbehaving?
  672. pieces["error"] = ("unable to parse git-describe output: '%%s'"
  673. %% describe_out)
  674. return pieces
  675. # tag
  676. full_tag = mo.group(1)
  677. if not full_tag.startswith(tag_prefix):
  678. if verbose:
  679. fmt = "tag '%%s' doesn't start with prefix '%%s'"
  680. print(fmt %% (full_tag, tag_prefix))
  681. pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'"
  682. %% (full_tag, tag_prefix))
  683. return pieces
  684. pieces["closest-tag"] = full_tag[len(tag_prefix):]
  685. # distance: number of commits since tag
  686. pieces["distance"] = int(mo.group(2))
  687. # commit: short hex revision ID
  688. pieces["short"] = mo.group(3)
  689. else:
  690. # HEX: no tags
  691. pieces["closest-tag"] = None
  692. out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
  693. pieces["distance"] = len(out.split()) # total number of commits
  694. # commit date: see ISO-8601 comment in git_versions_from_keywords()
  695. date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip()
  696. # Use only the last line. Previous lines may contain GPG signature
  697. # information.
  698. date = date.splitlines()[-1]
  699. pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
  700. return pieces
  701. def plus_or_dot(pieces):
  702. """Return a + if we don't already have one, else return a ."""
  703. if "+" in pieces.get("closest-tag", ""):
  704. return "."
  705. return "+"
  706. def render_pep440(pieces):
  707. """Build up version string, with post-release "local version identifier".
  708. Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
  709. get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
  710. Exceptions:
  711. 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
  712. """
  713. if pieces["closest-tag"]:
  714. rendered = pieces["closest-tag"]
  715. if pieces["distance"] or pieces["dirty"]:
  716. rendered += plus_or_dot(pieces)
  717. rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"])
  718. if pieces["dirty"]:
  719. rendered += ".dirty"
  720. else:
  721. # exception #1
  722. rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"],
  723. pieces["short"])
  724. if pieces["dirty"]:
  725. rendered += ".dirty"
  726. return rendered
  727. def render_pep440_branch(pieces):
  728. """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
  729. The ".dev0" means not master branch. Note that .dev0 sorts backwards
  730. (a feature branch will appear "older" than the master branch).
  731. Exceptions:
  732. 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
  733. """
  734. if pieces["closest-tag"]:
  735. rendered = pieces["closest-tag"]
  736. if pieces["distance"] or pieces["dirty"]:
  737. if pieces["branch"] != "master":
  738. rendered += ".dev0"
  739. rendered += plus_or_dot(pieces)
  740. rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"])
  741. if pieces["dirty"]:
  742. rendered += ".dirty"
  743. else:
  744. # exception #1
  745. rendered = "0"
  746. if pieces["branch"] != "master":
  747. rendered += ".dev0"
  748. rendered += "+untagged.%%d.g%%s" %% (pieces["distance"],
  749. pieces["short"])
  750. if pieces["dirty"]:
  751. rendered += ".dirty"
  752. return rendered
  753. def pep440_split_post(ver):
  754. """Split pep440 version string at the post-release segment.
  755. Returns the release segments before the post-release and the
  756. post-release version number (or -1 if no post-release segment is present).
  757. """
  758. vc = str.split(ver, ".post")
  759. return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
  760. def render_pep440_pre(pieces):
  761. """TAG[.postN.devDISTANCE] -- No -dirty.
  762. Exceptions:
  763. 1: no tags. 0.post0.devDISTANCE
  764. """
  765. if pieces["closest-tag"]:
  766. if pieces["distance"]:
  767. # update the post release segment
  768. tag_version, post_version = pep440_split_post(pieces["closest-tag"])
  769. rendered = tag_version
  770. if post_version is not None:
  771. rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"])
  772. else:
  773. rendered += ".post0.dev%%d" %% (pieces["distance"])
  774. else:
  775. # no commits, use the tag as the version
  776. rendered = pieces["closest-tag"]
  777. else:
  778. # exception #1
  779. rendered = "0.post0.dev%%d" %% pieces["distance"]
  780. return rendered
  781. def render_pep440_post(pieces):
  782. """TAG[.postDISTANCE[.dev0]+gHEX] .
  783. The ".dev0" means dirty. Note that .dev0 sorts backwards
  784. (a dirty tree will appear "older" than the corresponding clean one),
  785. but you shouldn't be releasing software with -dirty anyways.
  786. Exceptions:
  787. 1: no tags. 0.postDISTANCE[.dev0]
  788. """
  789. if pieces["closest-tag"]:
  790. rendered = pieces["closest-tag"]
  791. if pieces["distance"] or pieces["dirty"]:
  792. rendered += ".post%%d" %% pieces["distance"]
  793. if pieces["dirty"]:
  794. rendered += ".dev0"
  795. rendered += plus_or_dot(pieces)
  796. rendered += "g%%s" %% pieces["short"]
  797. else:
  798. # exception #1
  799. rendered = "0.post%%d" %% pieces["distance"]
  800. if pieces["dirty"]:
  801. rendered += ".dev0"
  802. rendered += "+g%%s" %% pieces["short"]
  803. return rendered
  804. def render_pep440_post_branch(pieces):
  805. """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
  806. The ".dev0" means not master branch.
  807. Exceptions:
  808. 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
  809. """
  810. if pieces["closest-tag"]:
  811. rendered = pieces["closest-tag"]
  812. if pieces["distance"] or pieces["dirty"]:
  813. rendered += ".post%%d" %% pieces["distance"]
  814. if pieces["branch"] != "master":
  815. rendered += ".dev0"
  816. rendered += plus_or_dot(pieces)
  817. rendered += "g%%s" %% pieces["short"]
  818. if pieces["dirty"]:
  819. rendered += ".dirty"
  820. else:
  821. # exception #1
  822. rendered = "0.post%%d" %% pieces["distance"]
  823. if pieces["branch"] != "master":
  824. rendered += ".dev0"
  825. rendered += "+g%%s" %% pieces["short"]
  826. if pieces["dirty"]:
  827. rendered += ".dirty"
  828. return rendered
  829. def render_pep440_old(pieces):
  830. """TAG[.postDISTANCE[.dev0]] .
  831. The ".dev0" means dirty.
  832. Exceptions:
  833. 1: no tags. 0.postDISTANCE[.dev0]
  834. """
  835. if pieces["closest-tag"]:
  836. rendered = pieces["closest-tag"]
  837. if pieces["distance"] or pieces["dirty"]:
  838. rendered += ".post%%d" %% pieces["distance"]
  839. if pieces["dirty"]:
  840. rendered += ".dev0"
  841. else:
  842. # exception #1
  843. rendered = "0.post%%d" %% pieces["distance"]
  844. if pieces["dirty"]:
  845. rendered += ".dev0"
  846. return rendered
  847. def render_git_describe(pieces):
  848. """TAG[-DISTANCE-gHEX][-dirty].
  849. Like 'git describe --tags --dirty --always'.
  850. Exceptions:
  851. 1: no tags. HEX[-dirty] (note: no 'g' prefix)
  852. """
  853. if pieces["closest-tag"]:
  854. rendered = pieces["closest-tag"]
  855. if pieces["distance"]:
  856. rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
  857. else:
  858. # exception #1
  859. rendered = pieces["short"]
  860. if pieces["dirty"]:
  861. rendered += "-dirty"
  862. return rendered
  863. def render_git_describe_long(pieces):
  864. """TAG-DISTANCE-gHEX[-dirty].
  865. Like 'git describe --tags --dirty --always -long'.
  866. The distance/hash is unconditional.
  867. Exceptions:
  868. 1: no tags. HEX[-dirty] (note: no 'g' prefix)
  869. """
  870. if pieces["closest-tag"]:
  871. rendered = pieces["closest-tag"]
  872. rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
  873. else:
  874. # exception #1
  875. rendered = pieces["short"]
  876. if pieces["dirty"]:
  877. rendered += "-dirty"
  878. return rendered
  879. def render(pieces, style):
  880. """Render the given version pieces into the requested style."""
  881. if pieces["error"]:
  882. return {"version": "unknown",
  883. "full-revisionid": pieces.get("long"),
  884. "dirty": None,
  885. "error": pieces["error"],
  886. "date": None}
  887. if not style or style == "default":
  888. style = "pep440" # the default
  889. if style == "pep440":
  890. rendered = render_pep440(pieces)
  891. elif style == "pep440-branch":
  892. rendered = render_pep440_branch(pieces)
  893. elif style == "pep440-pre":
  894. rendered = render_pep440_pre(pieces)
  895. elif style == "pep440-post":
  896. rendered = render_pep440_post(pieces)
  897. elif style == "pep440-post-branch":
  898. rendered = render_pep440_post_branch(pieces)
  899. elif style == "pep440-old":
  900. rendered = render_pep440_old(pieces)
  901. elif style == "git-describe":
  902. rendered = render_git_describe(pieces)
  903. elif style == "git-describe-long":
  904. rendered = render_git_describe_long(pieces)
  905. else:
  906. raise ValueError("unknown style '%%s'" %% style)
  907. return {"version": rendered, "full-revisionid": pieces["long"],
  908. "dirty": pieces["dirty"], "error": None,
  909. "date": pieces.get("date")}
  910. def get_versions():
  911. """Get version information or return default if unable to do so."""
  912. # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
  913. # __file__, we can work backwards from there to the root. Some
  914. # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
  915. # case we can only use expanded keywords.
  916. cfg = get_config()
  917. verbose = cfg.verbose
  918. try:
  919. return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
  920. verbose)
  921. except NotThisMethod:
  922. pass
  923. try:
  924. root = os.path.realpath(__file__)
  925. # versionfile_source is the relative path from the top of the source
  926. # tree (where the .git directory might live) to this file. Invert
  927. # this to find the root from __file__.
  928. for _ in cfg.versionfile_source.split('/'):
  929. root = os.path.dirname(root)
  930. except NameError:
  931. return {"version": "0+unknown", "full-revisionid": None,
  932. "dirty": None,
  933. "error": "unable to find root of source tree",
  934. "date": None}
  935. try:
  936. pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
  937. return render(pieces, cfg.style)
  938. except NotThisMethod:
  939. pass
  940. try:
  941. if cfg.parentdir_prefix:
  942. return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
  943. except NotThisMethod:
  944. pass
  945. return {"version": "0+unknown", "full-revisionid": None,
  946. "dirty": None,
  947. "error": "unable to compute version", "date": None}
  948. '''
  949. @register_vcs_handler("git", "get_keywords")
  950. def git_get_keywords(versionfile_abs):
  951. """Extract version information from the given file."""
  952. # the code embedded in _version.py can just fetch the value of these
  953. # keywords. When used from setup.py, we don't want to import _version.py,
  954. # so we do it with a regexp instead. This function is not used from
  955. # _version.py.
  956. keywords = {}
  957. try:
  958. with open(versionfile_abs, "r") as fobj:
  959. for line in fobj:
  960. if line.strip().startswith("git_refnames ="):
  961. mo = re.search(r'=\s*"(.*)"', line)
  962. if mo:
  963. keywords["refnames"] = mo.group(1)
  964. if line.strip().startswith("git_full ="):
  965. mo = re.search(r'=\s*"(.*)"', line)
  966. if mo:
  967. keywords["full"] = mo.group(1)
  968. if line.strip().startswith("git_date ="):
  969. mo = re.search(r'=\s*"(.*)"', line)
  970. if mo:
  971. keywords["date"] = mo.group(1)
  972. except OSError:
  973. pass
  974. return keywords
  975. @register_vcs_handler("git", "keywords")
  976. def git_versions_from_keywords(keywords, tag_prefix, verbose):
  977. """Get version information from git keywords."""
  978. if "refnames" not in keywords:
  979. raise NotThisMethod("Short version file found")
  980. date = keywords.get("date")
  981. if date is not None:
  982. # Use only the last line. Previous lines may contain GPG signature
  983. # information.
  984. date = date.splitlines()[-1]
  985. # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
  986. # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
  987. # -like" string, which we must then edit to make compliant), because
  988. # it's been around since git-1.5.3, and it's too difficult to
  989. # discover which version we're using, or to work around using an
  990. # older one.
  991. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
  992. refnames = keywords["refnames"].strip()
  993. if refnames.startswith("$Format"):
  994. if verbose:
  995. print("keywords are unexpanded, not using")
  996. raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
  997. refs = {r.strip() for r in refnames.strip("()").split(",")}
  998. # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
  999. # just "foo-1.0". If we see a "tag: " prefix, prefer those.
  1000. TAG = "tag: "
  1001. tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
  1002. if not tags:
  1003. # Either we're using git < 1.8.3, or there really are no tags. We use
  1004. # a heuristic: assume all version tags have a digit. The old git %d
  1005. # expansion behaves like git log --decorate=short and strips out the
  1006. # refs/heads/ and refs/tags/ prefixes that would let us distinguish
  1007. # between branches and tags. By ignoring refnames without digits, we
  1008. # filter out many common branch names like "release" and
  1009. # "stabilization", as well as "HEAD" and "master".
  1010. tags = {r for r in refs if re.search(r"\d", r)}
  1011. if verbose:
  1012. print("discarding '%s', no digits" % ",".join(refs - tags))
  1013. if verbose:
  1014. print("likely tags: %s" % ",".join(sorted(tags)))
  1015. for ref in sorted(tags):
  1016. # sorting will prefer e.g. "2.0" over "2.0rc1"
  1017. if ref.startswith(tag_prefix):
  1018. r = ref[len(tag_prefix) :]
  1019. # Filter out refs that exactly match prefix or that don't start
  1020. # with a number once the prefix is stripped (mostly a concern
  1021. # when prefix is '')
  1022. if not re.match(r"\d", r):
  1023. continue
  1024. if verbose:
  1025. print("picking %s" % r)
  1026. return {
  1027. "version": r,
  1028. "full-revisionid": keywords["full"].strip(),
  1029. "dirty": False,
  1030. "error": None,
  1031. "date": date,
  1032. }
  1033. # no suitable tags, so version is "0+unknown", but full hex is still there
  1034. if verbose:
  1035. print("no suitable tags, using unknown + full revision id")
  1036. return {
  1037. "version": "0+unknown",
  1038. "full-revisionid": keywords["full"].strip(),
  1039. "dirty": False,
  1040. "error": "no suitable tags",
  1041. "date": None,
  1042. }
  1043. @register_vcs_handler("git", "pieces_from_vcs")
  1044. def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command):
  1045. """Get version from 'git describe' in the root of the source tree.
  1046. This only gets called if the git-archive 'subst' keywords were *not*
  1047. expanded, and _version.py hasn't already been rewritten with a short
  1048. version string, meaning we're inside a checked out source tree.
  1049. """
  1050. GITS = ["git"]
  1051. if sys.platform == "win32":
  1052. GITS = ["git.cmd", "git.exe"]
  1053. # GIT_DIR can interfere with correct operation of Versioneer.
  1054. # It may be intended to be passed to the Versioneer-versioned project,
  1055. # but that should not change where we get our version from.
  1056. env = os.environ.copy()
  1057. env.pop("GIT_DIR", None)
  1058. runner = functools.partial(runner, env=env)
  1059. _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose)
  1060. if rc != 0:
  1061. if verbose:
  1062. print("Directory %s not under git control" % root)
  1063. raise NotThisMethod("'git rev-parse --git-dir' returned error")
  1064. # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
  1065. # if there isn't one, this yields HEX[-dirty] (no NUM)
  1066. describe_out, rc = runner(
  1067. GITS,
  1068. [
  1069. "describe",
  1070. "--tags",
  1071. "--dirty",
  1072. "--always",
  1073. "--long",
  1074. "--match",
  1075. f"{tag_prefix}[[:digit:]]*",
  1076. ],
  1077. cwd=root,
  1078. )
  1079. # --long was added in git-1.5.5
  1080. if describe_out is None:
  1081. raise NotThisMethod("'git describe' failed")
  1082. describe_out = describe_out.strip()
  1083. full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
  1084. if full_out is None:
  1085. raise NotThisMethod("'git rev-parse' failed")
  1086. full_out = full_out.strip()
  1087. pieces = {}
  1088. pieces["long"] = full_out
  1089. pieces["short"] = full_out[:7] # maybe improved later
  1090. pieces["error"] = None
  1091. branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
  1092. # --abbrev-ref was added in git-1.6.3
  1093. if rc != 0 or branch_name is None:
  1094. raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
  1095. branch_name = branch_name.strip()
  1096. if branch_name == "HEAD":
  1097. # If we aren't exactly on a branch, pick a branch which represents
  1098. # the current commit. If all else fails, we are on a branchless
  1099. # commit.
  1100. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
  1101. # --contains was added in git-1.5.4
  1102. if rc != 0 or branches is None:
  1103. raise NotThisMethod("'git branch --contains' returned error")
  1104. branches = branches.split("\n")
  1105. # Remove the first line if we're running detached
  1106. if "(" in branches[0]:
  1107. branches.pop(0)
  1108. # Strip off the leading "* " from the list of branches.
  1109. branches = [branch[2:] for branch in branches]
  1110. if "master" in branches:
  1111. branch_name = "master"
  1112. elif not branches:
  1113. branch_name = None
  1114. else:
  1115. # Pick the first branch that is returned. Good or bad.
  1116. branch_name = branches[0]
  1117. pieces["branch"] = branch_name
  1118. # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
  1119. # TAG might have hyphens.
  1120. git_describe = describe_out
  1121. # look for -dirty suffix
  1122. dirty = git_describe.endswith("-dirty")
  1123. pieces["dirty"] = dirty
  1124. if dirty:
  1125. git_describe = git_describe[: git_describe.rindex("-dirty")]
  1126. # now we have TAG-NUM-gHEX or HEX
  1127. if "-" in git_describe:
  1128. # TAG-NUM-gHEX
  1129. mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
  1130. if not mo:
  1131. # unparsable. Maybe git-describe is misbehaving?
  1132. pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
  1133. return pieces
  1134. # tag
  1135. full_tag = mo.group(1)
  1136. if not full_tag.startswith(tag_prefix):
  1137. if verbose:
  1138. fmt = "tag '%s' doesn't start with prefix '%s'"
  1139. print(fmt % (full_tag, tag_prefix))
  1140. pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
  1141. full_tag,
  1142. tag_prefix,
  1143. )
  1144. return pieces
  1145. pieces["closest-tag"] = full_tag[len(tag_prefix) :]
  1146. # distance: number of commits since tag
  1147. pieces["distance"] = int(mo.group(2))
  1148. # commit: short hex revision ID
  1149. pieces["short"] = mo.group(3)
  1150. else:
  1151. # HEX: no tags
  1152. pieces["closest-tag"] = None
  1153. out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
  1154. pieces["distance"] = len(out.split()) # total number of commits
  1155. # commit date: see ISO-8601 comment in git_versions_from_keywords()
  1156. date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip()
  1157. # Use only the last line. Previous lines may contain GPG signature
  1158. # information.
  1159. date = date.splitlines()[-1]
  1160. pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
  1161. return pieces
  1162. def do_vcs_install(versionfile_source, ipy):
  1163. """Git-specific installation logic for Versioneer.
  1164. For Git, this means creating/changing .gitattributes to mark _version.py
  1165. for export-subst keyword substitution.
  1166. """
  1167. GITS = ["git"]
  1168. if sys.platform == "win32":
  1169. GITS = ["git.cmd", "git.exe"]
  1170. files = [versionfile_source]
  1171. if ipy:
  1172. files.append(ipy)
  1173. if "VERSIONEER_PEP518" not in globals():
  1174. try:
  1175. my_path = __file__
  1176. if my_path.endswith((".pyc", ".pyo")):
  1177. my_path = os.path.splitext(my_path)[0] + ".py"
  1178. versioneer_file = os.path.relpath(my_path)
  1179. except NameError:
  1180. versioneer_file = "versioneer.py"
  1181. files.append(versioneer_file)
  1182. present = False
  1183. try:
  1184. with open(".gitattributes", "r") as fobj:
  1185. for line in fobj:
  1186. if line.strip().startswith(versionfile_source):
  1187. if "export-subst" in line.strip().split()[1:]:
  1188. present = True
  1189. break
  1190. except OSError:
  1191. pass
  1192. if not present:
  1193. with open(".gitattributes", "a+") as fobj:
  1194. fobj.write(f"{versionfile_source} export-subst\n")
  1195. files.append(".gitattributes")
  1196. run_command(GITS, ["add", "--"] + files)
  1197. def versions_from_parentdir(parentdir_prefix, root, verbose):
  1198. """Try to determine the version from the parent directory name.
  1199. Source tarballs conventionally unpack into a directory that includes both
  1200. the project name and a version string. We will also support searching up
  1201. two directory levels for an appropriately named parent directory
  1202. """
  1203. rootdirs = []
  1204. for _ in range(3):
  1205. dirname = os.path.basename(root)
  1206. if dirname.startswith(parentdir_prefix):
  1207. return {
  1208. "version": dirname[len(parentdir_prefix) :],
  1209. "full-revisionid": None,
  1210. "dirty": False,
  1211. "error": None,
  1212. "date": None,
  1213. }
  1214. rootdirs.append(root)
  1215. root = os.path.dirname(root) # up a level
  1216. if verbose:
  1217. print(
  1218. "Tried directories %s but none started with prefix %s"
  1219. % (str(rootdirs), parentdir_prefix)
  1220. )
  1221. raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
  1222. SHORT_VERSION_PY = """
  1223. # This file was generated by 'versioneer.py' (0.28) from
  1224. # revision-control system data, or from the parent directory name of an
  1225. # unpacked source archive. Distribution tarballs contain a pre-generated copy
  1226. # of this file.
  1227. import json
  1228. version_json = '''
  1229. %s
  1230. ''' # END VERSION_JSON
  1231. def get_versions():
  1232. return json.loads(version_json)
  1233. """
  1234. def versions_from_file(filename):
  1235. """Try to determine the version from _version.py if present."""
  1236. try:
  1237. with open(filename) as f:
  1238. contents = f.read()
  1239. except OSError:
  1240. raise NotThisMethod("unable to read _version.py")
  1241. mo = re.search(
  1242. r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S
  1243. )
  1244. if not mo:
  1245. mo = re.search(
  1246. r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S
  1247. )
  1248. if not mo:
  1249. raise NotThisMethod("no version_json in _version.py")
  1250. return json.loads(mo.group(1))
  1251. def write_to_version_file(filename, versions):
  1252. """Write the given version number to the given _version.py file."""
  1253. os.unlink(filename)
  1254. contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": "))
  1255. with open(filename, "w") as f:
  1256. f.write(SHORT_VERSION_PY % contents)
  1257. print("set %s to '%s'" % (filename, versions["version"]))
  1258. def plus_or_dot(pieces):
  1259. """Return a + if we don't already have one, else return a ."""
  1260. if "+" in pieces.get("closest-tag", ""):
  1261. return "."
  1262. return "+"
  1263. def render_pep440(pieces):
  1264. """Build up version string, with post-release "local version identifier".
  1265. Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
  1266. get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
  1267. Exceptions:
  1268. 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
  1269. """
  1270. if pieces["closest-tag"]:
  1271. rendered = pieces["closest-tag"]
  1272. if pieces["distance"] or pieces["dirty"]:
  1273. rendered += plus_or_dot(pieces)
  1274. rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
  1275. if pieces["dirty"]:
  1276. rendered += ".dirty"
  1277. else:
  1278. # exception #1
  1279. rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
  1280. if pieces["dirty"]:
  1281. rendered += ".dirty"
  1282. return rendered
  1283. def render_pep440_branch(pieces):
  1284. """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
  1285. The ".dev0" means not master branch. Note that .dev0 sorts backwards
  1286. (a feature branch will appear "older" than the master branch).
  1287. Exceptions:
  1288. 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
  1289. """
  1290. if pieces["closest-tag"]:
  1291. rendered = pieces["closest-tag"]
  1292. if pieces["distance"] or pieces["dirty"]:
  1293. if pieces["branch"] != "master":
  1294. rendered += ".dev0"
  1295. rendered += plus_or_dot(pieces)
  1296. rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
  1297. if pieces["dirty"]:
  1298. rendered += ".dirty"
  1299. else:
  1300. # exception #1
  1301. rendered = "0"
  1302. if pieces["branch"] != "master":
  1303. rendered += ".dev0"
  1304. rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
  1305. if pieces["dirty"]:
  1306. rendered += ".dirty"
  1307. return rendered
  1308. def pep440_split_post(ver):
  1309. """Split pep440 version string at the post-release segment.
  1310. Returns the release segments before the post-release and the
  1311. post-release version number (or -1 if no post-release segment is present).
  1312. """
  1313. vc = str.split(ver, ".post")
  1314. return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
  1315. def render_pep440_pre(pieces):
  1316. """TAG[.postN.devDISTANCE] -- No -dirty.
  1317. Exceptions:
  1318. 1: no tags. 0.post0.devDISTANCE
  1319. """
  1320. if pieces["closest-tag"]:
  1321. if pieces["distance"]:
  1322. # update the post release segment
  1323. tag_version, post_version = pep440_split_post(pieces["closest-tag"])
  1324. rendered = tag_version
  1325. if post_version is not None:
  1326. rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"])
  1327. else:
  1328. rendered += ".post0.dev%d" % (pieces["distance"])
  1329. else:
  1330. # no commits, use the tag as the version
  1331. rendered = pieces["closest-tag"]
  1332. else:
  1333. # exception #1
  1334. rendered = "0.post0.dev%d" % pieces["distance"]
  1335. return rendered
  1336. def render_pep440_post(pieces):
  1337. """TAG[.postDISTANCE[.dev0]+gHEX] .
  1338. The ".dev0" means dirty. Note that .dev0 sorts backwards
  1339. (a dirty tree will appear "older" than the corresponding clean one),
  1340. but you shouldn't be releasing software with -dirty anyways.
  1341. Exceptions:
  1342. 1: no tags. 0.postDISTANCE[.dev0]
  1343. """
  1344. if pieces["closest-tag"]:
  1345. rendered = pieces["closest-tag"]
  1346. if pieces["distance"] or pieces["dirty"]:
  1347. rendered += ".post%d" % pieces["distance"]
  1348. if pieces["dirty"]:
  1349. rendered += ".dev0"
  1350. rendered += plus_or_dot(pieces)
  1351. rendered += "g%s" % pieces["short"]
  1352. else:
  1353. # exception #1
  1354. rendered = "0.post%d" % pieces["distance"]
  1355. if pieces["dirty"]:
  1356. rendered += ".dev0"
  1357. rendered += "+g%s" % pieces["short"]
  1358. return rendered
  1359. def render_pep440_post_branch(pieces):
  1360. """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
  1361. The ".dev0" means not master branch.
  1362. Exceptions:
  1363. 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
  1364. """
  1365. if pieces["closest-tag"]:
  1366. rendered = pieces["closest-tag"]
  1367. if pieces["distance"] or pieces["dirty"]:
  1368. rendered += ".post%d" % pieces["distance"]
  1369. if pieces["branch"] != "master":
  1370. rendered += ".dev0"
  1371. rendered += plus_or_dot(pieces)
  1372. rendered += "g%s" % pieces["short"]
  1373. if pieces["dirty"]:
  1374. rendered += ".dirty"
  1375. else:
  1376. # exception #1
  1377. rendered = "0.post%d" % pieces["distance"]
  1378. if pieces["branch"] != "master":
  1379. rendered += ".dev0"
  1380. rendered += "+g%s" % pieces["short"]
  1381. if pieces["dirty"]:
  1382. rendered += ".dirty"
  1383. return rendered
  1384. def render_pep440_old(pieces):
  1385. """TAG[.postDISTANCE[.dev0]] .
  1386. The ".dev0" means dirty.
  1387. Exceptions:
  1388. 1: no tags. 0.postDISTANCE[.dev0]
  1389. """
  1390. if pieces["closest-tag"]:
  1391. rendered = pieces["closest-tag"]
  1392. if pieces["distance"] or pieces["dirty"]:
  1393. rendered += ".post%d" % pieces["distance"]
  1394. if pieces["dirty"]:
  1395. rendered += ".dev0"
  1396. else:
  1397. # exception #1
  1398. rendered = "0.post%d" % pieces["distance"]
  1399. if pieces["dirty"]:
  1400. rendered += ".dev0"
  1401. return rendered
  1402. def render_git_describe(pieces):
  1403. """TAG[-DISTANCE-gHEX][-dirty].
  1404. Like 'git describe --tags --dirty --always'.
  1405. Exceptions:
  1406. 1: no tags. HEX[-dirty] (note: no 'g' prefix)
  1407. """
  1408. if pieces["closest-tag"]:
  1409. rendered = pieces["closest-tag"]
  1410. if pieces["distance"]:
  1411. rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
  1412. else:
  1413. # exception #1
  1414. rendered = pieces["short"]
  1415. if pieces["dirty"]:
  1416. rendered += "-dirty"
  1417. return rendered
  1418. def render_git_describe_long(pieces):
  1419. """TAG-DISTANCE-gHEX[-dirty].
  1420. Like 'git describe --tags --dirty --always -long'.
  1421. The distance/hash is unconditional.
  1422. Exceptions:
  1423. 1: no tags. HEX[-dirty] (note: no 'g' prefix)
  1424. """
  1425. if pieces["closest-tag"]:
  1426. rendered = pieces["closest-tag"]
  1427. rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
  1428. else:
  1429. # exception #1
  1430. rendered = pieces["short"]
  1431. if pieces["dirty"]:
  1432. rendered += "-dirty"
  1433. return rendered
  1434. def render(pieces, style):
  1435. """Render the given version pieces into the requested style."""
  1436. if pieces["error"]:
  1437. return {
  1438. "version": "unknown",
  1439. "full-revisionid": pieces.get("long"),
  1440. "dirty": None,
  1441. "error": pieces["error"],
  1442. "date": None,
  1443. }
  1444. if not style or style == "default":
  1445. style = "pep440" # the default
  1446. if style == "pep440":
  1447. rendered = render_pep440(pieces)
  1448. elif style == "pep440-branch":
  1449. rendered = render_pep440_branch(pieces)
  1450. elif style == "pep440-pre":
  1451. rendered = render_pep440_pre(pieces)
  1452. elif style == "pep440-post":
  1453. rendered = render_pep440_post(pieces)
  1454. elif style == "pep440-post-branch":
  1455. rendered = render_pep440_post_branch(pieces)
  1456. elif style == "pep440-old":
  1457. rendered = render_pep440_old(pieces)
  1458. elif style == "git-describe":
  1459. rendered = render_git_describe(pieces)
  1460. elif style == "git-describe-long":
  1461. rendered = render_git_describe_long(pieces)
  1462. else:
  1463. raise ValueError("unknown style '%s'" % style)
  1464. return {
  1465. "version": rendered,
  1466. "full-revisionid": pieces["long"],
  1467. "dirty": pieces["dirty"],
  1468. "error": None,
  1469. "date": pieces.get("date"),
  1470. }
  1471. class VersioneerBadRootError(Exception):
  1472. """The project root directory is unknown or missing key files."""
  1473. def get_versions(verbose=False):
  1474. """Get the project version from whatever source is available.
  1475. Returns dict with two keys: 'version' and 'full'.
  1476. """
  1477. if "versioneer" in sys.modules:
  1478. # see the discussion in cmdclass.py:get_cmdclass()
  1479. del sys.modules["versioneer"]
  1480. root = get_root()
  1481. cfg = get_config_from_root(root)
  1482. assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg"
  1483. handlers = HANDLERS.get(cfg.VCS)
  1484. assert handlers, "unrecognized VCS '%s'" % cfg.VCS
  1485. verbose = verbose or cfg.verbose
  1486. assert (
  1487. cfg.versionfile_source is not None
  1488. ), "please set versioneer.versionfile_source"
  1489. assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix"
  1490. versionfile_abs = os.path.join(root, cfg.versionfile_source)
  1491. # extract version from first of: _version.py, VCS command (e.g. 'git
  1492. # describe'), parentdir. This is meant to work for developers using a
  1493. # source checkout, for users of a tarball created by 'setup.py sdist',
  1494. # and for users of a tarball/zipball created by 'git archive' or github's
  1495. # download-from-tag feature or the equivalent in other VCSes.
  1496. get_keywords_f = handlers.get("get_keywords")
  1497. from_keywords_f = handlers.get("keywords")
  1498. if get_keywords_f and from_keywords_f:
  1499. try:
  1500. keywords = get_keywords_f(versionfile_abs)
  1501. ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)
  1502. if verbose:
  1503. print("got version from expanded keyword %s" % ver)
  1504. return ver
  1505. except NotThisMethod:
  1506. pass
  1507. try:
  1508. ver = versions_from_file(versionfile_abs)
  1509. if verbose:
  1510. print("got version from file %s %s" % (versionfile_abs, ver))
  1511. return ver
  1512. except NotThisMethod:
  1513. pass
  1514. from_vcs_f = handlers.get("pieces_from_vcs")
  1515. if from_vcs_f:
  1516. try:
  1517. pieces = from_vcs_f(cfg.tag_prefix, root, verbose)
  1518. ver = render(pieces, cfg.style)
  1519. if verbose:
  1520. print("got version from VCS %s" % ver)
  1521. return ver
  1522. except NotThisMethod:
  1523. pass
  1524. try:
  1525. if cfg.parentdir_prefix:
  1526. ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
  1527. if verbose:
  1528. print("got version from parentdir %s" % ver)
  1529. return ver
  1530. except NotThisMethod:
  1531. pass
  1532. if verbose:
  1533. print("unable to compute version")
  1534. return {
  1535. "version": "0+unknown",
  1536. "full-revisionid": None,
  1537. "dirty": None,
  1538. "error": "unable to compute version",
  1539. "date": None,
  1540. }
  1541. def get_version():
  1542. """Get the short version string for this project."""
  1543. return get_versions()["version"]
  1544. def get_cmdclass(cmdclass=None):
  1545. """Get the custom setuptools subclasses used by Versioneer.
  1546. If the package uses a different cmdclass (e.g. one from numpy), it
  1547. should be provide as an argument.
  1548. """
  1549. if "versioneer" in sys.modules:
  1550. del sys.modules["versioneer"]
  1551. # this fixes the "python setup.py develop" case (also 'install' and
  1552. # 'easy_install .'), in which subdependencies of the main project are
  1553. # built (using setup.py bdist_egg) in the same python process. Assume
  1554. # a main project A and a dependency B, which use different versions
  1555. # of Versioneer. A's setup.py imports A's Versioneer, leaving it in
  1556. # sys.modules by the time B's setup.py is executed, causing B to run
  1557. # with the wrong versioneer. Setuptools wraps the sub-dep builds in a
  1558. # sandbox that restores sys.modules to it's pre-build state, so the
  1559. # parent is protected against the child's "import versioneer". By
  1560. # removing ourselves from sys.modules here, before the child build
  1561. # happens, we protect the child from the parent's versioneer too.
  1562. # Also see https://github.com/python-versioneer/python-versioneer/issues/52
  1563. cmds = {} if cmdclass is None else cmdclass.copy()
  1564. # we add "version" to setuptools
  1565. from setuptools import Command
  1566. class cmd_version(Command):
  1567. description = "report generated version string"
  1568. user_options = []
  1569. boolean_options = []
  1570. def initialize_options(self):
  1571. pass
  1572. def finalize_options(self):
  1573. pass
  1574. def run(self):
  1575. vers = get_versions(verbose=True)
  1576. print("Version: %s" % vers["version"])
  1577. print(" full-revisionid: %s" % vers.get("full-revisionid"))
  1578. print(" dirty: %s" % vers.get("dirty"))
  1579. print(" date: %s" % vers.get("date"))
  1580. if vers["error"]:
  1581. print(" error: %s" % vers["error"])
  1582. cmds["version"] = cmd_version
  1583. # we override "build_py" in setuptools
  1584. #
  1585. # most invocation pathways end up running build_py:
  1586. # distutils/build -> build_py
  1587. # distutils/install -> distutils/build ->..
  1588. # setuptools/bdist_wheel -> distutils/install ->..
  1589. # setuptools/bdist_egg -> distutils/install_lib -> build_py
  1590. # setuptools/install -> bdist_egg ->..
  1591. # setuptools/develop -> ?
  1592. # pip install:
  1593. # copies source tree to a tempdir before running egg_info/etc
  1594. # if .git isn't copied too, 'git describe' will fail
  1595. # then does setup.py bdist_wheel, or sometimes setup.py install
  1596. # setup.py egg_info -> ?
  1597. # pip install -e . and setuptool/editable_wheel will invoke build_py
  1598. # but the build_py command is not expected to copy any files.
  1599. # we override different "build_py" commands for both environments
  1600. if "build_py" in cmds:
  1601. _build_py = cmds["build_py"]
  1602. else:
  1603. from setuptools.command.build_py import build_py as _build_py
  1604. class cmd_build_py(_build_py):
  1605. def run(self):
  1606. root = get_root()
  1607. cfg = get_config_from_root(root)
  1608. versions = get_versions()
  1609. _build_py.run(self)
  1610. if getattr(self, "editable_mode", False):
  1611. # During editable installs `.py` and data files are
  1612. # not copied to build_lib
  1613. return
  1614. # now locate _version.py in the new build/ directory and replace
  1615. # it with an updated value
  1616. if cfg.versionfile_build:
  1617. target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build)
  1618. print("UPDATING %s" % target_versionfile)
  1619. write_to_version_file(target_versionfile, versions)
  1620. cmds["build_py"] = cmd_build_py
  1621. if "build_ext" in cmds:
  1622. _build_ext = cmds["build_ext"]
  1623. else:
  1624. from setuptools.command.build_ext import build_ext as _build_ext
  1625. class cmd_build_ext(_build_ext):
  1626. def run(self):
  1627. root = get_root()
  1628. cfg = get_config_from_root(root)
  1629. versions = get_versions()
  1630. _build_ext.run(self)
  1631. if self.inplace:
  1632. # build_ext --inplace will only build extensions in
  1633. # build/lib<..> dir with no _version.py to write to.
  1634. # As in place builds will already have a _version.py
  1635. # in the module dir, we do not need to write one.
  1636. return
  1637. # now locate _version.py in the new build/ directory and replace
  1638. # it with an updated value
  1639. if not cfg.versionfile_build:
  1640. return
  1641. target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build)
  1642. if not os.path.exists(target_versionfile):
  1643. print(
  1644. f"Warning: {target_versionfile} does not exist, skipping "
  1645. "version update. This can happen if you are running build_ext "
  1646. "without first running build_py."
  1647. )
  1648. return
  1649. print("UPDATING %s" % target_versionfile)
  1650. write_to_version_file(target_versionfile, versions)
  1651. cmds["build_ext"] = cmd_build_ext
  1652. if "cx_Freeze" in sys.modules: # cx_freeze enabled?
  1653. from cx_Freeze.dist import build_exe as _build_exe
  1654. # nczeczulin reports that py2exe won't like the pep440-style string
  1655. # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g.
  1656. # setup(console=[{
  1657. # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION
  1658. # "product_version": versioneer.get_version(),
  1659. # ...
  1660. class cmd_build_exe(_build_exe):
  1661. def run(self):
  1662. root = get_root()
  1663. cfg = get_config_from_root(root)
  1664. versions = get_versions()
  1665. target_versionfile = cfg.versionfile_source
  1666. print("UPDATING %s" % target_versionfile)
  1667. write_to_version_file(target_versionfile, versions)
  1668. _build_exe.run(self)
  1669. os.unlink(target_versionfile)
  1670. with open(cfg.versionfile_source, "w") as f:
  1671. LONG = LONG_VERSION_PY[cfg.VCS]
  1672. f.write(
  1673. LONG
  1674. % {
  1675. "DOLLAR": "$",
  1676. "STYLE": cfg.style,
  1677. "TAG_PREFIX": cfg.tag_prefix,
  1678. "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1679. "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1680. }
  1681. )
  1682. cmds["build_exe"] = cmd_build_exe
  1683. del cmds["build_py"]
  1684. if "py2exe" in sys.modules: # py2exe enabled?
  1685. try:
  1686. from py2exe.setuptools_buildexe import py2exe as _py2exe
  1687. except ImportError:
  1688. from py2exe.distutils_buildexe import py2exe as _py2exe
  1689. class cmd_py2exe(_py2exe):
  1690. def run(self):
  1691. root = get_root()
  1692. cfg = get_config_from_root(root)
  1693. versions = get_versions()
  1694. target_versionfile = cfg.versionfile_source
  1695. print("UPDATING %s" % target_versionfile)
  1696. write_to_version_file(target_versionfile, versions)
  1697. _py2exe.run(self)
  1698. os.unlink(target_versionfile)
  1699. with open(cfg.versionfile_source, "w") as f:
  1700. LONG = LONG_VERSION_PY[cfg.VCS]
  1701. f.write(
  1702. LONG
  1703. % {
  1704. "DOLLAR": "$",
  1705. "STYLE": cfg.style,
  1706. "TAG_PREFIX": cfg.tag_prefix,
  1707. "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1708. "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1709. }
  1710. )
  1711. cmds["py2exe"] = cmd_py2exe
  1712. # sdist farms its file list building out to egg_info
  1713. if "egg_info" in cmds:
  1714. _egg_info = cmds["egg_info"]
  1715. else:
  1716. from setuptools.command.egg_info import egg_info as _egg_info
  1717. class cmd_egg_info(_egg_info):
  1718. def find_sources(self):
  1719. # egg_info.find_sources builds the manifest list and writes it
  1720. # in one shot
  1721. super().find_sources()
  1722. # Modify the filelist and normalize it
  1723. root = get_root()
  1724. cfg = get_config_from_root(root)
  1725. self.filelist.append("versioneer.py")
  1726. if cfg.versionfile_source:
  1727. # There are rare cases where versionfile_source might not be
  1728. # included by default, so we must be explicit
  1729. self.filelist.append(cfg.versionfile_source)
  1730. self.filelist.sort()
  1731. self.filelist.remove_duplicates()
  1732. # The write method is hidden in the manifest_maker instance that
  1733. # generated the filelist and was thrown away
  1734. # We will instead replicate their final normalization (to unicode,
  1735. # and POSIX-style paths)
  1736. from setuptools import unicode_utils
  1737. normalized = [
  1738. unicode_utils.filesys_decode(f).replace(os.sep, "/")
  1739. for f in self.filelist.files
  1740. ]
  1741. manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
  1742. with open(manifest_filename, "w") as fobj:
  1743. fobj.write("\n".join(normalized))
  1744. cmds["egg_info"] = cmd_egg_info
  1745. # we override different "sdist" commands for both environments
  1746. if "sdist" in cmds:
  1747. _sdist = cmds["sdist"]
  1748. else:
  1749. from setuptools.command.sdist import sdist as _sdist
  1750. class cmd_sdist(_sdist):
  1751. def run(self):
  1752. versions = get_versions()
  1753. self._versioneer_generated_versions = versions
  1754. # unless we update this, the command will keep using the old
  1755. # version
  1756. self.distribution.metadata.version = versions["version"]
  1757. return _sdist.run(self)
  1758. def make_release_tree(self, base_dir, files):
  1759. root = get_root()
  1760. cfg = get_config_from_root(root)
  1761. _sdist.make_release_tree(self, base_dir, files)
  1762. # now locate _version.py in the new base_dir directory
  1763. # (remembering that it may be a hardlink) and replace it with an
  1764. # updated value
  1765. target_versionfile = os.path.join(base_dir, cfg.versionfile_source)
  1766. print("UPDATING %s" % target_versionfile)
  1767. write_to_version_file(
  1768. target_versionfile, self._versioneer_generated_versions
  1769. )
  1770. cmds["sdist"] = cmd_sdist
  1771. return cmds
  1772. CONFIG_ERROR = """
  1773. setup.cfg is missing the necessary Versioneer configuration. You need
  1774. a section like:
  1775. [versioneer]
  1776. VCS = git
  1777. style = pep440
  1778. versionfile_source = src/myproject/_version.py
  1779. versionfile_build = myproject/_version.py
  1780. tag_prefix =
  1781. parentdir_prefix = myproject-
  1782. You will also need to edit your setup.py to use the results:
  1783. import versioneer
  1784. setup(version=versioneer.get_version(),
  1785. cmdclass=versioneer.get_cmdclass(), ...)
  1786. Please read the docstring in ./versioneer.py for configuration instructions,
  1787. edit setup.cfg, and re-run the installer or 'python versioneer.py setup'.
  1788. """
  1789. SAMPLE_CONFIG = """
  1790. # See the docstring in versioneer.py for instructions. Note that you must
  1791. # re-run 'versioneer.py setup' after changing this section, and commit the
  1792. # resulting files.
  1793. [versioneer]
  1794. #VCS = git
  1795. #style = pep440
  1796. #versionfile_source =
  1797. #versionfile_build =
  1798. #tag_prefix =
  1799. #parentdir_prefix =
  1800. """
  1801. OLD_SNIPPET = """
  1802. from ._version import get_versions
  1803. __version__ = get_versions()['version']
  1804. del get_versions
  1805. """
  1806. INIT_PY_SNIPPET = """
  1807. from . import {0}
  1808. __version__ = {0}.get_versions()['version']
  1809. """
  1810. def do_setup():
  1811. """Do main VCS-independent setup function for installing Versioneer."""
  1812. root = get_root()
  1813. try:
  1814. cfg = get_config_from_root(root)
  1815. except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e:
  1816. if isinstance(e, (OSError, configparser.NoSectionError)):
  1817. print("Adding sample versioneer config to setup.cfg", file=sys.stderr)
  1818. with open(os.path.join(root, "setup.cfg"), "a") as f:
  1819. f.write(SAMPLE_CONFIG)
  1820. print(CONFIG_ERROR, file=sys.stderr)
  1821. return 1
  1822. print(" creating %s" % cfg.versionfile_source)
  1823. with open(cfg.versionfile_source, "w") as f:
  1824. LONG = LONG_VERSION_PY[cfg.VCS]
  1825. f.write(
  1826. LONG
  1827. % {
  1828. "DOLLAR": "$",
  1829. "STYLE": cfg.style,
  1830. "TAG_PREFIX": cfg.tag_prefix,
  1831. "PARENTDIR_PREFIX": cfg.parentdir_prefix,
  1832. "VERSIONFILE_SOURCE": cfg.versionfile_source,
  1833. }
  1834. )
  1835. ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py")
  1836. if os.path.exists(ipy):
  1837. try:
  1838. with open(ipy, "r") as f:
  1839. old = f.read()
  1840. except OSError:
  1841. old = ""
  1842. module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0]
  1843. snippet = INIT_PY_SNIPPET.format(module)
  1844. if OLD_SNIPPET in old:
  1845. print(" replacing boilerplate in %s" % ipy)
  1846. with open(ipy, "w") as f:
  1847. f.write(old.replace(OLD_SNIPPET, snippet))
  1848. elif snippet not in old:
  1849. print(" appending to %s" % ipy)
  1850. with open(ipy, "a") as f:
  1851. f.write(snippet)
  1852. else:
  1853. print(" %s unmodified" % ipy)
  1854. else:
  1855. print(" %s doesn't exist, ok" % ipy)
  1856. ipy = None
  1857. # Make VCS-specific changes. For git, this means creating/changing
  1858. # .gitattributes to mark _version.py for export-subst keyword
  1859. # substitution.
  1860. do_vcs_install(cfg.versionfile_source, ipy)
  1861. return 0
  1862. def scan_setup_py():
  1863. """Validate the contents of setup.py against Versioneer's expectations."""
  1864. found = set()
  1865. setters = False
  1866. errors = 0
  1867. with open("setup.py", "r") as f:
  1868. for line in f.readlines():
  1869. if "import versioneer" in line:
  1870. found.add("import")
  1871. if "versioneer.get_cmdclass()" in line:
  1872. found.add("cmdclass")
  1873. if "versioneer.get_version()" in line:
  1874. found.add("get_version")
  1875. if "versioneer.VCS" in line:
  1876. setters = True
  1877. if "versioneer.versionfile_source" in line:
  1878. setters = True
  1879. if len(found) != 3:
  1880. print("")
  1881. print("Your setup.py appears to be missing some important items")
  1882. print("(but I might be wrong). Please make sure it has something")
  1883. print("roughly like the following:")
  1884. print("")
  1885. print(" import versioneer")
  1886. print(" setup( version=versioneer.get_version(),")
  1887. print(" cmdclass=versioneer.get_cmdclass(), ...)")
  1888. print("")
  1889. errors += 1
  1890. if setters:
  1891. print("You should remove lines like 'versioneer.VCS = ' and")
  1892. print("'versioneer.versionfile_source = ' . This configuration")
  1893. print("now lives in setup.cfg, and should be removed from setup.py")
  1894. print("")
  1895. errors += 1
  1896. return errors
  1897. def setup_command():
  1898. """Set up Versioneer and exit with appropriate error code."""
  1899. errors = do_setup()
  1900. errors += scan_setup_py()
  1901. sys.exit(1 if errors else 0)
  1902. if __name__ == "__main__":
  1903. cmd = sys.argv[1]
  1904. if cmd == "setup":
  1905. setup_command()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...