|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import datetime |
| 3 | +import os |
| 4 | +import re |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | + |
| 8 | + |
| 9 | +def run_cmd(cmd_args): |
| 10 | + """Runs a terminal command without shell=True to avoid injection risks.""" |
| 11 | + result = subprocess.run(cmd_args, capture_output=True, text=True, check=True) |
| 12 | + return result.stdout.strip() |
| 13 | + |
| 14 | + |
| 15 | +def get_latest_tag(): |
| 16 | + """Gets the latest git tag reachable from HEAD.""" |
| 17 | + try: |
| 18 | + return run_cmd(["git", "describe", "--tags", "--abbrev=0"]) |
| 19 | + except subprocess.CalledProcessError as e: |
| 20 | + print(f"Error getting latest tag: {e.stderr}", file=sys.stderr) |
| 21 | + raise |
| 22 | + |
| 23 | + |
| 24 | +def parse_version(version_str): |
| 25 | + """Parses a version string like YYYY.M.PATCH[-suffix] into a tuple of integers.""" |
| 26 | + match = re.match(r"^(\d+)\.(\d+)\.(\d+)", version_str) |
| 27 | + if not match: |
| 28 | + raise ValueError( |
| 29 | + f"Version '{version_str}' does not match expected CalVer pattern YYYY.M.PATCH" |
| 30 | + ) |
| 31 | + return tuple(map(int, match.groups())) |
| 32 | + |
| 33 | + |
| 34 | +def calculate_next_version(latest_tag): |
| 35 | + """Calculates the next CalVer version based on the latest tag and current date.""" |
| 36 | + latest_ver = parse_version(latest_tag) |
| 37 | + tag_year, tag_month, tag_patch = latest_ver |
| 38 | + |
| 39 | + now = datetime.datetime.now(datetime.timezone.utc) |
| 40 | + current_year = now.year |
| 41 | + current_month = now.month |
| 42 | + |
| 43 | + if tag_year == current_year and tag_month == current_month: |
| 44 | + # Same month, increment patch |
| 45 | + next_patch = tag_patch + 1 |
| 46 | + else: |
| 47 | + # New month, reset patch to 0 |
| 48 | + next_patch = 0 |
| 49 | + |
| 50 | + next_version_str = f"{current_year}.{current_month}.{next_patch}" |
| 51 | + next_ver = parse_version(next_version_str) |
| 52 | + |
| 53 | + # Safety guard: Ensure we never release a version older or equal to the last one |
| 54 | + if next_ver <= latest_ver: |
| 55 | + raise ValueError( |
| 56 | + f"Calculated next version ({next_version_str}) is not newer than " |
| 57 | + f"the latest tag ({latest_tag}). Potential version regression!" |
| 58 | + ) |
| 59 | + |
| 60 | + return next_version_str |
| 61 | + |
| 62 | + |
| 63 | +def get_changelog_entries(latest_tag): |
| 64 | + """Retrieves all non-merge commit subjects since the latest tag.""" |
| 65 | + cmd_args = [ |
| 66 | + "git", |
| 67 | + "log", |
| 68 | + f"{latest_tag}..HEAD", |
| 69 | + "--no-merges", |
| 70 | + "--pretty=format:* %s", |
| 71 | + ] |
| 72 | + log_output = run_cmd(cmd_args) |
| 73 | + if not log_output: |
| 74 | + return ["* No changes (released in sync with fsspec)."] |
| 75 | + return log_output.split("\n") |
| 76 | + |
| 77 | + |
| 78 | +def update_changelog_file(changelog_path, version, entries): |
| 79 | + """Inserts a new release section with version and commit logs into the changelog.rst file.""" |
| 80 | + if not os.path.exists(changelog_path): |
| 81 | + raise FileNotFoundError(f"Changelog file not found at {changelog_path}") |
| 82 | + |
| 83 | + with open(changelog_path, "r", encoding="utf-8") as f: |
| 84 | + content = f.read() |
| 85 | + |
| 86 | + lines = content.split("\n") |
| 87 | + insert_idx = -1 |
| 88 | + # Regex to match version header (e.g., "2026.4.0") |
| 89 | + version_re = re.compile(r"^\d{4}\.\d+\.\d+$") |
| 90 | + |
| 91 | + for i in range(len(lines) - 1): |
| 92 | + if ( |
| 93 | + version_re.match(lines[i]) |
| 94 | + and lines[i + 1].startswith("---") |
| 95 | + and len(lines[i + 1]) >= len(lines[i]) |
| 96 | + ): |
| 97 | + insert_idx = i |
| 98 | + break |
| 99 | + |
| 100 | + if insert_idx == -1: |
| 101 | + # If we couldn't find a version header, we might be in an empty or differently formatted file. |
| 102 | + # In this case, we raise an error. |
| 103 | + raise ValueError( |
| 104 | + "Could not find a valid version header in changelog to insert before." |
| 105 | + ) |
| 106 | + |
| 107 | + # Prepare the new section |
| 108 | + version_underline = "-" * len(version) |
| 109 | + new_section_lines = ( |
| 110 | + [ |
| 111 | + version, |
| 112 | + version_underline, |
| 113 | + "", |
| 114 | + ] |
| 115 | + + entries |
| 116 | + + [""] |
| 117 | + ) |
| 118 | + |
| 119 | + # Insert the new section. We want to keep an empty line between sections. |
| 120 | + # The first version header we found should be pushed down. |
| 121 | + # We insert before the version line. |
| 122 | + updated_lines = lines[:insert_idx] + new_section_lines + lines[insert_idx:] |
| 123 | + |
| 124 | + with open(changelog_path, "w", encoding="utf-8") as f: |
| 125 | + f.write("\n".join(updated_lines)) |
| 126 | + |
| 127 | + print(f"Successfully updated changelog with version {version}") |
| 128 | + |
| 129 | + |
| 130 | +def main(): |
| 131 | + changelog_path = "docs/source/changelog.rst" |
| 132 | + |
| 133 | + try: |
| 134 | + # 1. Retrieve the latest release tag from Git |
| 135 | + latest_tag = get_latest_tag() |
| 136 | + print(f"Latest tag found: {latest_tag}") |
| 137 | + |
| 138 | + # 2. Calculate the next CalVer version and perform regression checks |
| 139 | + next_version = calculate_next_version(latest_tag) |
| 140 | + print(f"Calculated next version: {next_version}") |
| 141 | + |
| 142 | + # 3. Fetch the changelog entries (non-merge commits) since the last tag |
| 143 | + entries = get_changelog_entries(latest_tag) |
| 144 | + print(f"Found {len(entries)} changelog entries.") |
| 145 | + |
| 146 | + # 4. Update the changelog file in place with the new release section |
| 147 | + update_changelog_file(changelog_path, next_version, entries) |
| 148 | + |
| 149 | + # 5. Output the version to GITHUB_ENV for downstream workflow consumption |
| 150 | + print(f"NEXT_VERSION={next_version}") |
| 151 | + if "GITHUB_ENV" in os.environ: |
| 152 | + with open(os.environ["GITHUB_ENV"], "a") as gh_env: |
| 153 | + gh_env.write(f"VERSION={next_version}\n") |
| 154 | + gh_env.write(f"BRANCH_NAME=release-{next_version}\n") |
| 155 | + |
| 156 | + except Exception as e: |
| 157 | + print(f"Error: {e}", file=sys.stderr) |
| 158 | + sys.exit(1) |
| 159 | + |
| 160 | + |
| 161 | +if __name__ == "__main__": |
| 162 | + main() |
0 commit comments