示例工程 39-ci-cd-release-pipeline

39-ci-cd-release-pipeline/04-tag-version/tag_version.py

python · 0.9 KB

"""从 git tag 推导包版本号,并生成 __version__ 行。"""
 
from __future__ import annotations
 
import re
 
SEMVER = re.compile(r"^v?(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)$")
 
 
class VersionError(ValueError):
    """tag 不是合法的 SemVer。"""
 
 
def version_from_tag(tag: str | None, fallback: str = "0.0.0+dev") -> str:
    if not tag:
        return fallback
    match = SEMVER.match(tag.strip())
    if match is None:
        raise VersionError(f"tag {tag!r} is not MAJOR.MINOR.PATCH")
    return f"{match['major']}.{match['minor']}.{match['patch']}"
 
 
def version_line(version: str) -> str:
    return f'__version__ = "{version}"'
 
 
def main() -> None:
    print(f"release: {version_from_tag('v1.2.3')}")
    print(f"dev: {version_from_tag(None)}")
    try:
        version_from_tag("v1.2")
    except VersionError as exc:
        print(f"invalid: {exc}")
 
 
if __name__ == "__main__":
    main()