release.py 28 KB

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