Skip to content

Commit bf9792c

Browse files
Copilotbenoit-cty
andcommitted
Improve pyproject_versions.py with version coherence checking
Co-authored-by: benoit-cty <6603048+benoit-cty@users.noreply.github.com>
1 parent da7b85e commit bf9792c

1 file changed

Lines changed: 117 additions & 1 deletion

File tree

.github/pyproject_versions.py

Lines changed: 117 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,112 @@
11
# Read package version in pyproject.toml and replace it in .conda/recipe.yaml
2+
# Also provides version coherence checking across multiple files
23

34
import argparse
45
import logging
6+
import re
7+
import sys
58
import tomllib
69

710
logging.basicConfig(level=logging.INFO, format="%(message)s")
811
PACKAGE_VERSION = "X.X.X"
912

1013

14+
def get_version_from_file(filepath: str, pattern: str) -> str:
15+
"""
16+
Extract version from a file using a regex pattern.
17+
18+
:param filepath: Path to the file to read
19+
:param pattern: Regex pattern to match the version
20+
:return: The version string found
21+
:raises: Exception if version not found
22+
"""
23+
try:
24+
with open(filepath, "rt") as file:
25+
content = file.read()
26+
27+
match = re.search(pattern, content, re.MULTILINE)
28+
if match:
29+
return match.group(1)
30+
else:
31+
raise Exception(f"Version pattern '{pattern}' not found in {filepath}")
32+
except FileNotFoundError:
33+
raise Exception(f"File not found: {filepath}")
34+
35+
36+
def get_all_versions() -> dict:
37+
"""
38+
Read versions from all three files managed by bumpver.
39+
40+
:return: Dict containing versions from all files
41+
"""
42+
versions = {}
43+
44+
# Get version from pyproject.toml
45+
try:
46+
with open("./pyproject.toml", "rb") as file:
47+
content = tomllib.load(file)
48+
versions["pyproject_toml"] = (
49+
content.get("tool", {}).get("bumpver", {}).get("current_version", None)
50+
)
51+
if versions["pyproject_toml"] is None:
52+
raise Exception(
53+
"current_version not found in pyproject.toml [tool.bumpver] section"
54+
)
55+
except FileNotFoundError:
56+
raise Exception("pyproject.toml not found")
57+
58+
# Get version from codecarbon/_version.py
59+
versions["codecarbon_version"] = get_version_from_file(
60+
"codecarbon/_version.py", r'^__version__\s*=\s*["\']([^"\']+)["\']'
61+
)
62+
63+
# Get version from docs/edit/conf.py
64+
versions["docs_conf"] = get_version_from_file(
65+
"docs/edit/conf.py", r'^release\s*=\s*["\']([^"\']+)["\']'
66+
)
67+
68+
return versions
69+
70+
71+
def check_version_coherence() -> bool:
72+
"""
73+
Check that all version files have the same version.
74+
75+
:return: True if all versions match, False otherwise
76+
"""
77+
try:
78+
versions = get_all_versions()
79+
80+
# Get unique versions
81+
unique_versions = set(versions.values())
82+
83+
if len(unique_versions) == 1:
84+
version = list(unique_versions)[0]
85+
logging.info(
86+
f"✓ Version coherence check passed. All files have version: {version}"
87+
)
88+
return True
89+
else:
90+
logging.error(
91+
"✗ Version coherence check failed! Versions are inconsistent:"
92+
)
93+
for file_key, version in versions.items():
94+
file_mapping = {
95+
"pyproject_toml": "pyproject.toml [tool.bumpver] current_version",
96+
"codecarbon_version": "codecarbon/_version.py __version__",
97+
"docs_conf": "docs/edit/conf.py release",
98+
}
99+
logging.error(f" {file_mapping[file_key]}: {version}")
100+
logging.error(
101+
"\nPlease use 'bumpver' to update versions consistently across all files."
102+
)
103+
return False
104+
105+
except Exception as e:
106+
logging.error(f"✗ Error checking version coherence: {e}")
107+
return False
108+
109+
11110
def get_versions():
12111
"""
13112
Read package version and deps in pyproject.toml
@@ -84,11 +183,28 @@ def replace_in_file(filepath: str, info: dict):
84183
default=False,
85184
help="Only display current package version",
86185
)
186+
parser.add_argument(
187+
"-c",
188+
"--check_coherence",
189+
action="store_true",
190+
help="Check version coherence across all bumpver-managed files",
191+
)
87192
args = parser.parse_args()
193+
194+
# Check version coherence first if requested or before any operations
195+
if args.check_coherence:
196+
coherence_ok = check_version_coherence()
197+
sys.exit(0 if coherence_ok else 1)
198+
199+
# Always check coherence before doing replacements or showing versions
200+
if not check_version_coherence():
201+
logging.error("Aborting due to version coherence issues.")
202+
sys.exit(1)
203+
88204
info = get_versions()
89205
file = args.filename
90206
if args.only_package_version:
91-
print(f'{info["openfisca_france"]}') # noqa: T201
207+
print(f'{info["package_version"]}') # Fixed: was "openfisca_france"
92208
exit()
93209
logging.info("Versions :")
94210
print(info) # noqa: T201

0 commit comments

Comments
 (0)