|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +"""A script to synchronize the version from _version.py to CITATION.cff.""" |
| 4 | + |
| 5 | +import re |
| 6 | +import sys |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +# --- Configuration --------------------------------------------------- |
| 10 | + |
| 11 | +# Append the parent directory (simopt package) to the system path |
| 12 | +SIMOPT_PACKAGE_DIR = Path(__file__).resolve().parent.parent |
| 13 | +sys.path.append(str(SIMOPT_PACKAGE_DIR)) |
| 14 | + |
| 15 | +# Source directory containing the _version.py file |
| 16 | +SIMOPT_DIR = SIMOPT_PACKAGE_DIR / "simopt" |
| 17 | + |
| 18 | +# Source of the citation file |
| 19 | +CITATION_FILENAME = "CITATION.cff" |
| 20 | +CITATION_FILE: Path = SIMOPT_PACKAGE_DIR / CITATION_FILENAME |
| 21 | + |
| 22 | +# Regex pattern to identify the version line in CITATION.cff |
| 23 | + |
| 24 | +VERSION_PATTERN = re.compile(r"^(version:\s*).+$") |
| 25 | + |
| 26 | +# --------------------------------------------------------------------- |
| 27 | + |
| 28 | + |
| 29 | +def main() -> None: |
| 30 | + """Reads the version and updates the CITATION.cff file.""" |
| 31 | + # --- Get the source version --- |
| 32 | + from simopt._version import __version__ |
| 33 | + |
| 34 | + # --- Read and update the CITATION.cff file --- |
| 35 | + if not CITATION_FILE.exists(): |
| 36 | + print(f"Error: File not found at {CITATION_FILE}") |
| 37 | + sys.exit(1) |
| 38 | + |
| 39 | + # We use 'str(__version__)' to handle non-string version types |
| 40 | + # and add quotes to be safe YAML, especially for pre-release tags. |
| 41 | + replacement_line = f'version: "{__version__!s}"' |
| 42 | + |
| 43 | + print(f"Updating {CITATION_FILE}...") |
| 44 | + |
| 45 | + new_lines = [] |
| 46 | + found = False |
| 47 | + |
| 48 | + with CITATION_FILE.open("r") as f: |
| 49 | + for line in f: |
| 50 | + # Check if the line matches our version pattern |
| 51 | + if not found and VERSION_PATTERN.match(line): |
| 52 | + # If it matches, replace it with our new line |
| 53 | + new_lines.append(replacement_line + "\n") |
| 54 | + found = True |
| 55 | + print(f" - Replaced: {line.strip()}") |
| 56 | + print(f" + With: {replacement_line}") |
| 57 | + else: |
| 58 | + # Otherwise, keep the line as-is |
| 59 | + new_lines.append(line) |
| 60 | + |
| 61 | + if not found: |
| 62 | + print("Error: A 'version:' line was not found in the file.") |
| 63 | + sys.exit(1) |
| 64 | + |
| 65 | + # Write the modified content back to the file |
| 66 | + with CITATION_FILE.open("w") as f: |
| 67 | + f.writelines(new_lines) |
| 68 | + |
| 69 | + print("Update complete.") |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + main() |
0 commit comments