release.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2020 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """An interactive script for doing a release. See `cli()` below.
  17. """
  18. import re
  19. import subprocess
  20. import sys
  21. import urllib.request
  22. from os import path
  23. from tempfile import TemporaryDirectory
  24. from typing import List, Optional, Tuple
  25. import attr
  26. import click
  27. import commonmark
  28. import git
  29. import redbaron
  30. from click.exceptions import ClickException
  31. from github import Github
  32. from packaging import version
  33. def run_until_successful(command, *args, **kwargs):
  34. while True:
  35. completed_process = subprocess.run(command, *args, **kwargs)
  36. exit_code = completed_process.returncode
  37. if exit_code == 0:
  38. # successful, so nothing more to do here.
  39. return completed_process
  40. print(f"The command {command!r} failed with exit code {exit_code}.")
  41. print("Please try to correct the failure and then re-run.")
  42. click.confirm("Try again?", abort=True)
  43. @click.group()
  44. def cli():
  45. """An interactive script to walk through the parts of creating a release.
  46. Requires the dev dependencies be installed, which can be done via:
  47. pip install -e .[dev]
  48. Then to use:
  49. ./scripts-dev/release.py prepare
  50. # ... ask others to look at the changelog ...
  51. ./scripts-dev/release.py tag
  52. # ... wait for asssets to build ...
  53. ./scripts-dev/release.py publish
  54. ./scripts-dev/release.py upload
  55. If the env var GH_TOKEN (or GITHUB_TOKEN) is set, or passed into the
  56. `tag`/`publish` command, then a new draft release will be created/published.
  57. """
  58. @cli.command()
  59. def prepare():
  60. """Do the initial stages of creating a release, including creating release
  61. branch, updating changelog and pushing to GitHub.
  62. """
  63. # Make sure we're in a git repo.
  64. try:
  65. repo = git.Repo()
  66. except git.InvalidGitRepositoryError:
  67. raise click.ClickException("Not in Synapse repo.")
  68. if repo.is_dirty():
  69. raise click.ClickException("Uncommitted changes exist.")
  70. click.secho("Updating git repo...")
  71. repo.remote().fetch()
  72. # Get the current version and AST from root Synapse module.
  73. current_version, parsed_synapse_ast, version_node = parse_version_from_module()
  74. # Figure out what sort of release we're doing and calcuate the new version.
  75. rc = click.confirm("RC", default=True)
  76. if current_version.pre:
  77. # If the current version is an RC we don't need to bump any of the
  78. # version numbers (other than the RC number).
  79. if rc:
  80. new_version = "{}.{}.{}rc{}".format(
  81. current_version.major,
  82. current_version.minor,
  83. current_version.micro,
  84. current_version.pre[1] + 1,
  85. )
  86. else:
  87. new_version = "{}.{}.{}".format(
  88. current_version.major,
  89. current_version.minor,
  90. current_version.micro,
  91. )
  92. else:
  93. # If this is a new release cycle then we need to know if it's a minor
  94. # or a patch version bump.
  95. release_type = click.prompt(
  96. "Release type",
  97. type=click.Choice(("minor", "patch")),
  98. show_choices=True,
  99. default="minor",
  100. )
  101. if release_type == "minor":
  102. if rc:
  103. new_version = "{}.{}.{}rc1".format(
  104. current_version.major,
  105. current_version.minor + 1,
  106. 0,
  107. )
  108. else:
  109. new_version = "{}.{}.{}".format(
  110. current_version.major,
  111. current_version.minor + 1,
  112. 0,
  113. )
  114. else:
  115. if rc:
  116. new_version = "{}.{}.{}rc1".format(
  117. current_version.major,
  118. current_version.minor,
  119. current_version.micro + 1,
  120. )
  121. else:
  122. new_version = "{}.{}.{}".format(
  123. current_version.major,
  124. current_version.minor,
  125. current_version.micro + 1,
  126. )
  127. # Confirm the calculated version is OK.
  128. if not click.confirm(f"Create new version: {new_version}?", default=True):
  129. click.get_current_context().abort()
  130. # Switch to the release branch.
  131. parsed_new_version = version.parse(new_version)
  132. # We assume for debian changelogs that we only do RCs or full releases.
  133. assert not parsed_new_version.is_devrelease
  134. assert not parsed_new_version.is_postrelease
  135. release_branch_name = (
  136. f"release-v{parsed_new_version.major}.{parsed_new_version.minor}"
  137. )
  138. release_branch = find_ref(repo, release_branch_name)
  139. if release_branch:
  140. if release_branch.is_remote():
  141. # If the release branch only exists on the remote we check it out
  142. # locally.
  143. repo.git.checkout(release_branch_name)
  144. release_branch = repo.active_branch
  145. else:
  146. # If a branch doesn't exist we create one. We ask which one branch it
  147. # should be based off, defaulting to sensible values depending on the
  148. # release type.
  149. if current_version.is_prerelease:
  150. default = release_branch_name
  151. elif release_type == "minor":
  152. default = "develop"
  153. else:
  154. default = "master"
  155. branch_name = click.prompt(
  156. "Which branch should the release be based on?", default=default
  157. )
  158. base_branch = find_ref(repo, branch_name)
  159. if not base_branch:
  160. print(f"Could not find base branch {branch_name}!")
  161. click.get_current_context().abort()
  162. # Check out the base branch and ensure it's up to date
  163. repo.head.reference = base_branch
  164. repo.head.reset(index=True, working_tree=True)
  165. if not base_branch.is_remote():
  166. update_branch(repo)
  167. # Create the new release branch
  168. release_branch = repo.create_head(release_branch_name, commit=base_branch)
  169. # Switch to the release branch and ensure its up to date.
  170. repo.git.checkout(release_branch_name)
  171. update_branch(repo)
  172. # Update the `__version__` variable and write it back to the file.
  173. version_node.value = '"' + new_version + '"'
  174. with open("synapse/__init__.py", "w") as f:
  175. f.write(parsed_synapse_ast.dumps())
  176. # Generate changelogs
  177. run_until_successful("python3 -m towncrier", shell=True)
  178. # Generate debian changelogs
  179. if parsed_new_version.pre is not None:
  180. # If this is an RC then we need to coerce the version string to match
  181. # Debian norms, e.g. 1.39.0rc2 gets converted to 1.39.0~rc2.
  182. base_ver = parsed_new_version.base_version
  183. pre_type, pre_num = parsed_new_version.pre
  184. debian_version = f"{base_ver}~{pre_type}{pre_num}"
  185. else:
  186. debian_version = new_version
  187. run_until_successful(
  188. f'dch -M -v {debian_version} "New synapse release {debian_version}."',
  189. shell=True,
  190. )
  191. run_until_successful('dch -M -r -D stable ""', shell=True)
  192. # Show the user the changes and ask if they want to edit the change log.
  193. repo.git.add("-u")
  194. subprocess.run("git diff --cached", shell=True)
  195. if click.confirm("Edit changelog?", default=False):
  196. click.edit(filename="CHANGES.md")
  197. # Commit the changes.
  198. repo.git.add("-u")
  199. repo.git.commit("-m", new_version)
  200. # We give the option to bail here in case the user wants to make sure things
  201. # are OK before pushing.
  202. if not click.confirm("Push branch to github?", default=True):
  203. print("")
  204. print("Run when ready to push:")
  205. print("")
  206. print(f"\tgit push -u {repo.remote().name} {repo.active_branch.name}")
  207. print("")
  208. sys.exit(0)
  209. # Otherwise, push and open the changelog in the browser.
  210. repo.git.push("-u", repo.remote().name, repo.active_branch.name)
  211. print("Opening the changelog in your browser...")
  212. print("Please ask others to give it a check.")
  213. click.launch(
  214. f"https://github.com/matrix-org/synapse/blob/{repo.active_branch.name}/CHANGES.md"
  215. )
  216. @cli.command()
  217. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"])
  218. def tag(gh_token: Optional[str]):
  219. """Tags the release and generates a draft GitHub release"""
  220. # Make sure we're in a git repo.
  221. try:
  222. repo = git.Repo()
  223. except git.InvalidGitRepositoryError:
  224. raise click.ClickException("Not in Synapse repo.")
  225. if repo.is_dirty():
  226. raise click.ClickException("Uncommitted changes exist.")
  227. click.secho("Updating git repo...")
  228. repo.remote().fetch()
  229. # Find out the version and tag name.
  230. current_version, _, _ = parse_version_from_module()
  231. tag_name = f"v{current_version}"
  232. # Check we haven't released this version.
  233. if tag_name in repo.tags:
  234. raise click.ClickException(f"Tag {tag_name} already exists!\n")
  235. # Get the appropriate changelogs and tag.
  236. changes = get_changes_for_version(current_version)
  237. click.echo_via_pager(changes)
  238. if click.confirm("Edit text?", default=False):
  239. changes = click.edit(changes, require_save=False)
  240. repo.create_tag(tag_name, message=changes, sign=True)
  241. if not click.confirm("Push tag to GitHub?", default=True):
  242. print("")
  243. print("Run when ready to push:")
  244. print("")
  245. print(f"\tgit push {repo.remote().name} tag {current_version}")
  246. print("")
  247. return
  248. repo.git.push(repo.remote().name, "tag", tag_name)
  249. # If no token was given, we bail here
  250. if not gh_token:
  251. print("Launching the GitHub release page in your browser.")
  252. print("Please correct the title and create a draft.")
  253. if current_version.is_prerelease:
  254. print("As this is an RC, remember to mark it as a pre-release!")
  255. print("(by the way, this step can be automated by passing --gh-token,")
  256. print("or one of the GH_TOKEN or GITHUB_TOKEN env vars.)")
  257. click.launch(f"https://github.com/matrix-org/synapse/releases/edit/{tag_name}")
  258. print("Once done, you need to wait for the release assets to build.")
  259. if click.confirm("Launch the release assets actions page?", default=True):
  260. click.launch(
  261. f"https://github.com/matrix-org/synapse/actions?query=branch%3A{tag_name}"
  262. )
  263. return
  264. # Create a new draft release
  265. gh = Github(gh_token)
  266. gh_repo = gh.get_repo("matrix-org/synapse")
  267. release = gh_repo.create_git_release(
  268. tag=tag_name,
  269. name=tag_name,
  270. message=changes,
  271. draft=True,
  272. prerelease=current_version.is_prerelease,
  273. )
  274. # Open the release and the actions where we are building the assets.
  275. print("Launching the release page and the actions page.")
  276. click.launch(release.html_url)
  277. click.launch(
  278. f"https://github.com/matrix-org/synapse/actions?query=branch%3A{tag_name}"
  279. )
  280. click.echo("Wait for release assets to be built")
  281. @cli.command()
  282. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"], required=True)
  283. def publish(gh_token: str):
  284. """Publish release."""
  285. # Make sure we're in a git repo.
  286. try:
  287. repo = git.Repo()
  288. except git.InvalidGitRepositoryError:
  289. raise click.ClickException("Not in Synapse repo.")
  290. if repo.is_dirty():
  291. raise click.ClickException("Uncommitted changes exist.")
  292. current_version, _, _ = parse_version_from_module()
  293. tag_name = f"v{current_version}"
  294. if not click.confirm(f"Publish {tag_name}?", default=True):
  295. return
  296. # Publish the draft release
  297. gh = Github(gh_token)
  298. gh_repo = gh.get_repo("matrix-org/synapse")
  299. for release in gh_repo.get_releases():
  300. if release.title == tag_name:
  301. break
  302. else:
  303. raise ClickException(f"Failed to find GitHub release for {tag_name}")
  304. assert release.title == tag_name
  305. if not release.draft:
  306. click.echo("Release already published.")
  307. return
  308. release = release.update_release(
  309. name=release.title,
  310. message=release.body,
  311. tag_name=release.tag_name,
  312. prerelease=release.prerelease,
  313. draft=False,
  314. )
  315. @cli.command()
  316. def upload():
  317. """Upload release to pypi."""
  318. current_version, _, _ = parse_version_from_module()
  319. tag_name = f"v{current_version}"
  320. pypi_asset_names = [
  321. f"matrix_synapse-{current_version}-py3-none-any.whl",
  322. f"matrix-synapse-{current_version}.tar.gz",
  323. ]
  324. with TemporaryDirectory(prefix=f"synapse_upload_{tag_name}_") as tmpdir:
  325. for name in pypi_asset_names:
  326. filename = path.join(tmpdir, name)
  327. url = f"https://github.com/matrix-org/synapse/releases/download/{tag_name}/{name}"
  328. click.echo(f"Downloading {name} into {filename}")
  329. urllib.request.urlretrieve(url, filename=filename)
  330. if click.confirm("Upload to PyPI?", default=True):
  331. subprocess.run("twine upload *", shell=True, cwd=tmpdir)
  332. click.echo(
  333. f"Done! Remember to merge the tag {tag_name} into the appropriate branches"
  334. )
  335. def parse_version_from_module() -> Tuple[
  336. version.Version, redbaron.RedBaron, redbaron.Node
  337. ]:
  338. # Parse the AST and load the `__version__` node so that we can edit it
  339. # later.
  340. with open("synapse/__init__.py") as f:
  341. red = redbaron.RedBaron(f.read())
  342. version_node = None
  343. for node in red:
  344. if node.type != "assignment":
  345. continue
  346. if node.target.type != "name":
  347. continue
  348. if node.target.value != "__version__":
  349. continue
  350. version_node = node
  351. break
  352. if not version_node:
  353. print("Failed to find '__version__' definition in synapse/__init__.py")
  354. sys.exit(1)
  355. # Parse the current version.
  356. current_version = version.parse(version_node.value.value.strip('"'))
  357. assert isinstance(current_version, version.Version)
  358. return current_version, red, version_node
  359. def find_ref(repo: git.Repo, ref_name: str) -> Optional[git.HEAD]:
  360. """Find the branch/ref, looking first locally then in the remote."""
  361. if ref_name in repo.refs:
  362. return repo.refs[ref_name]
  363. elif ref_name in repo.remote().refs:
  364. return repo.remote().refs[ref_name]
  365. else:
  366. return None
  367. def update_branch(repo: git.Repo):
  368. """Ensure branch is up to date if it has a remote"""
  369. if repo.active_branch.tracking_branch():
  370. repo.git.merge(repo.active_branch.tracking_branch().name)
  371. def get_changes_for_version(wanted_version: version.Version) -> str:
  372. """Get the changelogs for the given version.
  373. If an RC then will only get the changelog for that RC version, otherwise if
  374. its a full release will get the changelog for the release and all its RCs.
  375. """
  376. with open("CHANGES.md") as f:
  377. changes = f.read()
  378. # First we parse the changelog so that we can split it into sections based
  379. # on the release headings.
  380. ast = commonmark.Parser().parse(changes)
  381. @attr.s(auto_attribs=True)
  382. class VersionSection:
  383. title: str
  384. # These are 0-based.
  385. start_line: int
  386. end_line: Optional[int] = None # Is none if its the last entry
  387. headings: List[VersionSection] = []
  388. for node, _ in ast.walker():
  389. # We look for all text nodes that are in a level 1 heading.
  390. if node.t != "text":
  391. continue
  392. if node.parent.t != "heading" or node.parent.level != 1:
  393. continue
  394. # If we have a previous heading then we update its `end_line`.
  395. if headings:
  396. headings[-1].end_line = node.parent.sourcepos[0][0] - 1
  397. headings.append(VersionSection(node.literal, node.parent.sourcepos[0][0] - 1))
  398. changes_by_line = changes.split("\n")
  399. version_changelog = [] # The lines we want to include in the changelog
  400. # Go through each section and find any that match the requested version.
  401. regex = re.compile(r"^Synapse v?(\S+)")
  402. for section in headings:
  403. groups = regex.match(section.title)
  404. if not groups:
  405. continue
  406. heading_version = version.parse(groups.group(1))
  407. heading_base_version = version.parse(heading_version.base_version)
  408. # Check if heading version matches the requested version, or if its an
  409. # RC of the requested version.
  410. if wanted_version not in (heading_version, heading_base_version):
  411. continue
  412. version_changelog.extend(changes_by_line[section.start_line : section.end_line])
  413. return "\n".join(version_changelog)
  414. if __name__ == "__main__":
  415. cli()