Debian Codegraph @

scripts/prepare-release-pr.py

raw
1 # mypy: disallow-untyped-defs
2 """
3 This script is part of the pytest release process which is triggered manually in the Actions
4 tab of the repository.
5
6 The user will need to enter the base branch to start the release from (for example
7 ``6.1.x`` or ``main``) and if it should be a major release.
8
9 The appropriate version will be obtained based on the given branch automatically.
10
11 After that, it will create a release using the `release` tox environment, and push a new PR.
12
13 Note: the script uses the `gh` command-line tool, so `GH_TOKEN` must be set in the environment.
14 """
15
16 from __future__ import annotations
17
18 import argparse
19 from pathlib import Path
20 import re
21 from subprocess import check_call
22 from subprocess import check_output
23 from subprocess import run
24
25 from colorama import Fore
26 from colorama import init
27
28
29 class InvalidFeatureRelease(Exception):
30 pass
31
32
33 SLUG = "pytest-dev/pytest"
34
35 PR_BODY = """\
36 Created by the [prepare release pr]\
37 (https://github.com/pytest-dev/pytest/actions/workflows/prepare-release-pr.yml) workflow.
38
39 Once all builds pass and it has been **approved** by one or more maintainers, start the \
40 [deploy](https://github.com/pytest-dev/pytest/actions/workflows/deploy.yml) workflow, using these parameters:
41
42 * `Use workflow from`: `release-{version}`.
43 * `Release version`: `{version}`.
44
45 Or execute on the command line:
46
47 ```console
48 gh workflow run deploy.yml -r release-{version} -f version={version}
49 ```
50
51 After the workflow has been approved by a core maintainer, the package will be uploaded to PyPI automatically.
52 """
53
54
55 def prepare_release_pr(base_branch: str, is_major: bool, prerelease: str) -> None:
56 print()
57 print(f"Processing release for branch {Fore.CYAN}{base_branch}")
58
59 check_call(["git", "checkout", f"origin/{base_branch}"])
60
61 changelog = Path("changelog")
62
63 features = list(changelog.glob("*.feature.rst"))
64 breaking = list(changelog.glob("*.breaking.rst"))
65 is_feature_release = bool(features or breaking)
66
67 try:
68 version = find_next_version(
69 base_branch, is_major, is_feature_release, prerelease
70 )
71 except InvalidFeatureRelease as e:
72 print(f"{Fore.RED}{e}")
73 raise SystemExit(1) from None
74
75 print(f"Version: {Fore.CYAN}{version}")
76
77 release_branch = f"release-{version}"
78
79 run(
80 ["git", "config", "user.name", "pytest bot"],
81 check=True,
82 )
83 run(
84 ["git", "config", "user.email", "[email protected]"],
85 check=True,
86 )
87
88 run(
89 ["git", "checkout", "-b", release_branch, f"origin/{base_branch}"],
90 check=True,
91 )
92
93 print(f"Branch {Fore.CYAN}{release_branch}{Fore.RESET} created.")
94
95 if is_major:
96 template_name = "release.major.rst"
97 elif prerelease:
98 template_name = "release.pre.rst"
99 elif is_feature_release:
100 template_name = "release.minor.rst"
101 else:
102 template_name = "release.patch.rst"
103
104 # important to use tox here because we have changed branches, so dependencies
105 # might have changed as well
106 cmdline = [
107 "tox",
108 "-e",
109 "release",
110 "--",
111 version,
112 template_name,
113 release_branch, # doc_version
114 "--skip-check-links",
115 ]
116 print("Running", " ".join(cmdline))
117 run(
118 cmdline,
119 check=True,
120 )
121
122 run(
123 ["git", "push", "origin", f"HEAD:{release_branch}", "--force"],
124 check=True,
125 )
126 print(f"Branch {Fore.CYAN}{release_branch}{Fore.RESET} pushed.")
127
128 body = PR_BODY.format(version=version)
129 run(
130 [
131 "gh",
132 "pr",
133 "create",
134 f"--base={base_branch}",
135 f"--head={release_branch}",
136 f"--title=Release {version}",
137 f"--body={body}",
138 "--draft",
139 ],
140 check=True,
141 )
142
143
144 def find_next_version(
145 base_branch: str, is_major: bool, is_feature_release: bool, prerelease: str
146 ) -> str:
147 output = check_output(["git", "tag"], encoding="UTF-8")
148 valid_versions = []
149 for v in output.splitlines():
150 m = re.match(r"\d.\d.\d+$", v.strip())
151 if m:
152 valid_versions.append(tuple(int(x) for x in v.split(".")))
153
154 valid_versions.sort()
155 last_version = valid_versions[-1]
156
157 if is_major:
158 return f"{last_version[0] + 1}.0.0{prerelease}"
159 elif is_feature_release:
160 return f"{last_version[0]}.{last_version[1] + 1}.0{prerelease}"
161 else:
162 return f"{last_version[0]}.{last_version[1]}.{last_version[2] + 1}{prerelease}"
163
164
165 def main() -> None:
166 init(autoreset=True)
167 parser = argparse.ArgumentParser()
168 parser.add_argument("base_branch")
169 parser.add_argument("--major", action="store_true", default=False)
170 parser.add_argument("--prerelease", default="")
171 options = parser.parse_args()
172 prepare_release_pr(
173 base_branch=options.base_branch,
174 is_major=options.major,
175 prerelease=options.prerelease,
176 )
177
178
179 if __name__ == "__main__":
180 main()