|
| 1 | +"""Infer semver bump from towncrier fragment types and update version.""" |
| 2 | + |
| 3 | +import re |
| 4 | +import sys |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | + |
| 8 | +def get_current_version(pyproject_path: Path) -> str: |
| 9 | + text = pyproject_path.read_text() |
| 10 | + match = re.search(r'^version\s*=\s*"(\d+\.\d+\.\d+)"', text, re.MULTILINE) |
| 11 | + if not match: |
| 12 | + print( |
| 13 | + "Could not find version in pyproject.toml", |
| 14 | + file=sys.stderr, |
| 15 | + ) |
| 16 | + sys.exit(1) |
| 17 | + return match.group(1) |
| 18 | + |
| 19 | + |
| 20 | +def infer_bump(changelog_dir: Path) -> str: |
| 21 | + fragments = [ |
| 22 | + f for f in changelog_dir.iterdir() if f.is_file() and f.name != ".gitkeep" |
| 23 | + ] |
| 24 | + if not fragments: |
| 25 | + print("No changelog fragments found", file=sys.stderr) |
| 26 | + sys.exit(1) |
| 27 | + |
| 28 | + categories = {f.suffix.lstrip(".") for f in fragments} |
| 29 | + for f in fragments: |
| 30 | + parts = f.stem.split(".") |
| 31 | + if len(parts) >= 2: |
| 32 | + categories.add(parts[-1]) |
| 33 | + |
| 34 | + if "breaking" in categories: |
| 35 | + return "major" |
| 36 | + if "added" in categories or "removed" in categories: |
| 37 | + return "minor" |
| 38 | + return "patch" |
| 39 | + |
| 40 | + |
| 41 | +def bump_version(version: str, bump: str) -> str: |
| 42 | + major, minor, patch = (int(x) for x in version.split(".")) |
| 43 | + if bump == "major": |
| 44 | + return f"{major + 1}.0.0" |
| 45 | + elif bump == "minor": |
| 46 | + return f"{major}.{minor + 1}.0" |
| 47 | + else: |
| 48 | + return f"{major}.{minor}.{patch + 1}" |
| 49 | + |
| 50 | + |
| 51 | +def update_file(path: Path, old_version: str, new_version: str): |
| 52 | + text = path.read_text() |
| 53 | + updated = text.replace( |
| 54 | + f'version = "{old_version}"', |
| 55 | + f'version = "{new_version}"', |
| 56 | + ) |
| 57 | + if updated != text: |
| 58 | + path.write_text(updated) |
| 59 | + print(f" Updated {path}") |
| 60 | + |
| 61 | + |
| 62 | +def main(): |
| 63 | + root = Path(__file__).resolve().parent.parent |
| 64 | + pyproject = root / "pyproject.toml" |
| 65 | + changelog_dir = root / "changelog.d" |
| 66 | + |
| 67 | + current = get_current_version(pyproject) |
| 68 | + bump = infer_bump(changelog_dir) |
| 69 | + new = bump_version(current, bump) |
| 70 | + |
| 71 | + print(f"Version: {current} -> {new} ({bump})") |
| 72 | + |
| 73 | + update_file(pyproject, current, new) |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + main() |
0 commit comments