version.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env python3
  2. """Check the three version fields, or set them together. No dependencies."""
  3. from __future__ import annotations
  4. import argparse
  5. from pathlib import Path
  6. import re
  7. import tomllib
  8. ROOT = Path(__file__).resolve().parents[1]
  9. VERSION_FILE = ROOT / "VERSION"
  10. PROJECT_FILE = ROOT / "pyproject.toml"
  11. PACKAGE_FILE = ROOT / "src/stl_backend/__init__.py"
  12. PLAIN_VERSION = re.compile(r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)")
  13. def read_fields() -> dict[str, str]:
  14. package = PACKAGE_FILE.read_text(encoding="utf-8")
  15. values = re.findall(r'^__version__ = "([^"]+)"$', package, re.MULTILINE)
  16. if len(values) != 1:
  17. raise ValueError("Expected exactly one __version__ assignment")
  18. project = tomllib.loads(PROJECT_FILE.read_text(encoding="utf-8"))
  19. return {
  20. "VERSION": VERSION_FILE.read_text(encoding="utf-8").strip(),
  21. "pyproject.toml": project["project"]["version"],
  22. "src/stl_backend/__init__.py": values[0],
  23. }
  24. def replace_one(text: str, pattern: str, replacement: str) -> str:
  25. updated, count = re.subn(pattern, replacement, text, flags=re.MULTILINE)
  26. if count != 1:
  27. raise ValueError("Expected exactly one version field; no files were changed")
  28. return updated
  29. def main() -> None:
  30. parser = argparse.ArgumentParser(description=__doc__)
  31. parser.add_argument("action", choices=("check", "set"))
  32. parser.add_argument("version", nargs="?")
  33. args = parser.parse_args()
  34. if (args.action == "set") != (args.version is not None):
  35. parser.error("Use 'check' or 'set X.Y.Z'")
  36. try:
  37. if args.action == "set":
  38. if not PLAIN_VERSION.fullmatch(args.version):
  39. raise ValueError("Version must be X.Y.Z, for example 0.1.1")
  40. project = replace_one(PROJECT_FILE.read_text(encoding="utf-8"),
  41. r'^version = "[^"]+"$', f'version = "{args.version}"')
  42. package = replace_one(PACKAGE_FILE.read_text(encoding="utf-8"),
  43. r'^__version__ = "[^"]+"$', f'__version__ = "{args.version}"')
  44. PROJECT_FILE.write_text(project, encoding="utf-8")
  45. PACKAGE_FILE.write_text(package, encoding="utf-8")
  46. VERSION_FILE.write_text(args.version + "\n", encoding="utf-8")
  47. fields = read_fields()
  48. expected = fields["VERSION"]
  49. if not PLAIN_VERSION.fullmatch(expected) or any(v != expected for v in fields.values()):
  50. raise ValueError(f"Version mismatch: {fields}; use 'set X.Y.Z' to synchronize")
  51. print(f"Version OK: {expected}")
  52. except (OSError, ValueError, KeyError) as exc:
  53. parser.exit(1, f"Version error: {exc}\n")
  54. if __name__ == "__main__":
  55. main()