-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathbump_version.py
355 lines (273 loc) · 11.8 KB
/
bump_version.py
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import json
import re
import argparse
import sys
import difflib
from datetime import datetime
from pathlib import Path
from typing import Tuple, Optional
# Define directories and files
DIR_ROOT = Path(__file__).resolve().parent
FILE_VERSION = DIR_ROOT / "VERSION.json"
DIR_SRC = DIR_ROOT / "src"
DIR_PACKAGE = DIR_ROOT / "packages"
# Version regex patterns
PATTERN_STAGES = ['alpha', 'beta', 'rc']
PATTERN_VERSION = r'\d+\.\d+\.\d+'
PATTERN_STAGE = r'({})\d{{1,2}}'.format('|'.join(PATTERN_STAGES))
# Control variables
DRY_RUN = False
VERBOSE = False
def debug_globals() -> str:
"""Get global variables for debugging."""
dg = f"DIR_ROOT: {DIR_ROOT}\nFILE_VERSION: {FILE_VERSION}\n\n"
dg += f"DIR_SRC: {DIR_SRC}\n"
dg += f"DIR_PACKAGE: {DIR_PACKAGE}\n"
dg += f"PATTERN_STAGES: {PATTERN_STAGES}\nPATTERN_VERSION: {PATTERN_VERSION}\nPATTERN_STAGE: {PATTERN_STAGE}\n\n"
dg += f"DRY_RUN: {DRY_RUN}\nVERBOSE: {VERBOSE}\n"
return dg
def print_v(text: str) -> None:
if VERBOSE:
print(text)
class Command:
def __init__(self, file: Path, backup_text: str, new_text: str):
self._file = file
self._backup_text = backup_text
self._new_text = new_text
def do(self) -> Optional[str]:
try:
self._file.write_text(self._new_text)
print_v(f"Updated {self._file}")
except Exception as e:
print_v(f"Failed to update {self._file}: {e}")
return str(e)
return None
def undo(self) -> Optional[str]:
try:
self._file.write_text(self._backup_text)
print_v(f"Reverted {self._file}")
except Exception as e:
print_v(f"Failed to revert {self._file}: {e}")
return str(e)
return None
def diff(self) -> str:
# Show only differences from backup and new
diff = difflib.unified_diff(
self._backup_text.splitlines(), self._new_text.splitlines(), lineterm='', n=1)
return "{}:\n{}\n".format(self._file, "\n".join(diff))
class Executor:
def __init__(self):
self._commands = []
self._do_errors = []
self._undo_errors = []
self._current_index = 0
def add_command(self, command: Command):
self._commands.append(command)
def execute(self, dry_run: bool = False):
for self._current_index, command in enumerate(self._commands):
if dry_run:
print(command.diff())
else:
error = command.do()
if error:
self._do_errors.append(error)
for i in range(self._current_index, -1, -1):
error = self._commands[i].undo()
if error:
self._undo_errors.append(error)
def validate_version(version: str) -> None:
"""Validate version format.
Raises:
ValueError: If version is invalid.
"""
if not isinstance(version, str):
raise ValueError(f"Version must be a string, got {type(version)}")
if not re.match(f'^{PATTERN_VERSION}$', version):
raise ValueError(f"Invalid version value '{version}'")
def validate_stage(stage: str) -> None:
"""Validate stage format.
Raises:
ValueError: If stage is invalid.
"""
if not isinstance(stage, str):
raise ValueError(f"Stage must be a string, got {type(stage)}")
if not re.match(f'^{PATTERN_STAGE}$', stage):
raise ValueError(f"Invalid stage value '{stage}'")
def validate_date(date: str) -> None:
"""Validate date format.
Raises:
ValueError: If date is invalid.
"""
pass
def load_version(version_file_path: Path) -> Tuple[str, str]:
"""Load version and stage from VERSION.json.
Returns:
Tuple[str, str]: (version, stage)
Raises:
FileNotFoundError: If VERSION.json does not exist.
ValueError: If VERSION.json is invalid or missing keys.
"""
if not version_file_path.exists():
raise FileNotFoundError(f"{version_file_path} not found")
try:
with version_file_path.open("r", encoding="utf-8") as f:
json_version = json.load(f)
except json.JSONDecodeError:
raise ValueError(
f"{version_file_path} is not a valid JSON file")
version = json_version.get("version")
stage = json_version.get("stage")
if not version or not stage:
raise ValueError(
f"Missing 'version' or 'stage' in {version_file_path}")
validate_version(version)
validate_stage(stage)
return version, stage
def update_file_version(executor: Executor, file_path: Path, new_version: Optional[str] = None, new_stage: Optional[str] = None) -> None:
"""Update version file
Args:
executor (Executor): Executor to handle commands.
file_path (Path): Path to file.
new_version (Optional[str], optional): Defaults to None.
new_stage (Optional[str], optional): Defaults to None.
Raises:
Exception: If failed to create a command.
"""
if not new_version and not new_stage:
return
current = file_path.read_text()
updated = json.loads(current)
if new_version:
updated["version"] = new_version
if new_stage:
updated["stage"] = new_stage
to_write = json.dumps(updated, indent=4) + "\n"
if current != to_write:
executor.add_command(
Command(file_path, current, to_write))
def update_file(executor: Executor, file_path: Path, patterns: dict[str, tuple[re.Pattern, Optional[str]]]) -> None:
"""Helper function to update patterns in a given file."""
content = file_path.read_text()
updated_content = content
for key, (pattern, replacement) in patterns.items():
if replacement:
updated_content = pattern.sub(
replacement, updated_content)
if content != updated_content:
executor.add_command(Command(file_path, content, updated_content))
def update_file_sources(executor: Executor, new_version: Optional[str] = None, new_stage: Optional[str] = None) -> None:
"""Update source files with new version and stage."""
if not new_version and not new_stage:
return
# Update Doxyfile
patterns_doxyfile = {
"version": (re.compile(fr'(PROJECT_NUMBER\s+=\s+"v)({PATTERN_VERSION})("$)', re.MULTILINE), fr'\g<1>{new_version}\g<3>' if new_version else None)
}
update_file(executor, DIR_SRC / 'Doxyfile', patterns_doxyfile)
# Update vcpkg.json
vcpkg_json_path = DIR_SRC / "vcpkg.json"
if vcpkg_json_path.exists():
current = vcpkg_json_path.read_text()
vcpkg_data = json.loads(current)
if new_version:
vcpkg_data["version"] = new_version
to_write = json.dumps(vcpkg_data, indent=4) + "\n"
if current != to_write:
executor.add_command(Command(vcpkg_json_path, current, to_write))
def update_file_packages(executor: Executor, new_version: str, new_stage: str, new_date: str) -> None:
"""Update package-related files with new version, stage, and release date."""
major, minor, patch = new_version.split('.')
formatted_date = datetime.strptime(
new_date, "%Y-%m-%d").strftime("%a, %d %b %Y 00:00:00 +0000")
spec_date = datetime.strptime(
new_date, "%Y-%m-%d").strftime("%a %b %d %Y")
# Define regex patterns for different files
pattern_spec = re.compile(r"^.+\.spec$")
pattern_changelog = re.compile(r"^changelog$")
pattern_copyright = re.compile(r"^copyright$")
pattern_pkginfo = re.compile(r"^pkginfo$")
# Update .spec files
for spec_file in [f for f in DIR_PACKAGE.rglob("*") if pattern_spec.match(f.name)]:
patterns = {
"changelog_entry": (re.compile(r"(^%changelog\s*$)", re.MULTILINE),
rf'\g<1>\n* {spec_date} support <[email protected]> - {new_version}\n- More info: https://documentation.wazuh.com/current/release-notes/release-{new_version.replace(".", "-")}.html')
}
update_file(executor, spec_file, patterns)
# Update changelog files
for changelog_file in [f for f in DIR_PACKAGE.rglob("*") if pattern_changelog.match(f.name)]:
install_type = changelog_file.resolve().parent.parent.name
patterns = {
"changelog_entry": (re.compile('^'),
rf'{install_type} ({new_version}-RELEASE) stable; urgency=low\n\n * More info: https://documentation.wazuh.com/current/release-notes/release-{new_version.replace(".", "-")}.html\n\n -- Wazuh, Inc <[email protected]> {formatted_date}\n\n')
}
update_file(executor, changelog_file, patterns)
# Update copyright files
for copyright_file in [f for f in DIR_PACKAGE.rglob("*") if pattern_copyright.match(f.name)]:
patterns = {
"copyright_date": (re.compile(
rf'(^ Wazuh, Inc <[email protected]> on )(.+)($)', re.MULTILINE), fr'\g<1>{formatted_date}\g<3>'),
}
update_file(executor, copyright_file, patterns)
# Update pkginfo files
for pkginfo_file in [f for f in DIR_PACKAGE.rglob("*") if pattern_pkginfo.match(f.name)]:
patterns = {
"pkginfo_version": (re.compile(
fr'(^VERSION=")({PATTERN_VERSION})("$)', re.MULTILINE), fr'\g<1>{new_version}\g<3>'),
}
update_file(executor, pkginfo_file, patterns)
def update_version(current_version: str, current_stage: str, new_version: Optional[str] = None, new_stage: Optional[str] = None, new_date: Optional[str] = None) -> None:
"""Update version to a specific version.
Args:
current_version (str): Current version.
current_stage (str): Current stage.
new_version (str): New version.
new_stage (Optional[str]): New stage to set.
new_date (Optional[str]): New date to set.
"""
if new_version:
validate_version(new_version)
if new_stage:
validate_stage(new_stage)
if new_date:
validate_date(new_date)
executor = Executor()
# Create commands
# Update version files and references
update_file_version(executor, FILE_VERSION, new_version, new_stage)
update_file_sources(executor, new_version, new_stage)
# Add package entries
update_file_packages(executor, new_version or current_version,
new_stage or current_stage, new_date or datetime.now().strftime("%Y-%m-%d"))
# Execute commands
executor.execute(DRY_RUN)
def parse_args() -> Tuple[Optional[str], Optional[str], Optional[str], bool, bool]:
parser = argparse.ArgumentParser(
description='Bump version, stage and date for all packages')
parser.add_argument('--version', help='Update version')
parser.add_argument('--stage', help='Update stage')
parser.add_argument('--date', help='Update date')
parser.add_argument(
'--verbose', help='Verbose output', action='store_true')
parser.add_argument(
'--dry-run', help='Dry run', action='store_true')
args = parser.parse_args()
if not args.version and not args.stage and not args.date:
parser.error(
'No arguments provided. Use at least one of --version, --stage, or --date')
return args.version, args.stage, args.date, args.verbose, args.dry_run
if __name__ == "__main__":
new_version, new_stage, new_date, VERBOSE, DRY_RUN = parse_args()
print_v(debug_globals())
try:
current_version, current_stage = load_version(FILE_VERSION)
print_v(
f"Current version: {current_version}\nCurrent stage: {current_stage}\n")
print_v(
f"New version: {new_version}\nNew stage: {new_stage}\nNew date: {new_date}\n")
except Exception as e:
sys.exit(f"Error loading current {FILE_VERSION}: {e}")
try:
update_version(current_version, current_stage,
new_version, new_stage, new_date)
except Exception as e:
sys.exit(f"Error updating version: {e}")