release.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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 glob
  19. import os
  20. import re
  21. import subprocess
  22. import sys
  23. import urllib.request
  24. from os import path
  25. from tempfile import TemporaryDirectory
  26. from typing import Any, List, Optional, cast
  27. import attr
  28. import click
  29. import commonmark
  30. import git
  31. from click.exceptions import ClickException
  32. from github import Github
  33. from packaging import version
  34. def run_until_successful(
  35. command: str, *args: Any, **kwargs: Any
  36. ) -> subprocess.CompletedProcess:
  37. while True:
  38. completed_process = subprocess.run(command, *args, **kwargs)
  39. exit_code = completed_process.returncode
  40. if exit_code == 0:
  41. # successful, so nothing more to do here.
  42. return completed_process
  43. print(f"The command {command!r} failed with exit code {exit_code}.")
  44. print("Please try to correct the failure and then re-run.")
  45. click.confirm("Try again?", abort=True)
  46. @click.group()
  47. def cli() -> None:
  48. """An interactive script to walk through the parts of creating a release.
  49. Requirements:
  50. - The dev dependencies be installed, which can be done via:
  51. pip install -e .[dev]
  52. - A checkout of the sytest repository at ../sytest
  53. Then to use:
  54. ./scripts-dev/release.py prepare
  55. # ... ask others to look at the changelog ...
  56. ./scripts-dev/release.py tag
  57. # ... wait for assets to build ...
  58. ./scripts-dev/release.py publish
  59. ./scripts-dev/release.py upload
  60. # Optional: generate some nice links for the announcement
  61. ./scripts-dev/release.py announce
  62. If the env var GH_TOKEN (or GITHUB_TOKEN) is set, or passed into the
  63. `tag`/`publish` command, then a new draft release will be created/published.
  64. """
  65. @cli.command()
  66. def prepare() -> None:
  67. """Do the initial stages of creating a release, including creating release
  68. branch, updating changelog and pushing to GitHub.
  69. """
  70. # Make sure we're in a git repo.
  71. synapse_repo = get_repo_and_check_clean_checkout()
  72. sytest_repo = get_repo_and_check_clean_checkout("../sytest", "sytest")
  73. click.secho("Updating Synapse and Sytest git repos...")
  74. synapse_repo.remote().fetch()
  75. sytest_repo.remote().fetch()
  76. # Get the current version and AST from root Synapse module.
  77. current_version = get_package_version()
  78. # Figure out what sort of release we're doing and calcuate the new version.
  79. rc = click.confirm("RC", default=True)
  80. if current_version.pre:
  81. # If the current version is an RC we don't need to bump any of the
  82. # version numbers (other than the RC number).
  83. if rc:
  84. new_version = "{}.{}.{}rc{}".format(
  85. current_version.major,
  86. current_version.minor,
  87. current_version.micro,
  88. current_version.pre[1] + 1,
  89. )
  90. else:
  91. new_version = "{}.{}.{}".format(
  92. current_version.major,
  93. current_version.minor,
  94. current_version.micro,
  95. )
  96. else:
  97. # If this is a new release cycle then we need to know if it's a minor
  98. # or a patch version bump.
  99. release_type = click.prompt(
  100. "Release type",
  101. type=click.Choice(("minor", "patch")),
  102. show_choices=True,
  103. default="minor",
  104. )
  105. if release_type == "minor":
  106. if rc:
  107. new_version = "{}.{}.{}rc1".format(
  108. current_version.major,
  109. current_version.minor + 1,
  110. 0,
  111. )
  112. else:
  113. new_version = "{}.{}.{}".format(
  114. current_version.major,
  115. current_version.minor + 1,
  116. 0,
  117. )
  118. else:
  119. if rc:
  120. new_version = "{}.{}.{}rc1".format(
  121. current_version.major,
  122. current_version.minor,
  123. current_version.micro + 1,
  124. )
  125. else:
  126. new_version = "{}.{}.{}".format(
  127. current_version.major,
  128. current_version.minor,
  129. current_version.micro + 1,
  130. )
  131. # Confirm the calculated version is OK.
  132. if not click.confirm(f"Create new version: {new_version}?", default=True):
  133. click.get_current_context().abort()
  134. # Switch to the release branch.
  135. # Cast safety: parse() won't return a version.LegacyVersion from our
  136. # version string format.
  137. parsed_new_version = cast(version.Version, version.parse(new_version))
  138. # We assume for debian changelogs that we only do RCs or full releases.
  139. assert not parsed_new_version.is_devrelease
  140. assert not parsed_new_version.is_postrelease
  141. release_branch_name = get_release_branch_name(parsed_new_version)
  142. release_branch = find_ref(synapse_repo, release_branch_name)
  143. if release_branch:
  144. if release_branch.is_remote():
  145. # If the release branch only exists on the remote we check it out
  146. # locally.
  147. synapse_repo.git.checkout(release_branch_name)
  148. else:
  149. # If a branch doesn't exist we create one. We ask which one branch it
  150. # should be based off, defaulting to sensible values depending on the
  151. # release type.
  152. if current_version.is_prerelease:
  153. default = release_branch_name
  154. elif release_type == "minor":
  155. default = "develop"
  156. else:
  157. default = "master"
  158. branch_name = click.prompt(
  159. "Which branch should the release be based on?", default=default
  160. )
  161. for repo_name, repo in {"synapse": synapse_repo, "sytest": sytest_repo}.items():
  162. base_branch = find_ref(repo, branch_name)
  163. if not base_branch:
  164. print(f"Could not find base branch {branch_name} for {repo_name}!")
  165. click.get_current_context().abort()
  166. # Check out the base branch and ensure it's up to date
  167. repo.head.set_reference(
  168. base_branch, f"check out the base branch for {repo_name}"
  169. )
  170. repo.head.reset(index=True, working_tree=True)
  171. if not base_branch.is_remote():
  172. update_branch(repo)
  173. # Create the new release branch
  174. # Type ignore will no longer be needed after GitPython 3.1.28.
  175. # See https://github.com/gitpython-developers/GitPython/pull/1419
  176. repo.create_head(release_branch_name, commit=base_branch) # type: ignore[arg-type]
  177. # Special-case SyTest: we don't actually prepare any files so we may
  178. # as well push it now (and only when we create a release branch;
  179. # not on subsequent RCs or full releases).
  180. if click.confirm("Push new SyTest branch?", default=True):
  181. sytest_repo.git.push("-u", sytest_repo.remote().name, release_branch_name)
  182. # Switch to the release branch and ensure it's up to date.
  183. synapse_repo.git.checkout(release_branch_name)
  184. update_branch(synapse_repo)
  185. # Update the version specified in pyproject.toml.
  186. subprocess.check_output(["poetry", "version", new_version])
  187. # Generate changelogs.
  188. generate_and_write_changelog(current_version, new_version)
  189. # Generate debian changelogs
  190. if parsed_new_version.pre is not None:
  191. # If this is an RC then we need to coerce the version string to match
  192. # Debian norms, e.g. 1.39.0rc2 gets converted to 1.39.0~rc2.
  193. base_ver = parsed_new_version.base_version
  194. pre_type, pre_num = parsed_new_version.pre
  195. debian_version = f"{base_ver}~{pre_type}{pre_num}"
  196. else:
  197. debian_version = new_version
  198. run_until_successful(
  199. f'dch -M -v {debian_version} "New Synapse release {new_version}."',
  200. shell=True,
  201. )
  202. run_until_successful('dch -M -r -D stable ""', shell=True)
  203. # Show the user the changes and ask if they want to edit the change log.
  204. synapse_repo.git.add("-u")
  205. subprocess.run("git diff --cached", shell=True)
  206. if click.confirm("Edit changelog?", default=False):
  207. click.edit(filename="CHANGES.md")
  208. # Commit the changes.
  209. synapse_repo.git.add("-u")
  210. synapse_repo.git.commit("-m", new_version)
  211. # We give the option to bail here in case the user wants to make sure things
  212. # are OK before pushing.
  213. if not click.confirm("Push branch to github?", default=True):
  214. print("")
  215. print("Run when ready to push:")
  216. print("")
  217. print(
  218. f"\tgit push -u {synapse_repo.remote().name} {synapse_repo.active_branch.name}"
  219. )
  220. print("")
  221. sys.exit(0)
  222. # Otherwise, push and open the changelog in the browser.
  223. synapse_repo.git.push(
  224. "-u", synapse_repo.remote().name, synapse_repo.active_branch.name
  225. )
  226. print("Opening the changelog in your browser...")
  227. print("Please ask others to give it a check.")
  228. click.launch(
  229. f"https://github.com/matrix-org/synapse/blob/{synapse_repo.active_branch.name}/CHANGES.md"
  230. )
  231. @cli.command()
  232. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"])
  233. def tag(gh_token: Optional[str]) -> None:
  234. """Tags the release and generates a draft GitHub release"""
  235. # Make sure we're in a git repo.
  236. repo = get_repo_and_check_clean_checkout()
  237. click.secho("Updating git repo...")
  238. repo.remote().fetch()
  239. # Find out the version and tag name.
  240. current_version = get_package_version()
  241. tag_name = f"v{current_version}"
  242. # Check we haven't released this version.
  243. if tag_name in repo.tags:
  244. raise click.ClickException(f"Tag {tag_name} already exists!\n")
  245. # Check we're on the right release branch
  246. release_branch = get_release_branch_name(current_version)
  247. if repo.active_branch.name != release_branch:
  248. click.echo(
  249. f"Need to be on the release branch ({release_branch}) before tagging. "
  250. f"Currently on ({repo.active_branch.name})."
  251. )
  252. click.get_current_context().abort()
  253. # Get the appropriate changelogs and tag.
  254. changes = get_changes_for_version(current_version)
  255. click.echo_via_pager(changes)
  256. if click.confirm("Edit text?", default=False):
  257. edited_changes = click.edit(changes, require_save=False)
  258. # This assert is for mypy's benefit. click's docs are a little unclear, but
  259. # when `require_save=False`, not saving the temp file in the editor returns
  260. # the original string.
  261. assert edited_changes is not None
  262. changes = edited_changes
  263. repo.create_tag(tag_name, message=changes, sign=True)
  264. if not click.confirm("Push tag to GitHub?", default=True):
  265. print("")
  266. print("Run when ready to push:")
  267. print("")
  268. print(f"\tgit push {repo.remote().name} tag {current_version}")
  269. print("")
  270. return
  271. repo.git.push(repo.remote().name, "tag", tag_name)
  272. # If no token was given, we bail here
  273. if not gh_token:
  274. print("Launching the GitHub release page in your browser.")
  275. print("Please correct the title and create a draft.")
  276. if current_version.is_prerelease:
  277. print("As this is an RC, remember to mark it as a pre-release!")
  278. print("(by the way, this step can be automated by passing --gh-token,")
  279. print("or one of the GH_TOKEN or GITHUB_TOKEN env vars.)")
  280. click.launch(f"https://github.com/matrix-org/synapse/releases/edit/{tag_name}")
  281. print("Once done, you need to wait for the release assets to build.")
  282. if click.confirm("Launch the release assets actions page?", default=True):
  283. click.launch(
  284. f"https://github.com/matrix-org/synapse/actions?query=branch%3A{tag_name}"
  285. )
  286. return
  287. # Create a new draft release
  288. gh = Github(gh_token)
  289. gh_repo = gh.get_repo("matrix-org/synapse")
  290. release = gh_repo.create_git_release(
  291. tag=tag_name,
  292. name=tag_name,
  293. message=changes,
  294. draft=True,
  295. prerelease=current_version.is_prerelease,
  296. )
  297. # Open the release and the actions where we are building the assets.
  298. print("Launching the release page and the actions page.")
  299. click.launch(release.html_url)
  300. click.launch(
  301. f"https://github.com/matrix-org/synapse/actions?query=branch%3A{tag_name}"
  302. )
  303. click.echo("Wait for release assets to be built")
  304. @cli.command()
  305. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"], required=True)
  306. def publish(gh_token: str) -> None:
  307. """Publish release on GitHub."""
  308. # Make sure we're in a git repo.
  309. get_repo_and_check_clean_checkout()
  310. current_version = get_package_version()
  311. tag_name = f"v{current_version}"
  312. if not click.confirm(f"Publish release {tag_name} on GitHub?", default=True):
  313. return
  314. # Publish the draft release
  315. gh = Github(gh_token)
  316. gh_repo = gh.get_repo("matrix-org/synapse")
  317. for release in gh_repo.get_releases():
  318. if release.title == tag_name:
  319. break
  320. else:
  321. raise ClickException(f"Failed to find GitHub release for {tag_name}")
  322. assert release.title == tag_name
  323. if not release.draft:
  324. click.echo("Release already published.")
  325. return
  326. release = release.update_release(
  327. name=release.title,
  328. message=release.body,
  329. tag_name=release.tag_name,
  330. prerelease=release.prerelease,
  331. draft=False,
  332. )
  333. @cli.command()
  334. def upload() -> None:
  335. """Upload release to pypi."""
  336. current_version = get_package_version()
  337. tag_name = f"v{current_version}"
  338. # Check we have the right tag checked out.
  339. repo = get_repo_and_check_clean_checkout()
  340. tag = repo.tag(f"refs/tags/{tag_name}")
  341. if repo.head.commit != tag.commit:
  342. click.echo("Tag {tag_name} (tag.commit) is not currently checked out!")
  343. click.get_current_context().abort()
  344. pypi_asset_names = [
  345. f"matrix_synapse-{current_version}-py3-none-any.whl",
  346. f"matrix-synapse-{current_version}.tar.gz",
  347. ]
  348. with TemporaryDirectory(prefix=f"synapse_upload_{tag_name}_") as tmpdir:
  349. for name in pypi_asset_names:
  350. filename = path.join(tmpdir, name)
  351. url = f"https://github.com/matrix-org/synapse/releases/download/{tag_name}/{name}"
  352. click.echo(f"Downloading {name} into {filename}")
  353. urllib.request.urlretrieve(url, filename=filename)
  354. if click.confirm("Upload to PyPI?", default=True):
  355. subprocess.run("twine upload *", shell=True, cwd=tmpdir)
  356. click.echo(
  357. f"Done! Remember to merge the tag {tag_name} into the appropriate branches"
  358. )
  359. @cli.command()
  360. def announce() -> None:
  361. """Generate markdown to announce the release."""
  362. current_version = get_package_version()
  363. tag_name = f"v{current_version}"
  364. click.echo(
  365. f"""
  366. Hi everyone. Synapse {current_version} has just been released.
  367. [notes](https://github.com/matrix-org/synapse/releases/tag/{tag_name}) | \
  368. [docker](https://hub.docker.com/r/matrixdotorg/synapse/tags?name={tag_name}) | \
  369. [debs](https://packages.matrix.org/debian/) | \
  370. [pypi](https://pypi.org/project/matrix-synapse/{current_version}/)"""
  371. )
  372. if "rc" in tag_name:
  373. click.echo(
  374. """
  375. Announce the RC in
  376. - #homeowners:matrix.org (Synapse Announcements)
  377. - #synapse-dev:matrix.org"""
  378. )
  379. else:
  380. click.echo(
  381. """
  382. Announce the release in
  383. - #homeowners:matrix.org (Synapse Announcements), bumping the version in the topic
  384. - #synapse:matrix.org (Synapse Admins), bumping the version in the topic
  385. - #synapse-dev:matrix.org
  386. - #synapse-package-maintainers:matrix.org"""
  387. )
  388. def get_package_version() -> version.Version:
  389. version_string = subprocess.check_output(["poetry", "version", "--short"]).decode(
  390. "utf-8"
  391. )
  392. return version.Version(version_string)
  393. def get_release_branch_name(version_number: version.Version) -> str:
  394. return f"release-v{version_number.major}.{version_number.minor}"
  395. def get_repo_and_check_clean_checkout(
  396. path: str = ".", name: str = "synapse"
  397. ) -> git.Repo:
  398. """Get the project repo and check it's not got any uncommitted changes."""
  399. try:
  400. repo = git.Repo(path=path)
  401. except git.InvalidGitRepositoryError:
  402. raise click.ClickException(
  403. f"{path} is not a git repository (expecting a {name} repository)."
  404. )
  405. if repo.is_dirty():
  406. raise click.ClickException(f"Uncommitted changes exist in {path}.")
  407. return repo
  408. def find_ref(repo: git.Repo, ref_name: str) -> Optional[git.HEAD]:
  409. """Find the branch/ref, looking first locally then in the remote."""
  410. if ref_name in repo.references:
  411. return repo.references[ref_name]
  412. elif ref_name in repo.remote().refs:
  413. return repo.remote().refs[ref_name]
  414. else:
  415. return None
  416. def update_branch(repo: git.Repo) -> None:
  417. """Ensure branch is up to date if it has a remote"""
  418. tracking_branch = repo.active_branch.tracking_branch()
  419. if tracking_branch:
  420. repo.git.merge(tracking_branch.name)
  421. def get_changes_for_version(wanted_version: version.Version) -> str:
  422. """Get the changelogs for the given version.
  423. If an RC then will only get the changelog for that RC version, otherwise if
  424. its a full release will get the changelog for the release and all its RCs.
  425. """
  426. with open("CHANGES.md") as f:
  427. changes = f.read()
  428. # First we parse the changelog so that we can split it into sections based
  429. # on the release headings.
  430. ast = commonmark.Parser().parse(changes)
  431. @attr.s(auto_attribs=True)
  432. class VersionSection:
  433. title: str
  434. # These are 0-based.
  435. start_line: int
  436. end_line: Optional[int] = None # Is none if its the last entry
  437. headings: List[VersionSection] = []
  438. for node, _ in ast.walker():
  439. # We look for all text nodes that are in a level 1 heading.
  440. if node.t != "text":
  441. continue
  442. if node.parent.t != "heading" or node.parent.level != 1:
  443. continue
  444. # If we have a previous heading then we update its `end_line`.
  445. if headings:
  446. headings[-1].end_line = node.parent.sourcepos[0][0] - 1
  447. headings.append(VersionSection(node.literal, node.parent.sourcepos[0][0] - 1))
  448. changes_by_line = changes.split("\n")
  449. version_changelog = [] # The lines we want to include in the changelog
  450. # Go through each section and find any that match the requested version.
  451. regex = re.compile(r"^Synapse v?(\S+)")
  452. for section in headings:
  453. groups = regex.match(section.title)
  454. if not groups:
  455. continue
  456. heading_version = version.parse(groups.group(1))
  457. heading_base_version = version.parse(heading_version.base_version)
  458. # Check if heading version matches the requested version, or if its an
  459. # RC of the requested version.
  460. if wanted_version not in (heading_version, heading_base_version):
  461. continue
  462. version_changelog.extend(changes_by_line[section.start_line : section.end_line])
  463. return "\n".join(version_changelog)
  464. def generate_and_write_changelog(
  465. current_version: version.Version, new_version: str
  466. ) -> None:
  467. # We do this by getting a draft so that we can edit it before writing to the
  468. # changelog.
  469. result = run_until_successful(
  470. f"python3 -m towncrier build --draft --version {new_version}",
  471. shell=True,
  472. capture_output=True,
  473. )
  474. new_changes = result.stdout.decode("utf-8")
  475. new_changes = new_changes.replace(
  476. "No significant changes.", f"No significant changes since {current_version}."
  477. )
  478. # Prepend changes to changelog
  479. with open("CHANGES.md", "r+") as f:
  480. existing_content = f.read()
  481. f.seek(0, 0)
  482. f.write(new_changes)
  483. f.write("\n")
  484. f.write(existing_content)
  485. # Remove all the news fragments
  486. for filename in glob.iglob("changelog.d/*.*"):
  487. os.remove(filename)
  488. if __name__ == "__main__":
  489. cli()