get_version.py
1 """Get current project version from Git tags or changelog.""" 2 3 import re 4 from contextlib import suppress 5 from pathlib import Path 6 7 from pdm.backend.hooks.version import SCMVersion, Version, default_version_formatter, get_version_from_scm 8 9 _root = Path(__file__).parent.parent 10 _changelog = _root / "CHANGELOG.md" 11 _changelog_version_re = re.compile(r"^## \[(\d+\.\d+\.\d+)\].*$") 12 _default_scm_version = SCMVersion(Version("0.0.0"), None, False, None, None) # noqa: FBT003 13 14 15 def get_version() -> str: 16 """Get current project version from Git tags or changelog.""" 17 scm_version = get_version_from_scm(_root) or _default_scm_version 18 if scm_version.version <= Version("0.1"): # Missing Git tags? 19 with suppress(OSError, StopIteration): # noqa: SIM117 20 with _changelog.open("r", encoding="utf8") as file: 21 match = next(filter(None, map(_changelog_version_re.match, file))) 22 scm_version = scm_version._replace(version=Version(match.group(1))) 23 return default_version_formatter(scm_version) 24 25 26 if __name__ == "__main__": 27 print(get_version())