1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
|
# ==================================================================================================================== #
# _____ _ _ __ __ _ _ #
# _ __ _ |_ _|__ ___ | (_)_ __ __ \ \ / /__ _ __ ___(_) ___ _ __ (_)_ __ __ _ #
# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` \ \ / / _ \ '__/ __| |/ _ \| '_ \| | '_ \ / _` | #
# | |_) | |_| || | (_) | (_) | | | | | | (_| |\ V / __/ | \__ \ | (_) | | | | | | | | (_| | #
# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)_/ \___|_| |___/_|\___/|_| |_|_|_| |_|\__, | #
# |_| |___/ |___/ |___/ #
# ==================================================================================================================== #
# Authors: #
# Patrick Lehmann #
# #
# License: #
# ==================================================================================================================== #
# Copyright 2020-2026 Patrick Lehmann - Bötzingen, Germany #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
# SPDX-License-Identifier: Apache-2.0 #
# ==================================================================================================================== #
#
"""
Implementation of semantic and date versioning version-numbers.
.. hint::
See :ref:`high-level help <VERSIONING>` for explanations and usage examples.
"""
from collections.abc import Iterable as abc_Iterable
from enum import Flag, Enum
from re import compile as re_compile
from typing import Optional as Nullable, Union, Callable, Any, Generic, TypeVar, Iterable, Iterator, List
try:
from pyTooling.Decorators import export, readonly
from pyTooling.MetaClasses import ExtendedType, abstractmethod, mustoverride
from pyTooling.Exceptions import ToolingException
from pyTooling.Common import getFullyQualifiedName
except (ImportError, ModuleNotFoundError): # pragma: no cover
print("[pyTooling.Versioning] Could not import from 'pyTooling.*'!")
try:
from Decorators import export, readonly
from MetaClasses import ExtendedType, abstractmethod, mustoverride
from Exceptions import ToolingException
from Common import getFullyQualifiedName
except (ImportError, ModuleNotFoundError) as ex: # pragma: no cover
print("[pyTooling.Versioning] Could not import directly!")
raise ex
@export
class Parts(Flag):
"""Enumeration describing parts of a version number that can be present."""
Unknown = 0 #: Undocumented
Major = 1 #: Major number is present. (e.g. X in ``vX.0.0``).
Year = 1 #: Year is present. (e.g. X in ``XXXX.10``).
Minor = 2 #: Minor number is present. (e.g. Y in ``v0.Y.0``).
Month = 2 #: Month is present. (e.g. X in ``2024.YY``).
Week = 2 #: Week is present. (e.g. X in ``2024.YY``).
Micro = 4 #: Patch number is present. (e.g. Z in ``v0.0.Z``).
Patch = 4 #: Patch number is present. (e.g. Z in ``v0.0.Z``).
Day = 4 #: Day is present. (e.g. X in ``2024.10.ZZ``).
Level = 8 #: Release level is present.
Dev = 16 #: Development part is present.
Build = 32 #: Build number is present. (e.g. bbbb in ``v0.0.0.bbbb``)
Post = 64 #: Post-release number is present.
Prefix = 128 #: Prefix is present.
Postfix = 256 #: Postfix is present.
Hash = 512 #: Hash is present.
# AHead = 256
@export
class ReleaseLevel(Enum):
"""Enumeration describing the version's maturity level."""
Final = 0 #:
ReleaseCandidate = -10 #:
Development = -20 #:
Gamma = -30 #:
Beta = -40 #:
Alpha = -50 #:
def __eq__(self, other: Any) -> bool:
"""
Compare two release levels if the level is equal to the second operand.
:param other: Operand to compare against.
:returns: ``True``, if release level is equal the second operand's release level.
:raises TypeError: If parameter ``other`` is not of type :class:`ReleaseLevel` or :class:`str`.
"""
if isinstance(other, str):
other = ReleaseLevel(other)
if not isinstance(other, ReleaseLevel):
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by == operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__} or 'str'.")
raise ex
return self is other
def __ne__(self, other: Any) -> bool:
"""
Compare two release levels if the level is unequal to the second operand.
:param other: Operand to compare against.
:returns: ``True``, if release level is unequal the second operand's release level.
:raises TypeError: If parameter ``other`` is not of type :class:`ReleaseLevel` or :class:`str`.
"""
if isinstance(other, str):
other = ReleaseLevel(other)
if not isinstance(other, ReleaseLevel):
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by != operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__} or 'str'.")
raise ex
return self is not other
def __lt__(self, other: Any) -> bool:
"""
Compare two release levels if the level is less than the second operand.
:param other: Operand to compare against.
:returns: ``True``, if release level is less than the second operand.
:raises TypeError: If parameter ``other`` is not of type :class:`ReleaseLevel` or :class:`str`.
"""
if isinstance(other, str):
other = ReleaseLevel(other)
if not isinstance(other, ReleaseLevel):
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by < operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__} or 'str'.")
raise ex
return self.value < other.value
def __le__(self, other: Any) -> bool:
"""
Compare two release levels if the level is less than or equal the second operand.
:param other: Operand to compare against.
:returns: ``True``, if release level is less than or equal the second operand.
:raises TypeError: If parameter ``other`` is not of type :class:`ReleaseLevel` or :class:`str`.
"""
if isinstance(other, str):
other = ReleaseLevel(other)
if not isinstance(other, ReleaseLevel):
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by <=>= operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__} or 'str'.")
raise ex
return self.value <= other.value
def __gt__(self, other: Any) -> bool:
"""
Compare two release levels if the level is greater than the second operand.
:param other: Operand to compare against.
:returns: ``True``, if release level is greater than the second operand.
:raises TypeError: If parameter ``other`` is not of type :class:`ReleaseLevel` or :class:`str`.
"""
if isinstance(other, str):
other = ReleaseLevel(other)
if not isinstance(other, ReleaseLevel):
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by > operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__} or 'str'.")
raise ex
return self.value > other.value
def __ge__(self, other: Any) -> bool:
"""
Compare two release levels if the level is greater than or equal the second operand.
:param other: Operand to compare against.
:returns: ``True``, if release level is greater than or equal the second operand.
:raises TypeError: If parameter ``other`` is not of type :class:`ReleaseLevel` or :class:`str`.
"""
if isinstance(other, str):
other = ReleaseLevel(other)
if not isinstance(other, ReleaseLevel):
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by >= operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__} or 'str'.")
raise ex
return self.value >= other.value
def __hash__(self) -> int:
return hash(self.value)
def __str__(self) -> str:
"""
Returns the release level's string equivalent.
:returns: The string equivalent of the release level.
"""
if self is ReleaseLevel.Final:
return "final"
elif self is ReleaseLevel.ReleaseCandidate:
return "rc"
elif self is ReleaseLevel.Development:
return "dev"
elif self is ReleaseLevel.Beta:
return "beta"
elif self is ReleaseLevel.Alpha:
return "alpha"
raise ToolingException(f"Unknown ReleaseLevel '{self.name}'.")
@export
class Flags(Flag):
"""State enumeration, if a (tagged) version is build from a clean or dirty working directory."""
NoVCS = 0 #: No Version Control System VCS
Clean = 1 #: A versioned build was created from a *clean* working directory.
Dirty = 2 #: A versioned build was created from a *dirty* working directory.
CVS = 16 #: Concurrent Versions System (CVS)
SVN = 32 #: Subversion (SVN)
Git = 64 #: Git
Hg = 128 #: Mercurial (Hg)
@export
def WordSizeValidator(
bits: Nullable[int] = None,
majorBits: Nullable[int] = None,
minorBits: Nullable[int] = None,
microBits: Nullable[int] = None,
buildBits: Nullable[int] = None
):
"""
A factory function to return a validator for Version instances for a positive integer range based on word-sizes in bits.
:param bits: Number of bits to encode any positive version number part.
:param majorBits: Number of bits to encode a positive major number in a version.
:param minorBits: Number of bits to encode a positive minor number in a version.
:param microBits: Number of bits to encode a positive micro number in a version.
:param buildBits: Number of bits to encode a positive build number in a version.
:return: A validation function for Version instances.
"""
majorMax = minorMax = microMax = buildMax = -1
if bits is not None:
majorMax = minorMax = microMax = buildMax = 2**bits - 1
if majorBits is not None:
majorMax = 2**majorBits - 1
if minorBits is not None:
minorMax = 2**minorBits - 1
if microBits is not None:
microMax = 2 ** microBits - 1
if buildBits is not None:
buildMax = 2**buildBits - 1
def validator(version: SemanticVersion) -> bool:
if Parts.Major in version._parts and version._major > majorMax:
raise ValueError(f"Field 'Version.Major' > {majorMax}.")
if Parts.Minor in version._parts and version._minor > minorMax:
raise ValueError(f"Field 'Version.Minor' > {minorMax}.")
if Parts.Micro in version._parts and version._micro > microMax:
raise ValueError(f"Field 'Version.Micro' > {microMax}.")
if Parts.Build in version._parts and version._build > buildMax:
raise ValueError(f"Field 'Version.Build' > {buildMax}.")
return True
return validator
@export
def MaxValueValidator(
max: Nullable[int] = None,
majorMax: Nullable[int] = None,
minorMax: Nullable[int] = None,
microMax: Nullable[int] = None,
buildMax: Nullable[int] = None
):
"""
A factory function to return a validator for Version instances checking for a positive integer range [0..max].
:param max: The upper bound for any positive version number part.
:param majorMax: The upper bound for the positive major number.
:param minorMax: The upper bound for the positive minor number.
:param microMax: The upper bound for the positive micro number.
:param buildMax: The upper bound for the positive build number.
:return: A validation function for Version instances.
"""
if max is not None:
majorMax = minorMax = microMax = buildMax = max
def validator(version: SemanticVersion) -> bool:
if Parts.Major in version._parts and version._major > majorMax:
raise ValueError(f"Field 'Version.Major' > {majorMax}.")
if Parts.Minor in version._parts and version._minor > minorMax:
raise ValueError(f"Field 'Version.Minor' > {minorMax}.")
if Parts.Micro in version._parts and version._micro > microMax:
raise ValueError(f"Field 'Version.Micro' > {microMax}.")
if Parts.Build in version._parts and version._build > buildMax:
raise ValueError(f"Field 'Version.Build' > {buildMax}.")
return True
return validator
@export
class Version(metaclass=ExtendedType, slots=True):
"""Base-class for a version representation."""
__hash: Nullable[int] #: once computed hash of the object
_parts: Parts #: Integer flag enumeration of present parts in a version number.
_prefix: str #: Prefix string
_major: int #: Major number part of the version number.
_minor: int #: Minor number part of the version number.
_micro: int #: Micro number part of the version number.
_releaseLevel: ReleaseLevel #: Release level (alpha, beta, rc, final, ...).
_releaseNumber: int #: Release number (Python calls this a serial).
_post: int #: Post-release version number part.
_dev: int #: Development number
_build: int #: Build number part of the version number.
_postfix: str #: Postfix string
_hash: str #: Hash from version control system.
_flags: Flags #: State if the version in a working directory is clean or dirty compared to a tagged version.
def __init__(
self,
major: int,
minor: Nullable[int] = None,
micro: Nullable[int] = None,
level: Nullable[ReleaseLevel] = ReleaseLevel.Final,
number: Nullable[int] = None,
post: Nullable[int] = None,
dev: Nullable[int] = None,
*,
build: Nullable[int] = None,
postfix: Nullable[str] = None,
prefix: Nullable[str] = None,
hash: Nullable[str] = None,
flags: Flags = Flags.NoVCS
) -> None:
"""
Initializes a version number representation.
:param major: Major number part of the version number.
:param minor: Minor number part of the version number.
:param micro: Micro (patch) number part of the version number.
:param level: Release level (alpha, beta, release candidate, final, ...) of the version number.
:param number: Release number part (in combination with release level) of the version number.
:param post: Post number part of the version number.
:param dev: Development number part of the version number.
:param build: Build number part of the version number.
:param postfix: The version number's postfix.
:param prefix: The version number's prefix.
:param hash: Postfix string.
:param flags: The version number's flags.
:raises TypeError: If parameter 'major' is not of type int.
:raises ValueError: If parameter 'major' is a negative number.
:raises TypeError: If parameter 'minor' is not of type int.
:raises ValueError: If parameter 'minor' is a negative number.
:raises TypeError: If parameter 'micro' is not of type int.
:raises ValueError: If parameter 'micro' is a negative number.
:raises TypeError: If parameter 'build' is not of type int.
:raises ValueError: If parameter 'build' is a negative number.
:raises TypeError: If parameter 'prefix' is not of type str.
:raises TypeError: If parameter 'postfix' is not of type str.
"""
self.__hash = None
if not isinstance(major, int):
raise TypeError("Parameter 'major' is not of type 'int'.")
elif major < 0:
raise ValueError("Parameter 'major' is negative.")
self._parts = Parts.Major
self._major = major
if minor is not None:
if not isinstance(minor, int):
raise TypeError("Parameter 'minor' is not of type 'int'.")
elif minor < 0:
raise ValueError("Parameter 'minor' is negative.")
self._parts |= Parts.Minor
self._minor = minor
else:
self._minor = 0
if micro is not None:
if not isinstance(micro, int):
raise TypeError("Parameter 'micro' is not of type 'int'.")
elif micro < 0:
raise ValueError("Parameter 'micro' is negative.")
self._parts |= Parts.Micro
self._micro = micro
else:
self._micro = 0
if level is None:
raise ValueError("Parameter 'level' is None.")
elif not isinstance(level, ReleaseLevel):
raise TypeError("Parameter 'level' is not of type 'ReleaseLevel'.")
elif level is ReleaseLevel.Final:
if number is not None:
raise ValueError("Parameter 'number' must be None, if parameter 'level' is 'Final'.")
self._parts |= Parts.Level
self._releaseLevel = level
self._releaseNumber = 0
else:
self._parts |= Parts.Level
self._releaseLevel = level
if number is not None:
if not isinstance(number, int):
raise TypeError("Parameter 'number' is not of type 'int'.")
elif number < 0:
raise ValueError("Parameter 'number' is negative.")
self._releaseNumber = number
else:
self._releaseNumber = 0
if dev is not None:
if not isinstance(dev, int):
raise TypeError("Parameter 'dev' is not of type 'int'.")
elif dev < 0:
raise ValueError("Parameter 'dev' is negative.")
self._parts |= Parts.Dev
self._dev = dev
else:
self._dev = 0
if post is not None:
if not isinstance(post, int):
raise TypeError("Parameter 'post' is not of type 'int'.")
elif post < 0:
raise ValueError("Parameter 'post' is negative.")
self._parts |= Parts.Post
self._post = post
else:
self._post = 0
if build is not None:
if not isinstance(build, int):
raise TypeError("Parameter 'build' is not of type 'int'.")
elif build < 0:
raise ValueError("Parameter 'build' is negative.")
self._build = build
self._parts |= Parts.Build
else:
self._build = 0
if postfix is not None:
if not isinstance(postfix, str):
raise TypeError("Parameter 'postfix' is not of type 'str'.")
self._parts |= Parts.Postfix
self._postfix = postfix
else:
self._postfix = ""
if prefix is not None:
if not isinstance(prefix, str):
raise TypeError("Parameter 'prefix' is not of type 'str'.")
self._parts |= Parts.Prefix
self._prefix = prefix
else:
self._prefix = ""
if hash is not None:
if not isinstance(hash, str):
raise TypeError("Parameter 'hash' is not of type 'str'.")
self._parts |= Parts.Hash
self._hash = hash
else:
self._hash = ""
if flags is None:
raise ValueError("Parameter 'flags' is None.")
elif not isinstance(flags, Flags):
raise TypeError("Parameter 'flags' is not of type 'Flags'.")
self._flags = flags
@classmethod
@abstractmethod
def Parse(cls, versionString: Nullable[str], validator: Nullable[Callable[["SemanticVersion"], bool]] = None) -> "Version":
"""Parse a version string and return a Version instance."""
@readonly
def Parts(self) -> Parts:
"""
Read-only property to access the used parts of this version number.
:return: A flag enumeration of used version number parts.
"""
return self._parts
@readonly
def Prefix(self) -> str:
"""
Read-only property to access the version number's prefix.
:return: The prefix of the version number.
"""
return self._prefix
@readonly
def Major(self) -> int:
"""
Read-only property to access the major number.
:return: The major number.
"""
return self._major
@readonly
def Minor(self) -> int:
"""
Read-only property to access the minor number.
:return: The minor number.
"""
return self._minor
@readonly
def Micro(self) -> int:
"""
Read-only property to access the micro number.
:return: The micro number.
"""
return self._micro
@readonly
def ReleaseLevel(self) -> ReleaseLevel:
"""
Read-only property to access the release level.
:return: The release level.
"""
return self._releaseLevel
@readonly
def ReleaseNumber(self) -> int:
"""
Read-only property to access the release number.
:return: The release number.
"""
return self._releaseNumber
@readonly
def Post(self) -> int:
"""
Read-only property to access the post number.
:return: The post number.
"""
return self._post
@readonly
def Dev(self) -> int:
"""
Read-only property to access the development number.
:return: The development number.
"""
return self._dev
@readonly
def Build(self) -> int:
"""
Read-only property to access the build number.
:return: The build number.
"""
return self._build
@readonly
def Postfix(self) -> str:
"""
Read-only property to access the version number's postfix.
:return: The postfix of the version number.
"""
return self._postfix
@readonly
def Hash(self) -> str:
"""
Read-only property to access the version number's hash.
:return: The hash.
"""
return self._hash
@readonly
def Flags(self) -> Flags:
"""
Read-only property to access the version number's flags.
:return: The flags of the version number.
"""
return self._flags
def _equal(self, left: "Version", right: "Version") -> Nullable[bool]:
"""
Private helper method to compute the equality of two :class:`Version` instances.
:param left: Left operand.
:param right: Right operand.
:returns: ``True``, if ``left`` is equal to ``right``, otherwise it's ``False``.
"""
return (
(left._major == right._major) and
(left._minor == right._minor) and
(left._micro == right._micro) and
(left._releaseLevel == right._releaseLevel) and
(left._releaseNumber == right._releaseNumber) and
(left._post == right._post) and
(left._dev == right._dev) and
(left._build == right._build) and
(left._postfix == right._postfix)
)
def _compare(self, left: "Version", right: "Version") -> Nullable[bool]:
"""
Private helper method to compute the comparison of two :class:`Version` instances.
:param left: Left operand.
:param right: Right operand.
:returns: ``True``, if ``left`` is smaller than ``right``. |br|
False if ``left`` is greater than ``right``. |br|
Otherwise it's None (both operands are equal).
"""
if left._major < right._major:
return True
elif left._major > right._major:
return False
if left._minor < right._minor:
return True
elif left._minor > right._minor:
return False
if left._micro < right._micro:
return True
elif left._micro > right._micro:
return False
if left._releaseLevel < right._releaseLevel:
return True
elif left._releaseLevel > right._releaseLevel:
return False
if left._releaseNumber < right._releaseNumber:
return True
elif left._releaseNumber > right._releaseNumber:
return False
if left._post < right._post:
return True
elif left._post > right._post:
return False
if left._dev < right._dev:
return True
elif left._dev > right._dev:
return False
if left._build < right._build:
return True
elif left._build > right._build:
return False
return None
def _minimum(self, actual: "Version", expected: "Version") -> Nullable[bool]:
exactMajor = Parts.Minor in expected._parts
exactMinor = Parts.Micro in expected._parts
if exactMajor and actual._major != expected._major:
return False
elif not exactMajor and actual._major < expected._major:
return False
if exactMinor and actual._minor != expected._minor:
return False
elif not exactMinor and actual._minor < expected._minor:
return False
if Parts.Micro in expected._parts:
return actual._micro >= expected._micro
return True
def _format(self, formatSpec: str) -> str:
"""
Return a string representation of this version number according to the format specification.
.. topic:: Format Specifiers
* ``%p`` - prefix
* ``%M`` - major number
* ``%m`` - minor number
* ``%u`` - micro number
* ``%b`` - build number
:param formatSpec: The format specification.
:return: Formatted version number.
"""
if formatSpec == "":
return self.__str__()
result = formatSpec
result = result.replace("%p", str(self._prefix))
result = result.replace("%M", str(self._major))
result = result.replace("%m", str(self._minor))
result = result.replace("%u", str(self._micro))
result = result.replace("%b", str(self._build))
result = result.replace("%r", str(self._releaseLevel)[0])
result = result.replace("%R", str(self._releaseLevel))
result = result.replace("%n", str(self._releaseNumber))
result = result.replace("%d", str(self._dev))
result = result.replace("%P", str(self._postfix))
return result
@mustoverride
def __eq__(self, other: Union["Version", str, int, None]) -> bool:
"""
Compare two version numbers for equality.
The second operand should be an instance of :class:`Version`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if both version numbers are equal.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`Version`, :class:`str` or :class:`ìnt`.
"""
if other is None:
raise ValueError(f"Second operand is None.")
elif ((sC := self.__class__) is (oC := other.__class__) or issubclass(sC, oC) or issubclass(oC, sC)):
pass
elif isinstance(other, str):
other = self.__class__.Parse(other)
elif isinstance(other, int):
other = self.__class__(major=other)
else:
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by == operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__}, str, int")
raise ex
return self._equal(self, other)
@mustoverride
def __ne__(self, other: Union["Version", str, int, None]) -> bool:
"""
Compare two version numbers for inequality.
The second operand should be an instance of :class:`Version`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if both version numbers are not equal.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`Version`, :class:`str` or :class:`ìnt`.
"""
if other is None:
raise ValueError(f"Second operand is None.")
elif ((sC := self.__class__) is (oC := other.__class__) or issubclass(sC, oC) or issubclass(oC, sC)):
pass
elif isinstance(other, str):
other = self.__class__.Parse(other)
elif isinstance(other, int):
other = self.__class__(major=other)
else:
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by == operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__}, str, int")
raise ex
return not self._equal(self, other)
@mustoverride
def __lt__(self, other: Union["Version", str, int, None]) -> bool:
"""
Compare two version numbers if the version is less than the second operand.
The second operand should be an instance of :class:`Version`, but :class:`VersionRange`, :class:`VersionSet`,
``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if version is less than the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`Version`, :class:`VersionRange`, :class:`VersionSet`, :class:`str` or :class:`ìnt`.
"""
if other is None:
raise ValueError(f"Second operand is None.")
elif ((sC := self.__class__) is (oC := other.__class__) or issubclass(sC, oC) or issubclass(oC, sC)):
pass
elif isinstance(other, VersionRange):
other = other._lowerBound
elif isinstance(other, VersionSet):
other = other._items[0]
elif isinstance(other, str):
other = self.__class__.Parse(other)
elif isinstance(other, int):
other = self.__class__(major=other)
else:
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by < operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__}, VersionRange, VersionSet, str, int")
raise ex
return self._compare(self, other) is True
@mustoverride
def __le__(self, other: Union["Version", str, int, None]) -> bool:
"""
Compare two version numbers if the version is less than or equal the second operand.
The second operand should be an instance of :class:`Version`, :class:`VersionRange`, :class:`VersionSet`, but
``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if version is less than or equal the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`Version`, :class:`VersionRange`, :class:`VersionSet`, :class:`str` or :class:`ìnt`.
"""
equalValue = True
if other is None:
raise ValueError(f"Second operand is None.")
elif ((sC := self.__class__) is (oC := other.__class__) or issubclass(sC, oC) or issubclass(oC, sC)):
pass
elif isinstance(other, VersionRange):
equalValue = RangeBoundHandling.LowerBoundExclusive not in other._boundHandling
other = other._lowerBound
elif isinstance(other, VersionSet):
other = other._items[0]
elif isinstance(other, str):
other = self.__class__.Parse(other)
elif isinstance(other, int):
other = self.__class__(major=other)
else:
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by <= operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__}, VersionRange, VersionSet, str, int")
raise ex
result = self._compare(self, other)
return result if result is not None else equalValue
@mustoverride
def __gt__(self, other: Union["Version", str, int, None]) -> bool:
"""
Compare two version numbers if the version is greater than the second operand.
The second operand should be an instance of :class:`Version`, :class:`VersionRange`, :class:`VersionSet`, but
``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if version is greater than the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`Version`, :class:`VersionRange`, :class:`VersionSet`, :class:`str` or :class:`ìnt`.
"""
if other is None:
raise ValueError(f"Second operand is None.")
elif ((sC := self.__class__) is (oC := other.__class__) or issubclass(sC, oC) or issubclass(oC, sC)):
pass
elif isinstance(other, VersionRange):
other = other._upperBound
elif isinstance(other, VersionSet):
other = other._items[-1]
elif isinstance(other, str):
other = self.__class__.Parse(other)
elif isinstance(other, int):
other = self.__class__(major=other)
else:
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by > operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__}, VersionRange, VersionSet, str, int")
raise ex
return self._compare(self, other) is False
@mustoverride
def __ge__(self, other: Union["Version", str, int, None]) -> bool:
"""
Compare two version numbers if the version is greater than or equal the second operand.
The second operand should be an instance of :class:`Version`, :class:`VersionRange`, :class:`VersionSet`, but
``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if version is greater than or equal the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`Version`, :class:`VersionRange`, :class:`VersionSet`, :class:`str` or :class:`ìnt`.
"""
equalValue = True
if other is None:
raise ValueError(f"Second operand is None.")
elif ((sC := self.__class__) is (oC := other.__class__) or issubclass(sC, oC) or issubclass(oC, sC)):
pass
elif isinstance(other, VersionRange):
equalValue = RangeBoundHandling.UpperBoundExclusive not in other._boundHandling
other = other._upperBound
elif isinstance(other, VersionSet):
other = other._items[-1]
elif isinstance(other, str):
other = self.__class__.Parse(other)
elif isinstance(other, int):
other = self.__class__(major=other)
else:
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by >= operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__}, VersionRange, VersionSet, str, int")
raise ex
result = self._compare(self, other)
return not result if result is not None else equalValue
def __rshift__(self, other: Union["Version", str, int, None]) -> bool:
if other is None:
raise ValueError(f"Second operand is None.")
elif isinstance(other, self.__class__):
pass
elif isinstance(other, str):
other = self.__class__.Parse(other)
elif isinstance(other, int):
other = self.__class__(major=other)
else:
ex = TypeError(f"Second operand of type '{other.__class__.__name__}' is not supported by >> operator.")
ex.add_note(f"Supported types for second operand: {self.__class__.__name__}, str, int")
raise ex
return self._minimum(self, other)
def __hash__(self) -> int:
if self.__hash is None:
self.__hash = hash((
self._prefix,
self._major,
self._minor,
self._micro,
self._releaseLevel,
self._releaseNumber,
self._post,
self._dev,
self._build,
self._postfix,
self._hash,
self._flags
))
return self.__hash
@export
class SemanticVersion(Version):
"""Representation of a semantic version number like ``3.7.12``."""
_PATTERN = re_compile(
r"^"
r"(?P<prefix>[a-zA-Z]*)"
r"(?P<major>\d+)"
r"(?:\.(?P<minor>\d+))?"
r"(?:\.(?P<micro>\d+))?"
r"(?:"
r"(?:\.(?P<build>\d+))"
r"|"
r"(?:[-](?P<release>dev|final))"
r"|"
r"(?:(?P<delim1>[\.\-]?)(?P<level>alpha|beta|gamma|a|b|c|rc|pl)(?P<number>\d+))"
r")?"
r"(?:(?P<delim2>[\.\-]post)(?P<post>\d+))?"
r"(?:(?P<delim3>[\.\-]dev)(?P<dev>\d+))?"
r"(?:(?P<delim4>[\.\-\+])(?P<postfix>\w+))?"
r"$"
)
# QUESTION: was this how many commits a version is ahead of the last tagged version?
# ahead: int = 0
def __init__(
self,
major: int,
minor: Nullable[int] = None,
micro: Nullable[int] = None,
level: Nullable[ReleaseLevel] = ReleaseLevel.Final,
number: Nullable[int] = None,
post: Nullable[int] = None,
dev: Nullable[int] = None,
*,
build: Nullable[int] = None,
postfix: Nullable[str] = None,
prefix: Nullable[str] = None,
hash: Nullable[str] = None,
flags: Flags = Flags.NoVCS
) -> None:
"""
Initializes a semantic version number representation.
:param major: Major number part of the version number.
:param minor: Minor number part of the version number.
:param micro: Micro (patch) number part of the version number.
:param build: Build number part of the version number.
:param level: tbd
:param number: tbd
:param post: Post number part of the version number.
:param dev: Development number part of the version number.
:param prefix: The version number's prefix.
:param postfix: The version number's postfix.
:param flags: The version number's flags.
:param hash: tbd
:raises TypeError: If parameter 'major' is not of type int.
:raises ValueError: If parameter 'major' is a negative number.
:raises TypeError: If parameter 'minor' is not of type int.
:raises ValueError: If parameter 'minor' is a negative number.
:raises TypeError: If parameter 'micro' is not of type int.
:raises ValueError: If parameter 'micro' is a negative number.
:raises TypeError: If parameter 'build' is not of type int.
:raises ValueError: If parameter 'build' is a negative number.
:raises TypeError: If parameter 'post' is not of type int.
:raises ValueError: If parameter 'post' is a negative number.
:raises TypeError: If parameter 'dev' is not of type int.
:raises ValueError: If parameter 'dev' is a negative number.
:raises TypeError: If parameter 'prefix' is not of type str.
:raises TypeError: If parameter 'postfix' is not of type str.
"""
super().__init__(major, minor, micro, level, number, post, dev, build=build, postfix=postfix, prefix=prefix, hash=hash, flags=flags)
@classmethod
def Parse(cls, versionString: Nullable[str], validator: Nullable[Callable[["SemanticVersion"], bool]] = None) -> "SemanticVersion":
"""
Parse a version string and return a :class:`SemanticVersion` instance.
Allowed prefix characters:
* ``v|V`` - version, public version, public release
* ``i|I`` - internal version, internal release
* ``r|R`` - release, revision
* ``rev|REV`` - revision
:param versionString: The version string to parse.
:param validator: Optional, a validation function.
:returns: An object representing a semantic version.
:raises TypeError: When parameter ``versionString`` is not a string.
:raises ValueError: When parameter ``versionString`` is None.
:raises ValueError: When parameter ``versionString`` is empty.
"""
if versionString is None:
raise ValueError("Parameter 'versionString' is None.")
elif not isinstance(versionString, str):
ex = TypeError(f"Parameter 'versionString' is not of type 'str'.")
ex.add_note(f"Got type '{getFullyQualifiedName(versionString)}'.")
raise ex
elif (versionString := versionString.strip()) == "":
raise ValueError("Parameter 'versionString' is empty.")
if (match := cls._PATTERN.match(versionString)) is None:
raise ValueError(f"Syntax error in parameter 'versionString': '{versionString}'")
def toInt(value: Nullable[str]) -> Nullable[int]:
if value is None or value == "":
return None
try:
return int(value)
except ValueError as ex: # pragma: no cover
raise ValueError(f"Invalid part '{value}' in version number '{versionString}'.") from ex
release = match["release"]
if release is not None:
if release == "dev":
releaseLevel = ReleaseLevel.Development
elif release == "final":
releaseLevel = ReleaseLevel.Final
else: # pragma: no cover
raise ValueError(f"Unknown release level '{release}' in version number '{versionString}'.")
else:
level = match["level"]
if level is not None:
level = level.lower()
if level == "a" or level == "alpha":
releaseLevel = ReleaseLevel.Alpha
elif level == "b" or level == "beta":
releaseLevel = ReleaseLevel.Beta
elif level == "c" or level == "gamma":
releaseLevel = ReleaseLevel.Gamma
elif level == "rc":
releaseLevel = ReleaseLevel.ReleaseCandidate
else: # pragma: no cover
raise ValueError(f"Unknown release level '{level}' in version number '{versionString}'.")
else:
releaseLevel = ReleaseLevel.Final
version = cls(
major=toInt(match["major"]),
minor=toInt(match["minor"]),
micro=toInt(match["micro"]),
level=releaseLevel,
number=toInt(match["number"]),
post=toInt(match["post"]),
dev=toInt(match["dev"]),
build=toInt(match["build"]),
postfix=match["postfix"],
prefix=match["prefix"],
# hash=match["hash"],
flags=Flags.Clean
)
if validator is not None and not validator(version):
# TODO: VersionValidatorException
raise ValueError(f"Failed to validate version string '{versionString}'.")
return version
@readonly
def Patch(self) -> int:
"""
Read-only property to access the patch number.
The patch number is identical to the micro number.
:return: The patch number.
"""
return self._micro
def _equal(self, left: "SemanticVersion", right: "SemanticVersion") -> Nullable[bool]:
"""
Private helper method to compute the equality of two :class:`SemanticVersion` instances.
:param left: Left operand.
:param right: Right operand.
:returns: ``True``, if ``left`` is equal to ``right``, otherwise it's ``False``.
"""
return super()._equal(left, right)
def _compare(self, left: "SemanticVersion", right: "SemanticVersion") -> Nullable[bool]:
"""
Private helper method to compute the comparison of two :class:`SemanticVersion` instances.
:param left: Left operand.
:param right: Right operand.
:returns: ``True``, if ``left`` is smaller than ``right``. |br|
False if ``left`` is greater than ``right``. |br|
Otherwise it's None (both operands are equal).
"""
return super()._compare(left, right)
def __eq__(self, other: Union["SemanticVersion", str, int, None]) -> bool:
"""
Compare two version numbers for equality.
The second operand should be an instance of :class:`SemanticVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a semantic version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if both version numbers are equal.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`SemanticVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__eq__(other)
def __ne__(self, other: Union["SemanticVersion", str, int, None]) -> bool:
"""
Compare two version numbers for inequality.
The second operand should be an instance of :class:`SemanticVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a semantic version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if both version numbers are not equal.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`SemanticVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__ne__(other)
def __lt__(self, other: Union["SemanticVersion", str, int, None]) -> bool:
"""
Compare two version numbers if the version is less than the second operand.
The second operand should be an instance of :class:`SemanticVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a semantic version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if version is less than the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`SemanticVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__lt__(other)
def __le__(self, other: Union["SemanticVersion", str, int, None]) -> bool:
"""
Compare two version numbers if the version is less than or equal the second operand.
The second operand should be an instance of :class:`SemanticVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a semantic version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if version is less than or equal the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`SemanticVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__le__(other)
def __gt__(self, other: Union["SemanticVersion", str, int, None]) -> bool:
"""
Compare two version numbers if the version is greater than the second operand.
The second operand should be an instance of :class:`SemanticVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a semantic version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if version is greater than the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`SemanticVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__gt__(other)
def __ge__(self, other: Union["SemanticVersion", str, int, None]) -> bool:
"""
Compare two version numbers if the version is greater than or equal the second operand.
The second operand should be an instance of :class:`SemanticVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a semantic version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Operand to compare against.
:returns: ``True``, if version is greater than or equal the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`SemanticVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__ge__(other)
def __rshift__(self, other: Union["SemanticVersion", str, int, None]) -> bool:
return super().__rshift__(other)
def __hash__(self) -> int:
return super().__hash__()
def __format__(self, formatSpec: str) -> str:
result = self._format(formatSpec)
if (pos := result.find("%")) != -1 and result[pos + 1] != "%": # pragma: no cover
raise ValueError(f"Unknown format specifier '%{result[pos + 1]}' in '{formatSpec}'.")
return result.replace("%%", "%")
def __repr__(self) -> str:
"""
Return a string representation of this version number without prefix ``v``.
:returns: Raw version number representation without a prefix.
"""
return f"{self._prefix if Parts.Prefix in self._parts else ''}{self._major}.{self._minor}.{self._micro}"
def __str__(self) -> str:
"""
Return a string representation of this version number.
:returns: Version number representation.
"""
result = self._prefix if Parts.Prefix in self._parts else ""
result += f"{self._major}" # major is always present
result += f".{self._minor}" if Parts.Minor in self._parts else ""
result += f".{self._micro}" if Parts.Micro in self._parts else ""
result += f".{self._build}" if Parts.Build in self._parts else ""
if self._releaseLevel is ReleaseLevel.Development:
result += "-dev"
elif self._releaseLevel is ReleaseLevel.Alpha:
result += f".alpha{self._releaseNumber}"
elif self._releaseLevel is ReleaseLevel.Beta:
result += f".beta{self._releaseNumber}"
elif self._releaseLevel is ReleaseLevel.Gamma:
result += f".gamma{self._releaseNumber}"
elif self._releaseLevel is ReleaseLevel.ReleaseCandidate:
result += f".rc{self._releaseNumber}"
result += f".post{self._post}" if Parts.Post in self._parts else ""
result += f".dev{self._dev}" if Parts.Dev in self._parts else ""
result += f"+{self._postfix}" if Parts.Postfix in self._parts else ""
return result
@export
class PythonVersion(SemanticVersion):
"""
Represents a Python version.
"""
@classmethod
def FromSysVersionInfo(cls) -> "PythonVersion":
"""
Create a Python version from :data:`sys.version_info`.
:returns: A PythonVersion instance of the current Python interpreter's version.
"""
from sys import version_info
if version_info.releaselevel == "final":
rl = ReleaseLevel.Final
number = None
else: # pragma: no cover
number = version_info.serial
if version_info.releaselevel == "alpha":
rl = ReleaseLevel.Alpha
elif version_info.releaselevel == "beta":
rl = ReleaseLevel.Beta
elif version_info.releaselevel == "candidate":
rl = ReleaseLevel.ReleaseCandidate
else: # pragma: no cover
raise ToolingException(f"Unsupported release level '{version_info.releaselevel}'.")
return cls(version_info.major, version_info.minor, version_info.micro, level=rl, number=number)
def __hash__(self) -> int:
return super().__hash__()
def __str__(self) -> str:
"""
Return a string representation of this version number.
:returns: Version number representation.
"""
result = self._prefix if Parts.Prefix in self._parts else ""
result += f"{self._major}" # major is always present
result += f".{self._minor}" if Parts.Minor in self._parts else ""
result += f".{self._micro}" if Parts.Micro in self._parts else ""
if self._releaseLevel is ReleaseLevel.Alpha:
result += f"a{self._releaseNumber}"
elif self._releaseLevel is ReleaseLevel.Beta:
result += f"b{self._releaseNumber}"
elif self._releaseLevel is ReleaseLevel.Gamma:
result += f"c{self._releaseNumber}"
elif self._releaseLevel is ReleaseLevel.ReleaseCandidate:
result += f"rc{self._releaseNumber}"
result += f".post{self._post}" if Parts.Post in self._parts else ""
result += f".dev{self._dev}" if Parts.Dev in self._parts else ""
result += f"+{self._postfix}" if Parts.Postfix in self._parts else ""
return result
@export
class CalendarVersion(Version):
"""Representation of a calendar version number like ``2021.10``."""
def __init__(
self,
major: int,
minor: Nullable[int] = None,
micro: Nullable[int] = None,
build: Nullable[int] = None,
flags: Flags = Flags.Clean,
prefix: Nullable[str] = None,
postfix: Nullable[str] = None
) -> None:
"""
Initializes a calendar version number representation.
:param major: Major number part of the version number.
:param minor: Minor number part of the version number.
:param micro: Micro (patch) number part of the version number.
:param build: Build number part of the version number.
:param flags: The version number's flags.
:param prefix: The version number's prefix.
:param postfix: The version number's postfix.
:raises TypeError: If parameter 'major' is not of type int.
:raises ValueError: If parameter 'major' is a negative number.
:raises TypeError: If parameter 'minor' is not of type int.
:raises ValueError: If parameter 'minor' is a negative number.
:raises TypeError: If parameter 'micro' is not of type int.
:raises ValueError: If parameter 'micro' is a negative number.
:raises TypeError: If parameter 'build' is not of type int.
:raises ValueError: If parameter 'build' is a negative number.
:raises TypeError: If parameter 'prefix' is not of type str.
:raises TypeError: If parameter 'postfix' is not of type str.
"""
super().__init__(major, minor, micro, build=build, postfix=postfix, prefix=prefix, flags=flags)
@classmethod
def Parse(cls, versionString: Nullable[str], validator: Nullable[Callable[["CalendarVersion"], bool]] = None) -> "CalendarVersion":
"""
Parse a version string and return a :class:`CalendarVersion` instance.
:param versionString: The version string to parse.
:returns: An object representing a calendar version.
:raises TypeError: If parameter ``other`` is not a string.
:raises ValueError: If parameter ``other`` is None.
:raises ValueError: If parameter ``other`` is empty.
"""
parts = Parts.Unknown
if versionString is None:
raise ValueError("Parameter 'versionString' is None.")
elif not isinstance(versionString, str):
ex = TypeError(f"Parameter 'versionString' is not of type 'str'.")
ex.add_note(f"Got type '{getFullyQualifiedName(versionString)}'.")
raise ex
elif versionString == "":
raise ValueError("Parameter 'versionString' is empty.")
split = versionString.split(".")
length = len(split)
major = int(split[0])
minor = 0
parts |= Parts.Major
if length >= 2:
minor = int(split[1])
parts |= Parts.Minor
flags = Flags.Clean
version = cls(major, minor, flags=flags)
if validator is not None and not validator(version):
raise ValueError(f"Failed to validate version string '{versionString}'.") # pragma: no cover
return version
@property
def Year(self) -> int:
"""
Read-only property to access the year part.
:return: The year part.
"""
return self._major
def _equal(self, left: "CalendarVersion", right: "CalendarVersion") -> Nullable[bool]:
"""
Private helper method to compute the equality of two :class:`CalendarVersion` instances.
:param left: Left parameter.
:param right: Right parameter.
:returns: ``True``, if ``left`` is equal to ``right``, otherwise it's ``False``.
"""
return (left._major == right._major) and (left._minor == right._minor) and (left._micro == right._micro)
def _compare(self, left: "CalendarVersion", right: "CalendarVersion") -> Nullable[bool]:
"""
Private helper method to compute the comparison of two :class:`CalendarVersion` instances.
:param left: Left parameter.
:param right: Right parameter.
:returns: ``True``, if ``left`` is smaller than ``right``. |br|
False if ``left`` is greater than ``right``. |br|
Otherwise it's None (both parameters are equal).
"""
if left._major < right._major:
return True
elif left._major > right._major:
return False
if left._minor < right._minor:
return True
elif left._minor > right._minor:
return False
if left._micro < right._micro:
return True
elif left._micro > right._micro:
return False
return None
def __eq__(self, other: Union["CalendarVersion", str, int, None]) -> bool:
"""
Compare two version numbers for equality.
The second operand should be an instance of :class:`CalendarVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a calendar version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Parameter to compare against.
:returns: ``True``, if both version numbers are equal.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`CalendarVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__eq__(other)
def __ne__(self, other: Union["CalendarVersion", str, int, None]) -> bool:
"""
Compare two version numbers for inequality.
The second operand should be an instance of :class:`CalendarVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a calendar version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Parameter to compare against.
:returns: ``True``, if both version numbers are not equal.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`CalendarVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__ne__(other)
def __lt__(self, other: Union["CalendarVersion", str, int, None]) -> bool:
"""
Compare two version numbers if the version is less than the second operand.
The second operand should be an instance of :class:`CalendarVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a semantic version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Parameter to compare against.
:returns: ``True``, if version is less than the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`CalendarVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__lt__(other)
def __le__(self, other: Union["CalendarVersion", str, int, None]) -> bool:
"""
Compare two version numbers if the version is less than or equal the second operand.
The second operand should be an instance of :class:`CalendarVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a semantic version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Parameter to compare against.
:returns: ``True``, if version is less than or equal the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`CalendarVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__le__(other)
def __gt__(self, other: Union["CalendarVersion", str, int, None]) -> bool:
"""
Compare two version numbers if the version is greater than the second operand.
The second operand should be an instance of :class:`CalendarVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a semantic version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Parameter to compare against.
:returns: ``True``, if version is greater than the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`CalendarVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__gt__(other)
def __ge__(self, other: Union["CalendarVersion", str, int, None]) -> bool:
"""
Compare two version numbers if the version is greater than or equal the second operand.
The second operand should be an instance of :class:`CalendarVersion`, but ``str`` and ``int`` are accepted, too. |br|
In case of ``str``, it's tried to parse the string as a semantic version number. In case of ``int``, a single major
number is assumed (all other parts are zero).
``float`` is not supported, due to rounding issues when converting the fractional part of the float to a minor
number.
:param other: Parameter to compare against.
:returns: ``True``, if version is greater than or equal the second operand.
:raises ValueError: If parameter ``other`` is None.
:raises TypeError: If parameter ``other`` is not of type :class:`CalendarVersion`, :class:`str` or :class:`ìnt`.
"""
return super().__ge__(other)
def __hash__(self) -> int:
return super().__hash__()
def __format__(self, formatSpec: str) -> str:
"""
Return a string representation of this version number according to the format specification.
.. topic:: Format Specifiers
* ``%M`` - major number (year)
* ``%m`` - minor number (month/week)
:param formatSpec: The format specification.
:return: Formatted version number.
"""
if formatSpec == "":
return self.__str__()
result = formatSpec
# result = result.replace("%P", str(self._prefix))
result = result.replace("%M", str(self._major))
result = result.replace("%m", str(self._minor))
# result = result.replace("%p", str(self._pre))
return result.replace("%%", "%")
def __repr__(self) -> str:
"""
Return a string representation of this version number without prefix ``v``.
:returns: Raw version number representation without a prefix.
"""
return f"{self._major}.{self._minor}"
def __str__(self) -> str:
"""
Return a string representation of this version number with prefix ``v``.
:returns: Version number representation including a prefix.
"""
result = f"{self._major}"
result += f".{self._minor}" if Parts.Minor in self._parts else ""
return result
@export
class YearMonthVersion(CalendarVersion):
"""Representation of a calendar version number made of year and month like ``2021.10``."""
def __init__(
self,
year: int,
month: Nullable[int] = None,
build: Nullable[int] = None,
flags: Flags = Flags.Clean,
prefix: Nullable[str] = None,
postfix: Nullable[str] = None
) -> None:
"""
Initializes a year-month version number representation.
:param year: Year part of the version number.
:param month: Month part of the version number.
:param build: Build number part of the version number.
:param flags: The version number's flags.
:param prefix: The version number's prefix.
:param postfix: The version number's postfix.
:raises TypeError: If parameter 'major' is not of type int.
:raises ValueError: If parameter 'major' is a negative number.
:raises TypeError: If parameter 'minor' is not of type int.
:raises ValueError: If parameter 'minor' is a negative number.
:raises TypeError: If parameter 'micro' is not of type int.
:raises ValueError: If parameter 'micro' is a negative number.
:raises TypeError: If parameter 'build' is not of type int.
:raises ValueError: If parameter 'build' is a negative number.
:raises TypeError: If parameter 'prefix' is not of type str.
:raises TypeError: If parameter 'postfix' is not of type str.
"""
super().__init__(year, month, 0, build, flags, prefix, postfix)
@property
def Month(self) -> int:
"""
Read-only property to access the month part.
:return: The month part.
"""
return self._minor
def __hash__(self) -> int:
return super().__hash__()
@export
class YearWeekVersion(CalendarVersion):
"""Representation of a calendar version number made of year and week like ``2021.47``."""
def __init__(
self,
year: int,
week: Nullable[int] = None,
build: Nullable[int] = None,
flags: Flags = Flags.Clean,
prefix: Nullable[str] = None,
postfix: Nullable[str] = None
) -> None:
"""
Initializes a year-week version number representation.
:param year: Year part of the version number.
:param week: Week part of the version number.
:param build: Build number part of the version number.
:param flags: The version number's flags.
:param prefix: The version number's prefix.
:param postfix: The version number's postfix.
:raises TypeError: If parameter 'major' is not of type int.
:raises ValueError: If parameter 'major' is a negative number.
:raises TypeError: If parameter 'minor' is not of type int.
:raises ValueError: If parameter 'minor' is a negative number.
:raises TypeError: If parameter 'micro' is not of type int.
:raises ValueError: If parameter 'micro' is a negative number.
:raises TypeError: If parameter 'build' is not of type int.
:raises ValueError: If parameter 'build' is a negative number.
:raises TypeError: If parameter 'prefix' is not of type str.
:raises TypeError: If parameter 'postfix' is not of type str.
"""
super().__init__(year, week, 0, build, flags, prefix, postfix)
@property
def Week(self) -> int:
"""
Read-only property to access the week part.
:return: The week part.
"""
return self._minor
def __hash__(self) -> int:
return super().__hash__()
@export
class YearReleaseVersion(CalendarVersion):
"""Representation of a calendar version number made of year and release per year like ``2021.2``."""
def __init__(
self,
year: int,
release: Nullable[int] = None,
build: Nullable[int] = None,
flags: Flags = Flags.Clean,
prefix: Nullable[str] = None,
postfix: Nullable[str] = None
) -> None:
"""
Initializes a year-release version number representation.
:param year: Year part of the version number.
:param release: Release number of the version number.
:param build: Build number part of the version number.
:param flags: The version number's flags.
:param prefix: The version number's prefix.
:param postfix: The version number's postfix.
:raises TypeError: If parameter 'major' is not of type int.
:raises ValueError: If parameter 'major' is a negative number.
:raises TypeError: If parameter 'minor' is not of type int.
:raises ValueError: If parameter 'minor' is a negative number.
:raises TypeError: If parameter 'micro' is not of type int.
:raises ValueError: If parameter 'micro' is a negative number.
:raises TypeError: If parameter 'build' is not of type int.
:raises ValueError: If parameter 'build' is a negative number.
:raises TypeError: If parameter 'prefix' is not of type str.
:raises TypeError: If parameter 'postfix' is not of type str.
"""
super().__init__(year, release, 0, build, flags, prefix, postfix)
@property
def Release(self) -> int:
"""
Read-only property to access the release number.
:return: The release number.
"""
return self._minor
def __hash__(self) -> int:
return super().__hash__()
@export
class YearMonthDayVersion(CalendarVersion):
"""Representation of a calendar version number made of year, month and day like ``2021.10.15``."""
def __init__(
self,
year: int,
month: Nullable[int] = None,
day: Nullable[int] = None,
build: Nullable[int] = None,
flags: Flags = Flags.Clean,
prefix: Nullable[str] = None,
postfix: Nullable[str] = None
) -> None:
"""
Initializes a year-month-day version number representation.
:param year: Year part of the version number.
:param month: Month part of the version number.
:param day: Day part of the version number.
:param build: Build number part of the version number.
:param flags: The version number's flags.
:param prefix: The version number's prefix.
:param postfix: The version number's postfix.
:raises TypeError: If parameter 'major' is not of type int.
:raises ValueError: If parameter 'major' is a negative number.
:raises TypeError: If parameter 'minor' is not of type int.
:raises ValueError: If parameter 'minor' is a negative number.
:raises TypeError: If parameter 'micro' is not of type int.
:raises ValueError: If parameter 'micro' is a negative number.
:raises TypeError: If parameter 'build' is not of type int.
:raises ValueError: If parameter 'build' is a negative number.
:raises TypeError: If parameter 'prefix' is not of type str.
:raises TypeError: If parameter 'postfix' is not of type str.
"""
super().__init__(year, month, day, build, flags, prefix, postfix)
@property
def Month(self) -> int:
"""
Read-only property to access the month part.
:return: The month part.
"""
return self._minor
@property
def Day(self) -> int:
"""
Read-only property to access the day part.
:return: The day part.
"""
return self._micro
def __hash__(self) -> int:
return super().__hash__()
V = TypeVar("V", bound=Version)
@export
class RangeBoundHandling(Flag):
"""
A flag defining how to handle bounds in a range.
If a bound is inclusive, the bound's value is within the range. If a bound is exclusive, the bound's value is the
first value outside the range. Inclusive and exclusive behavior can be mixed for lower and upper bounds.
"""
BothBoundsInclusive = 0 #: Lower and upper bound are inclusive.
LowerBoundInclusive = 0 #: Lower bound is inclusive.
UpperBoundInclusive = 0 #: Upper bound is inclusive.
LowerBoundExclusive = 1 #: Lower bound is exclusive.
UpperBoundExclusive = 2 #: Upper bound is exclusive.
BothBoundsExclusive = 3 #: Lower and upper bound are exclusive.
@export
class VersionRange(Generic[V], metaclass=ExtendedType, slots=True):
"""
Representation of a version range described by a lower bound and upper bound version.
This version range works with :class:`SemanticVersion` and :class:`CalendarVersion` and its derived classes.
"""
_lowerBound: V
_upperBound: V
_boundHandling: RangeBoundHandling
def __init__(self, lowerBound: V, upperBound: V, boundHandling: RangeBoundHandling = RangeBoundHandling.BothBoundsInclusive) -> None:
"""
Initializes a version range described by a lower and upper bound.
:param lowerBound: lowest version (inclusive).
:param upperBound: hightest version (inclusive).
:raises TypeError: If parameter ``lowerBound`` is not of type :class:`Version`.
:raises TypeError: If parameter ``upperBound`` is not of type :class:`Version`.
:raises TypeError: If parameter ``lowerBound`` and ``upperBound`` are unrelated types.
:raises ValueError: If parameter ``lowerBound`` isn't less than or equal to ``upperBound``.
"""
if not isinstance(lowerBound, Version):
ex = TypeError(f"Parameter 'lowerBound' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(lowerBound)}'.")
raise ex
if not isinstance(upperBound, Version):
ex = TypeError(f"Parameter 'upperBound' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(upperBound)}'.")
raise ex
if not ((lBC := lowerBound.__class__) is (uBC := upperBound.__class__) or issubclass(lBC, uBC) or issubclass(uBC, lBC)):
ex = TypeError(f"Parameters 'lowerBound' and 'upperBound' are not compatible with each other.")
ex.add_note(f"Got type '{getFullyQualifiedName(lowerBound)}' for lowerBound and type '{getFullyQualifiedName(upperBound)}' for upperBound.")
raise ex
if not (lowerBound <= upperBound):
ex = ValueError(f"Parameter 'lowerBound' isn't less than parameter 'upperBound'.")
ex.add_note(f"Got '{lowerBound}' for lowerBound and '{upperBound}' for upperBound.")
raise ex
self._lowerBound = lowerBound
self._upperBound = upperBound
self._boundHandling = boundHandling
@property
def LowerBound(self) -> V:
"""
Property to access the range's lower bound.
:return: Lower bound of the version range.
"""
return self._lowerBound
@LowerBound.setter
def LowerBound(self, value: V) -> None:
if not isinstance(value, Version):
ex = TypeError(f"Parameter 'value' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
raise ex
self._lowerBound = value
@readonly
def UpperBound(self) -> V:
"""
Property to access the range's upper bound.
:return: Upper bound of the version range.
"""
return self._upperBound
@UpperBound.setter
def UpperBound(self, value: V) -> None:
if not isinstance(value, Version):
ex = TypeError(f"Parameter 'value' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
raise ex
self._upperBound = value
@readonly
def BoundHandling(self) -> RangeBoundHandling:
"""
Property to access the range's bound handling strategy.
:return: The range's bound handling strategy.
"""
return self._boundHandling
@BoundHandling.setter
def BoundHandling(self, value: RangeBoundHandling) -> None:
if not isinstance(value, RangeBoundHandling):
ex = TypeError(f"Parameter 'value' is not of type 'RangeBoundHandling'.")
ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
raise ex
self._boundHandling = value
def __and__(self, other: Any) -> "VersionRange[T]":
"""
Compute the intersection of two version ranges.
:param other: Second version range to intersect with.
:returns: Intersected version range.
:raises TypeError: If parameter 'other' is not of type :class:`VersionRange`.
:raises ValueError: If intersection is empty.
"""
if not isinstance(other, VersionRange):
ex = TypeError(f"Parameter 'other' is not of type 'VersionRange'.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
if not (isinstance(other._lowerBound, self._lowerBound.__class__) and isinstance(self._lowerBound, other._lowerBound.__class__)):
ex = TypeError(f"Parameter 'other's LowerBound and this range's 'LowerBound' are not compatible with each other.")
ex.add_note(
f"Got type '{getFullyQualifiedName(other._lowerBound)}' for other.LowerBound and type '{getFullyQualifiedName(self._lowerBound)}' for self.LowerBound.")
raise ex
if other._lowerBound < self._lowerBound:
lBound = self._lowerBound
elif other._lowerBound in self:
lBound = other._lowerBound
else:
raise ValueError()
if other._upperBound > self._upperBound:
uBound = self._upperBound
elif other._upperBound in self:
uBound = other._upperBound
else:
raise ValueError()
return self.__class__(lBound, uBound)
def __lt__(self, other: Any) -> bool:
"""
Compare a version range and a version numbers if the version range is less than the second operand (version).
:param other: Operand to compare against.
:returns: ``True``, if version range is less than the second operand (version).
:raises TypeError: If parameter ``other`` is not of type :class:`Version`.
"""
# TODO: support VersionRange < VersionRange too
# TODO: support str, int, ... like Version ?
if not isinstance(other, Version):
ex = TypeError(f"Parameter 'other' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
if not (isinstance(other, self._lowerBound.__class__) and isinstance(self._lowerBound, other.__class__)):
ex = TypeError(f"Parameter 'other' is not compatible with version range.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
return self._upperBound < other
def __le__(self, other: Any) -> bool:
"""
Compare a version range and a version numbers if the version range is less than or equal the second operand (version).
:param other: Operand to compare against.
:returns: ``True``, if version range is less than or equal the second operand (version).
:raises TypeError: If parameter ``other`` is not of type :class:`Version`.
"""
# TODO: support VersionRange < VersionRange too
# TODO: support str, int, ... like Version ?
if not isinstance(other, Version):
ex = TypeError(f"Parameter 'other' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
if not (isinstance(other, self._lowerBound.__class__) and isinstance(self._lowerBound, other.__class__)):
ex = TypeError(f"Parameter 'other' is not compatible with version range.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
if RangeBoundHandling.UpperBoundExclusive in self._boundHandling:
return self._upperBound < other
else:
return self._upperBound <= other
def __gt__(self, other: Any) -> bool:
"""
Compare a version range and a version numbers if the version range is greater than the second operand (version).
:param other: Operand to compare against.
:returns: ``True``, if version range is greater than the second operand (version).
:raises TypeError: If parameter ``other`` is not of type :class:`Version`.
"""
# TODO: support VersionRange < VersionRange too
# TODO: support str, int, ... like Version ?
if not isinstance(other, Version):
ex = TypeError(f"Parameter 'other' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
if not (isinstance(other, self._upperBound.__class__) and isinstance(self._upperBound, other.__class__)):
ex = TypeError(f"Parameter 'other' is not compatible with version range.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
return self._lowerBound > other
def __ge__(self, other: Any) -> bool:
"""
Compare a version range and a version numbers if the version range is greater than or equal the second operand (version).
:param other: Operand to compare against.
:returns: ``True``, if version range is greater than or equal the second operand (version).
:raises TypeError: If parameter ``other`` is not of type :class:`Version`.
"""
# TODO: support VersionRange < VersionRange too
# TODO: support str, int, ... like Version ?
if not isinstance(other, Version):
ex = TypeError(f"Parameter 'other' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
if not (isinstance(other, self._upperBound.__class__) and isinstance(self._upperBound, other.__class__)):
ex = TypeError(f"Parameter 'other' is not compatible with version range.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
if RangeBoundHandling.LowerBoundExclusive in self._boundHandling:
return self._lowerBound > other
else:
return self._lowerBound >= other
def __contains__(self, version: Version) -> bool:
"""
Check if the version is in the version range.
:param version: Version to check.
:returns: ``True``, if version is in range.
:raises TypeError: If parameter ``version`` is not of type :class:`Version`.
"""
if not isinstance(version, Version):
ex = TypeError(f"Parameter 'item' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(version)}'.")
raise ex
if self._boundHandling is RangeBoundHandling.BothBoundsInclusive:
return self._lowerBound <= version <= self._upperBound
elif self._boundHandling is (RangeBoundHandling.LowerBoundInclusive | RangeBoundHandling.UpperBoundExclusive):
return self._lowerBound <= version < self._upperBound
elif self._boundHandling is (RangeBoundHandling.LowerBoundExclusive | RangeBoundHandling.UpperBoundInclusive):
return self._lowerBound < version <= self._upperBound
else:
return self._lowerBound < version < self._upperBound
@export
class VersionSet(Generic[V], metaclass=ExtendedType, slots=True):
"""
Representation of an ordered set of versions.
This version set works with :class:`SemanticVersion` and :class:`CalendarVersion` and its derived classes.
"""
_items: List[V] #: An ordered list of set members.
def __init__(self, versions: Union[Version, Iterable[V]]) -> None:
"""
Initializes a version set either by a single version or an iterable of versions.
:param versions: A single version or an iterable of versions.
:raises ValueError: If parameter ``versions`` is None`.
:raises TypeError: In case of a single version, if parameter ``version`` is not of type :class:`Version`.
:raises TypeError: In case of an iterable, if parameter ``versions`` containes elements, which are not of type :class:`Version`.
:raises TypeError: If parameter ``versions`` is neither a single version nor an iterable thereof.
"""
if versions is None:
raise ValueError(f"Parameter 'versions' is None.")
if isinstance(versions, Version):
self._items = [versions]
elif isinstance(versions, abc_Iterable):
iterator = iter(versions)
try:
firstVersion = next(iterator)
except StopIteration:
self._items = []
return
if not isinstance(firstVersion, Version):
raise TypeError(f"First element in parameter 'versions' is not of type Version.")
baseType = firstVersion.__class__
for version in iterator:
if not isinstance(version, baseType):
raise TypeError(f"Element from parameter 'versions' is not of type {baseType.__name__}")
self._items = list(sorted(versions))
else:
raise TypeError(f"Parameter 'versions' is not an Iterable.")
def __and__(self, other: "VersionSet[V]") -> "VersionSet[T]":
"""
Compute intersection of two version sets.
:param other: Second set of versions.
:returns: Intersection of two version sets.
"""
selfIterator = self.__iter__()
otherIterator = other.__iter__()
result = []
try:
selfValue = next(selfIterator)
otherValue = next(otherIterator)
while True:
if selfValue < otherValue:
selfValue = next(selfIterator)
elif otherValue < selfValue:
otherValue = next(otherIterator)
else:
result.append(selfValue)
selfValue = next(selfIterator)
otherValue = next(otherIterator)
except StopIteration:
pass
return VersionSet(result)
def __or__(self, other: "VersionSet[V]") -> "VersionSet[T]":
"""
Compute union of two version sets.
:param other: Second set of versions.
:returns: Union of two version sets.
"""
selfIterator = self.__iter__()
otherIterator = other.__iter__()
result = []
try:
selfValue = next(selfIterator)
except StopIteration:
for otherValue in otherIterator:
result.append(otherValue)
try:
otherValue = next(otherIterator)
except StopIteration:
for selfValue in selfIterator:
result.append(selfValue)
while True:
if selfValue < otherValue:
result.append(selfValue)
try:
selfValue = next(selfIterator)
except StopIteration:
result.append(otherValue)
for otherValue in otherIterator:
result.append(otherValue)
break
elif otherValue < selfValue:
result.append(otherValue)
try:
otherValue = next(otherIterator)
except StopIteration:
result.append(selfValue)
for selfValue in selfIterator:
result.append(selfValue)
break
else:
result.append(selfValue)
try:
selfValue = next(selfIterator)
except StopIteration:
for otherValue in otherIterator:
result.append(otherValue)
break
try:
otherValue = next(otherIterator)
except StopIteration:
for selfValue in selfIterator:
result.append(selfValue)
break
return VersionSet(result)
def __lt__(self, other: Any) -> bool:
"""
Compare a version set and a version numbers if the version set is less than the second operand (version).
:param other: Operand to compare against.
:returns: ``True``, if version set is less than the second operand (version).
:raises TypeError: If parameter ``other`` is not of type :class:`Version`.
"""
# TODO: support VersionRange < VersionRange too
# TODO: support str, int, ... like Version ?
if not isinstance(other, Version):
ex = TypeError(f"Parameter 'other' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
return self._items[-1] < other
def __le__(self, other: Any) -> bool:
"""
Compare a version set and a version numbers if the version set is less than or equal the second operand (version).
:param other: Operand to compare against.
:returns: ``True``, if version set is less than or equal the second operand (version).
:raises TypeError: If parameter ``other`` is not of type :class:`Version`.
"""
# TODO: support VersionRange < VersionRange too
# TODO: support str, int, ... like Version ?
if not isinstance(other, Version):
ex = TypeError(f"Parameter 'other' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
return self._items[-1] <= other
def __gt__(self, other: Any) -> bool:
"""
Compare a version set and a version numbers if the version set is greater than the second operand (version).
:param other: Operand to compare against.
:returns: ``True``, if version set is greater than the second operand (version).
:raises TypeError: If parameter ``other`` is not of type :class:`Version`.
"""
# TODO: support VersionRange < VersionRange too
# TODO: support str, int, ... like Version ?
if not isinstance(other, Version):
ex = TypeError(f"Parameter 'other' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
return self._items[0] > other
def __ge__(self, other: Any) -> bool:
"""
Compare a version set and a version numbers if the version set is greater than or equal the second operand (version).
:param other: Operand to compare against.
:returns: ``True``, if version set is greater than or equal the second operand (version).
:raises TypeError: If parameter ``other`` is not of type :class:`Version`.
"""
# TODO: support VersionRange < VersionRange too
# TODO: support str, int, ... like Version ?
if not isinstance(other, Version):
ex = TypeError(f"Parameter 'other' is not of type 'Version'.")
ex.add_note(f"Got type '{getFullyQualifiedName(other)}'.")
raise ex
return self._items[0] >= other
def __contains__(self, version: V) -> bool:
"""
Checks if the version a member of the set.
:param version: The version to check.
:returns: ``True``, if the version is a member of the set.
"""
return version in self._items
def __len__(self) -> int:
"""
Returns the number of members in the set.
:returns: Number of set members.
"""
return len(self._items)
def __iter__(self) -> Iterator[V]:
"""
Returns an iterator to iterate all versions of this set from lowest to highest.
:returns: Iterator to iterate versions.
"""
return self._items.__iter__()
def __getitem__(self, index: int) -> V:
"""
Access to a version of a set by index.
:param index: The index of the version to access.
:returns: The indexed version.
.. hint::
Versions are ordered from lowest to highest version number.
"""
return self._items[index]
|