-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbump_patch_version.py
More file actions
302 lines (242 loc) · 11.2 KB
/
Copy pathbump_patch_version.py
File metadata and controls
302 lines (242 loc) · 11.2 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
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
#!/usr/bin/env python3
"""
Bump the patch version component across both Android (build.gradle.kts) and
iOS (project.pbxproj) source files, bump Android ``versionCode`` by one for the
next Play upload, then write the Android changelog for that new code (so the
previous release's changelog file is never overwritten).
Example: 1.3.19 → 1.3.20
Usage
-----
python scripts/bump_patch_version.py [--dry-run] [--changelog-message "..."]
The script exits non-zero if versions are out of sync between platforms so the
pipeline can catch accidental drift early.
"""
from __future__ import annotations
import argparse
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
REPO_ROOT = Path(__file__).resolve().parents[1]
ANDROID_GRADLE = REPO_ROOT / "native-android" / "app" / "build.gradle.kts"
IOS_PBXPROJ = REPO_ROOT / "native-ios" / "RandomTimer.xcodeproj" / "project.pbxproj"
ANDROID_CHANGELOG_DIR = (
REPO_ROOT / "native-android" / "fastlane" / "metadata" / "android" / "en-US" / "changelogs"
)
IOS_RELEASE_NOTES = (
REPO_ROOT / "native-ios" / "fastlane" / "metadata" / "en-US" / "release_notes.txt"
)
# ---------------------------------------------------------------------------
# Version parsing
# ---------------------------------------------------------------------------
def _parse_semver(version_str: str) -> tuple[int, int, int]:
m = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", version_str.strip())
if not m:
raise ValueError(f"Not a semver string: {version_str!r}")
return int(m.group(1)), int(m.group(2)), int(m.group(3))
def _bump_patch(major: int, minor: int, patch: int) -> tuple[int, int, int]:
return major, minor, patch + 1
def _semver_str(major: int, minor: int, patch: int) -> str:
return f"{major}.{minor}.{patch}"
# ---------------------------------------------------------------------------
# Android helpers
# ---------------------------------------------------------------------------
def read_android_version(gradle_text: str) -> str:
"""Return the versionName string from build.gradle.kts content."""
for line in gradle_text.splitlines():
if "versionName" in line and "=" in line:
rhs = line.split("=", 1)[1]
candidate = rhs.strip().strip('"')
if re.fullmatch(r"\d+\.\d+\.\d+", candidate):
return candidate
raise ValueError("Could not parse versionName from build.gradle.kts")
def read_android_version_code(gradle_text: str) -> int:
"""Return the concrete fallback versionCode from build.gradle.kts content."""
for line in gradle_text.splitlines():
if "versionCode" not in line or "=" not in line:
continue
rhs = line.split("=", 1)[1].split("//", 1)[0].strip()
if "?:" in rhs:
rhs = rhs.rsplit("?:", 1)[1].strip()
if rhs.isdigit():
return int(rhs)
raise ValueError("Could not parse versionCode from build.gradle.kts")
def write_android_version(gradle_text: str, new_version: str) -> str:
"""Return gradle_text with versionName updated to new_version."""
pattern = re.compile(r'(versionName\s*=\s*")\d+\.\d+\.\d+(")')
replacement = rf'\g<1>{new_version}\g<2>'
new_text, n = pattern.subn(replacement, gradle_text)
if n == 0:
raise ValueError("Could not update versionName in build.gradle.kts")
return new_text
def write_android_version_code(gradle_text: str, new_code: int) -> str:
"""Return gradle_text with defaultConfig versionCode literal updated to new_code.
Supports ``versionCode = ciVersionCode ?: N`` and plain ``versionCode = N``.
Uses line-wise parsing (no nested-quantifier regex) for predictable Gradle layout.
"""
out_lines: list[str] = []
updated = 0
for line in gradle_text.splitlines(keepends=True):
without_nl = line.rstrip("\n\r")
nl_suffix = line[len(without_nl) :]
stripped = without_nl.lstrip()
if not stripped.startswith("versionCode") or stripped.startswith("//"):
out_lines.append(line)
continue
rhs = without_nl.split("=", 1)[1].split("//", 1)[0].strip()
if "?:" in rhs:
needle = "?: "
pos = without_nl.find(needle)
if pos != -1:
num_start = pos + len(needle)
tail = without_nl[num_start:]
if tail.isdigit():
out_lines.append(without_nl[:num_start] + str(new_code) + nl_suffix)
updated += 1
continue
else:
m = re.match(r"^(\s*versionCode\s*=\s*)(\d+)(.*)$", without_nl)
if m:
out_lines.append(m.group(1) + str(new_code) + m.group(3) + nl_suffix)
updated += 1
continue
out_lines.append(line)
if updated != 1:
raise ValueError(
"Could not update versionCode in build.gradle.kts (expected exactly one defaultConfig line)"
)
return "".join(out_lines)
# ---------------------------------------------------------------------------
# iOS helpers
# ---------------------------------------------------------------------------
def read_ios_version(pbxproj_text: str) -> str:
"""Return the MARKETING_VERSION string from project.pbxproj content."""
for line in pbxproj_text.splitlines():
if "MARKETING_VERSION" in line and "=" in line:
rhs = line.split("=", 1)[1]
candidate = rhs.strip().rstrip(";").strip()
if re.fullmatch(r"\d+\.\d+\.\d+", candidate):
return candidate
raise ValueError("Could not parse MARKETING_VERSION from project.pbxproj")
def write_ios_version(pbxproj_text: str, new_version: str) -> str:
"""Return pbxproj_text with all MARKETING_VERSION entries updated."""
pattern = re.compile(r"(MARKETING_VERSION\s*=\s*)\d+\.\d+\.\d+(;)")
replacement = rf"\g<1>{new_version}\g<2>"
new_text, n = pattern.subn(replacement, pbxproj_text)
if n == 0:
raise ValueError("Could not update MARKETING_VERSION in project.pbxproj")
print(f" Updated {n} MARKETING_VERSION occurrence(s) in project.pbxproj")
return new_text
# ---------------------------------------------------------------------------
# Changelog helpers
# ---------------------------------------------------------------------------
def _build_changelog_message(base_message: str | None) -> str:
if base_message:
return base_message
month_year = datetime.now(tz=timezone.utc).strftime("%B %Y")
return f"Monthly Pro content update — {month_year}"
def update_android_changelog(version_code: int, message: str, dry_run: bool) -> Path:
"""Write a new Android changelog file for the given versionCode."""
ANDROID_CHANGELOG_DIR.mkdir(parents=True, exist_ok=True)
changelog_root = ANDROID_CHANGELOG_DIR.resolve()
dest = changelog_root / f"{int(version_code)}.txt"
if dry_run:
print(f" [dry-run] Would write Android changelog: {dest.relative_to(REPO_ROOT)}")
else:
dest.write_text(message + "\n", encoding="utf-8") # NOSONAR
print(f" ✅ Wrote Android changelog: {dest.relative_to(REPO_ROOT)}")
return dest
def update_ios_release_notes(message: str, dry_run: bool) -> Path:
"""Overwrite the iOS release_notes.txt with the changelog message."""
IOS_RELEASE_NOTES.parent.mkdir(parents=True, exist_ok=True)
release_notes_path = IOS_RELEASE_NOTES.resolve()
if dry_run:
print(f" [dry-run] Would write iOS release notes: {IOS_RELEASE_NOTES.relative_to(REPO_ROOT)}")
else:
release_notes_path.write_text(message + "\n", encoding="utf-8") # NOSONAR
print(f" ✅ Wrote iOS release notes: {IOS_RELEASE_NOTES.relative_to(REPO_ROOT)}")
return release_notes_path
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def bump(
dry_run: bool = False,
changelog_message: str | None = None,
skip_changelog: bool = False,
) -> str:
"""Perform the version bump. Returns the new version string."""
# Read current versions (strict resolved paths — repo constants, not user input)
gradle_path = ANDROID_GRADLE.resolve(strict=True)
pbxproj_path = IOS_PBXPROJ.resolve(strict=True)
gradle_text = gradle_path.read_text(encoding="utf-8")
pbxproj_text = pbxproj_path.read_text(encoding="utf-8")
android_ver = read_android_version(gradle_text)
android_version_code = read_android_version_code(gradle_text)
ios_ver = read_ios_version(pbxproj_text)
print(f"Current Android version : {android_ver}")
print(f"Current iOS version : {ios_ver}")
if android_ver != ios_ver:
print(
f"❌ Version mismatch: Android={android_ver}, iOS={ios_ver}. "
"Resolve drift before bumping.",
file=sys.stderr,
)
sys.exit(1)
major, minor, patch = _parse_semver(android_ver)
new_major, new_minor, new_patch = _bump_patch(major, minor, patch)
new_version = _semver_str(new_major, new_minor, new_patch)
next_version_code = android_version_code + 1
print(f"Bumping {android_ver} → {new_version}")
print(f"Android versionCode {android_version_code} → {next_version_code} (Play changelog filename)")
if dry_run:
print("[dry-run] No files written.")
else:
# Write Android (semver + monotonic versionCode for the new upload)
new_gradle = write_android_version(gradle_text, new_version)
new_gradle = write_android_version_code(new_gradle, next_version_code)
gradle_path.write_text(new_gradle, encoding="utf-8") # NOSONAR
print(f" ✅ Updated {ANDROID_GRADLE.relative_to(REPO_ROOT)}")
# Write iOS
new_pbxproj = write_ios_version(pbxproj_text, new_version)
pbxproj_path.write_text(new_pbxproj, encoding="utf-8") # NOSONAR
if skip_changelog:
print(" Skipped store changelog updates.")
else:
message = _build_changelog_message(changelog_message)
update_android_changelog(next_version_code, message, dry_run)
update_ios_release_notes(message, dry_run)
return new_version
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Bump patch version in Android + iOS source and update changelogs."
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Print planned changes without writing any files.",
)
parser.add_argument(
"--changelog-message",
default=None,
help='Override the default "Monthly Pro content update — Month YYYY" message.',
)
parser.add_argument(
"--skip-changelog",
action="store_true",
help="Only bump source versions; do not modify store release notes.",
)
return parser.parse_args()
def main() -> int:
args = _parse_args()
new_version = bump(
dry_run=args.dry_run,
changelog_message=args.changelog_message,
skip_changelog=args.skip_changelog,
)
print(f"\nNew version: {new_version}")
return 0
if __name__ == "__main__":
raise SystemExit(main())