release.py 23 KB

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