-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathsync_version.py
More file actions
205 lines (171 loc) · 7.66 KB
/
Copy pathsync_version.py
File metadata and controls
205 lines (171 loc) · 7.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/usr/bin/env python3
import json
import pathlib
import re
import subprocess
import sys
import urllib.request
INIT_FILE = pathlib.Path("socketsecurity/__init__.py")
PYPROJECT_FILE = pathlib.Path("pyproject.toml")
UV_LOCK_FILE = pathlib.Path("uv.lock")
VERSION_PATTERN = re.compile(r"__version__\s*=\s*['\"]([^'\"]+)['\"]")
PYPROJECT_PATTERN = re.compile(r'^version\s*=\s*".*"$', re.MULTILINE)
STABLE_VERSION_PATTERN = re.compile(r"^\d+\.\d+\.\d+$")
PYPI_PROD_API = "https://pypi.org/pypi/socketsecurity/json"
PYPI_TEST_API = "https://test.pypi.org/pypi/socketsecurity/json"
def read_version_from_init(path: pathlib.Path) -> str:
content = path.read_text()
match = VERSION_PATTERN.search(content)
if not match:
print(f"❌ Could not find __version__ in {path}")
sys.exit(1)
return match.group(1)
def read_version_from_git(path: str) -> str:
try:
output = subprocess.check_output(["git", "show", f"HEAD:{path}"], text=True)
match = VERSION_PATTERN.search(output)
if not match:
return None
return match.group(1)
except subprocess.CalledProcessError:
return None
def bump_patch_version(version: str) -> str:
if ".dev" in version:
version = version.split(".dev")[0]
parts = version.split(".")
parts[-1] = str(int(parts[-1]) + 1)
return ".".join(parts)
def parse_stable_version(version: str):
if not STABLE_VERSION_PATTERN.fullmatch(version):
return None
return tuple(int(part) for part in version.split("."))
def format_stable_version(version_parts) -> str:
return ".".join(str(part) for part in version_parts)
def fetch_existing_versions(api_url: str) -> set:
try:
with urllib.request.urlopen(api_url) as response:
data = json.load(response)
return set(data.get("releases", {}).keys())
except Exception as e:
print(f"⚠️ Warning: Failed to fetch versions from {api_url}: {e}")
return set()
def fetch_latest_stable_pypi_version():
versions = fetch_existing_versions(PYPI_PROD_API)
stable_versions = []
for ver in versions:
parsed = parse_stable_version(ver)
if parsed is not None:
stable_versions.append(parsed)
if not stable_versions:
return None
return max(stable_versions)
def find_next_available_dev_version(base_version: str) -> str:
existing_versions = fetch_existing_versions(PYPI_TEST_API)
for i in range(1, 100):
candidate = f"{base_version}.dev{i}"
if candidate not in existing_versions:
return candidate
print("❌ Could not find available .devN slot after 100 attempts.")
sys.exit(1)
def find_next_stable_patch_version(current_version: str) -> str:
current_stable = current_version.split(".dev")[0] if ".dev" in current_version else current_version
current_parts = parse_stable_version(current_stable)
if current_parts is None:
print(f"❌ Unsupported version format for stable bump: {current_version}")
sys.exit(1)
latest_pypi_parts = fetch_latest_stable_pypi_version()
base_parts = max([current_parts, latest_pypi_parts] if latest_pypi_parts else [current_parts])
next_parts = (base_parts[0], base_parts[1], base_parts[2] + 1)
return format_stable_version(next_parts)
def inject_version(version: str):
print(f"🔁 Updating version to: {version}")
# Update __init__.py
init_content = INIT_FILE.read_text()
new_init_content = VERSION_PATTERN.sub(f"__version__ = '{version}'", init_content)
INIT_FILE.write_text(new_init_content)
# Update pyproject.toml
pyproject = PYPROJECT_FILE.read_text()
if PYPROJECT_PATTERN.search(pyproject):
new_pyproject = PYPROJECT_PATTERN.sub(f'version = "{version}"', pyproject)
else:
new_pyproject = re.sub(r"(\[project\])", rf"\1\nversion = \"{version}\"", pyproject)
PYPROJECT_FILE.write_text(new_pyproject)
def run_uv_lock() -> bool:
before = UV_LOCK_FILE.read_bytes() if UV_LOCK_FILE.exists() else b""
try:
subprocess.run(["uv", "lock"], check=True, text=True)
except FileNotFoundError:
print("❌ `uv` is required but was not found in PATH.")
sys.exit(1)
except subprocess.CalledProcessError:
print("❌ `uv lock` failed. Please run it manually and fix any errors.")
sys.exit(1)
after = UV_LOCK_FILE.read_bytes() if UV_LOCK_FILE.exists() else b""
return before != after
def read_preview_id():
if "--preview-id" not in sys.argv:
return None
option_index = sys.argv.index("--preview-id")
try:
preview_id = sys.argv[option_index + 1]
except IndexError:
print("❌ `--preview-id` requires a numeric value.")
sys.exit(1)
if not preview_id.isascii() or not preview_id.isdigit():
print("❌ `--preview-id` must contain ASCII digits only.")
sys.exit(1)
return preview_id
def main():
dev_mode = "--dev" in sys.argv
skip_lock = "--skip-lock" in sys.argv
preview_id = read_preview_id()
current_version = read_version_from_init(INIT_FILE)
previous_version = read_version_from_git("socketsecurity/__init__.py")
print(f"Current: {current_version}, Previous: {previous_version}")
if preview_id is not None:
if not dev_mode:
print("❌ `--preview-id` can only be used with `--dev`.")
sys.exit(1)
base_version = current_version.split(".dev")[0]
new_version = f"{base_version}.dev{preview_id}"
inject_version(new_version)
if not skip_lock:
run_uv_lock()
print(f"✅ Prepared deterministic preview version {new_version}.")
sys.exit(0)
if current_version == previous_version:
if dev_mode:
base_version = current_version.split(".dev")[0] if ".dev" in current_version else current_version
new_version = find_next_available_dev_version(base_version)
inject_version(new_version)
uv_lock_changed = run_uv_lock()
lock_hint = " and uv.lock" if uv_lock_changed else ""
print(f"⚠️ Version was unchanged — auto-bumped. Please git add{lock_hint} + commit again.")
sys.exit(0)
else:
new_version = find_next_stable_patch_version(current_version)
inject_version(new_version)
uv_lock_changed = run_uv_lock()
lock_hint = " and uv.lock" if uv_lock_changed else ""
print(f"⚠️ Version was unchanged — auto-bumped to {new_version}. Please git add{lock_hint} + commit again.")
sys.exit(1)
else:
if not dev_mode:
current_parts = parse_stable_version(current_version)
latest_pypi_parts = fetch_latest_stable_pypi_version()
if current_parts is not None and latest_pypi_parts is not None and current_parts <= latest_pypi_parts:
next_parts = (latest_pypi_parts[0], latest_pypi_parts[1], latest_pypi_parts[2] + 1)
new_version = format_stable_version(next_parts)
inject_version(new_version)
uv_lock_changed = run_uv_lock()
lock_hint = " and uv.lock" if uv_lock_changed else ""
print(f"⚠️ Version {current_version} is already published on PyPI — auto-bumped to {new_version}. Please git add{lock_hint} + commit again.")
sys.exit(1)
uv_lock_changed = run_uv_lock()
if uv_lock_changed:
print("⚠️ Version already bumped, but uv.lock was out of date and has been updated. Please git add uv.lock + commit again.")
sys.exit(1)
print("✅ Version already bumped and uv.lock is up to date — proceeding.")
sys.exit(0)
if __name__ == "__main__":
main()