release.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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, Match, Optional, Union
  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. parsed_new_version = version.parse(new_version)
  145. # We assume for debian changelogs that we only do RCs or full releases.
  146. assert not parsed_new_version.is_devrelease
  147. assert not parsed_new_version.is_postrelease
  148. release_branch_name = get_release_branch_name(parsed_new_version)
  149. release_branch = find_ref(synapse_repo, release_branch_name)
  150. if release_branch:
  151. if release_branch.is_remote():
  152. # If the release branch only exists on the remote we check it out
  153. # locally.
  154. synapse_repo.git.checkout(release_branch_name)
  155. else:
  156. # If a branch doesn't exist we create one. We ask which one branch it
  157. # should be based off, defaulting to sensible values depending on the
  158. # release type.
  159. if current_version.is_prerelease:
  160. default = release_branch_name
  161. elif release_type == "minor":
  162. default = "develop"
  163. else:
  164. default = "master"
  165. branch_name = click.prompt(
  166. "Which branch should the release be based on?", default=default
  167. )
  168. for repo_name, repo in {"synapse": synapse_repo, "sytest": sytest_repo}.items():
  169. base_branch = find_ref(repo, branch_name)
  170. if not base_branch:
  171. print(f"Could not find base branch {branch_name} for {repo_name}!")
  172. click.get_current_context().abort()
  173. # Check out the base branch and ensure it's up to date
  174. repo.head.set_reference(
  175. base_branch, f"check out the base branch for {repo_name}"
  176. )
  177. repo.head.reset(index=True, working_tree=True)
  178. if not base_branch.is_remote():
  179. update_branch(repo)
  180. # Create the new release branch
  181. repo.create_head(release_branch_name, commit=base_branch)
  182. # Special-case SyTest: we don't actually prepare any files so we may
  183. # as well push it now (and only when we create a release branch;
  184. # not on subsequent RCs or full releases).
  185. if click.confirm("Push new SyTest branch?", default=True):
  186. sytest_repo.git.push("-u", sytest_repo.remote().name, release_branch_name)
  187. # Switch to the release branch and ensure it's up to date.
  188. synapse_repo.git.checkout(release_branch_name)
  189. update_branch(synapse_repo)
  190. # Update the version specified in pyproject.toml.
  191. subprocess.check_output(["poetry", "version", new_version])
  192. # Generate changelogs.
  193. generate_and_write_changelog(synapse_repo, current_version, new_version)
  194. # Generate debian changelogs
  195. if parsed_new_version.pre is not None:
  196. # If this is an RC then we need to coerce the version string to match
  197. # Debian norms, e.g. 1.39.0rc2 gets converted to 1.39.0~rc2.
  198. base_ver = parsed_new_version.base_version
  199. pre_type, pre_num = parsed_new_version.pre
  200. debian_version = f"{base_ver}~{pre_type}{pre_num}"
  201. else:
  202. debian_version = new_version
  203. run_until_successful(
  204. f'dch -M -v {debian_version} "New Synapse release {new_version}."',
  205. shell=True,
  206. )
  207. run_until_successful('dch -M -r -D stable ""', shell=True)
  208. # Show the user the changes and ask if they want to edit the change log.
  209. synapse_repo.git.add("-u")
  210. subprocess.run("git diff --cached", shell=True)
  211. if click.confirm("Edit changelog?", default=False):
  212. click.edit(filename="CHANGES.md")
  213. # Commit the changes.
  214. synapse_repo.git.add("-u")
  215. synapse_repo.git.commit("-m", new_version)
  216. # We give the option to bail here in case the user wants to make sure things
  217. # are OK before pushing.
  218. if not click.confirm("Push branch to github?", default=True):
  219. print("")
  220. print("Run when ready to push:")
  221. print("")
  222. print(
  223. f"\tgit push -u {synapse_repo.remote().name} {synapse_repo.active_branch.name}"
  224. )
  225. print("")
  226. sys.exit(0)
  227. # Otherwise, push and open the changelog in the browser.
  228. synapse_repo.git.push(
  229. "-u", synapse_repo.remote().name, synapse_repo.active_branch.name
  230. )
  231. print("Opening the changelog in your browser...")
  232. print("Please ask #synapse-dev to give it a check.")
  233. click.launch(
  234. f"https://github.com/matrix-org/synapse/blob/{synapse_repo.active_branch.name}/CHANGES.md"
  235. )
  236. @cli.command()
  237. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"])
  238. def tag(gh_token: Optional[str]) -> None:
  239. _tag(gh_token)
  240. def _tag(gh_token: Optional[str]) -> None:
  241. """Tags the release and generates a draft GitHub release"""
  242. # Make sure we're in a git repo.
  243. repo = get_repo_and_check_clean_checkout()
  244. click.secho("Updating git repo...")
  245. repo.remote().fetch()
  246. # Find out the version and tag name.
  247. current_version = get_package_version()
  248. tag_name = f"v{current_version}"
  249. # Check we haven't released this version.
  250. if tag_name in repo.tags:
  251. raise click.ClickException(f"Tag {tag_name} already exists!\n")
  252. # Check we're on the right release branch
  253. release_branch = get_release_branch_name(current_version)
  254. if repo.active_branch.name != release_branch:
  255. click.echo(
  256. f"Need to be on the release branch ({release_branch}) before tagging. "
  257. f"Currently on ({repo.active_branch.name})."
  258. )
  259. click.get_current_context().abort()
  260. # Get the appropriate changelogs and tag.
  261. changes = get_changes_for_version(current_version)
  262. click.echo_via_pager(changes)
  263. if click.confirm("Edit text?", default=False):
  264. edited_changes = click.edit(changes, require_save=False)
  265. # This assert is for mypy's benefit. click's docs are a little unclear, but
  266. # when `require_save=False`, not saving the temp file in the editor returns
  267. # the original string.
  268. assert edited_changes is not None
  269. changes = edited_changes
  270. repo.create_tag(tag_name, message=changes, sign=True)
  271. if not click.confirm("Push tag to GitHub?", default=True):
  272. print("")
  273. print("Run when ready to push:")
  274. print("")
  275. print(f"\tgit push {repo.remote().name} tag {current_version}")
  276. print("")
  277. return
  278. repo.git.push(repo.remote().name, "tag", tag_name)
  279. # If no token was given, we bail here
  280. if not gh_token:
  281. print("Launching the GitHub release page in your browser.")
  282. print("Please correct the title and create a draft.")
  283. if current_version.is_prerelease:
  284. print("As this is an RC, remember to mark it as a pre-release!")
  285. print("(by the way, this step can be automated by passing --gh-token,")
  286. print("or one of the GH_TOKEN or GITHUB_TOKEN env vars.)")
  287. click.launch(f"https://github.com/matrix-org/synapse/releases/edit/{tag_name}")
  288. print("Once done, you need to wait for the release assets to build.")
  289. if click.confirm("Launch the release assets actions page?", default=True):
  290. click.launch(
  291. f"https://github.com/matrix-org/synapse/actions?query=branch%3A{tag_name}"
  292. )
  293. return
  294. # Create a new draft release
  295. gh = Github(gh_token)
  296. gh_repo = gh.get_repo("matrix-org/synapse")
  297. release = gh_repo.create_git_release(
  298. tag=tag_name,
  299. name=tag_name,
  300. message=changes,
  301. draft=True,
  302. prerelease=current_version.is_prerelease,
  303. )
  304. # Open the release and the actions where we are building the assets.
  305. print("Launching the release page and the actions page.")
  306. click.launch(release.html_url)
  307. click.launch(
  308. f"https://github.com/matrix-org/synapse/actions?query=branch%3A{tag_name}"
  309. )
  310. click.echo("Wait for release assets to be built")
  311. @cli.command()
  312. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"], required=True)
  313. def publish(gh_token: str) -> None:
  314. _publish(gh_token)
  315. def _publish(gh_token: str) -> None:
  316. """Publish release on GitHub."""
  317. # Make sure we're in a git repo.
  318. get_repo_and_check_clean_checkout()
  319. current_version = get_package_version()
  320. tag_name = f"v{current_version}"
  321. if not click.confirm(f"Publish release {tag_name} on GitHub?", default=True):
  322. return
  323. # Publish the draft release
  324. gh = Github(gh_token)
  325. gh_repo = gh.get_repo("matrix-org/synapse")
  326. for release in gh_repo.get_releases():
  327. if release.title == tag_name:
  328. break
  329. else:
  330. raise ClickException(f"Failed to find GitHub release for {tag_name}")
  331. assert release.title == tag_name
  332. if not release.draft:
  333. click.echo("Release already published.")
  334. return
  335. release = release.update_release(
  336. name=release.title,
  337. message=release.body,
  338. tag_name=release.tag_name,
  339. prerelease=release.prerelease,
  340. draft=False,
  341. )
  342. @cli.command()
  343. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"], required=False)
  344. def upload(gh_token: Optional[str]) -> None:
  345. _upload(gh_token)
  346. def _upload(gh_token: Optional[str]) -> None:
  347. """Upload release to pypi."""
  348. current_version = get_package_version()
  349. tag_name = f"v{current_version}"
  350. # Check we have the right tag checked out.
  351. repo = get_repo_and_check_clean_checkout()
  352. tag = repo.tag(f"refs/tags/{tag_name}")
  353. if repo.head.commit != tag.commit:
  354. click.echo(f"Tag {tag_name} ({tag.commit}) is not currently checked out!")
  355. click.get_current_context().abort()
  356. # Query all the assets corresponding to this release.
  357. gh = Github(gh_token)
  358. gh_repo = gh.get_repo("matrix-org/synapse")
  359. gh_release = gh_repo.get_release(tag_name)
  360. all_assets = set(gh_release.get_assets())
  361. # Only accept the wheels and sdist.
  362. # Notably: we don't care about debs.tar.xz.
  363. asset_names_and_urls = sorted(
  364. (asset.name, asset.browser_download_url)
  365. for asset in all_assets
  366. if asset.name.endswith((".whl", ".tar.gz"))
  367. )
  368. # Print out what we've determined.
  369. print("Found relevant assets:")
  370. for asset_name, _ in asset_names_and_urls:
  371. print(f" - {asset_name}")
  372. ignored_asset_names = sorted(
  373. {asset.name for asset in all_assets}
  374. - {asset_name for asset_name, _ in asset_names_and_urls}
  375. )
  376. print("\nIgnoring irrelevant assets:")
  377. for asset_name in ignored_asset_names:
  378. print(f" - {asset_name}")
  379. with TemporaryDirectory(prefix=f"synapse_upload_{tag_name}_") as tmpdir:
  380. for name, asset_download_url in asset_names_and_urls:
  381. filename = path.join(tmpdir, name)
  382. click.echo(f"Downloading {name} into {filename}")
  383. urllib.request.urlretrieve(asset_download_url, filename=filename)
  384. if click.confirm("Upload to PyPI?", default=True):
  385. subprocess.run("twine upload *", shell=True, cwd=tmpdir)
  386. click.echo(
  387. f"Done! Remember to merge the tag {tag_name} into the appropriate branches"
  388. )
  389. def _merge_into(repo: Repo, source: str, target: str) -> None:
  390. """
  391. Merges branch `source` into branch `target`.
  392. Pulls both before merging and pushes the result.
  393. """
  394. # Update our branches and switch to the target branch
  395. for branch in [source, target]:
  396. click.echo(f"Switching to {branch} and pulling...")
  397. repo.heads[branch].checkout()
  398. # Pull so we're up to date
  399. repo.remote().pull()
  400. assert repo.active_branch.name == target
  401. try:
  402. # TODO This seemed easier than using GitPython directly
  403. click.echo(f"Merging {source}...")
  404. repo.git.merge(source)
  405. except GitCommandError as exc:
  406. # If a merge conflict occurs, give some context and try to
  407. # make it easy to abort if necessary.
  408. click.echo(exc)
  409. if not click.confirm(
  410. f"Likely merge conflict whilst merging ({source} → {target}). "
  411. f"Have you resolved it?"
  412. ):
  413. repo.git.merge("--abort")
  414. return
  415. # Push result.
  416. click.echo("Pushing...")
  417. repo.remote().push()
  418. @cli.command()
  419. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"], required=False)
  420. def wait_for_actions(gh_token: Optional[str]) -> None:
  421. _wait_for_actions(gh_token)
  422. def _wait_for_actions(gh_token: Optional[str]) -> None:
  423. # Find out the version and tag name.
  424. current_version = get_package_version()
  425. tag_name = f"v{current_version}"
  426. # Authentication is optional on this endpoint,
  427. # but use a token if we have one to reduce the chance of being rate-limited.
  428. url = f"https://api.github.com/repos/matrix-org/synapse/actions/runs?branch={tag_name}"
  429. headers = {"Accept": "application/vnd.github+json"}
  430. if gh_token is not None:
  431. headers["authorization"] = f"token {gh_token}"
  432. req = urllib.request.Request(url, headers=headers)
  433. time.sleep(10 * 60)
  434. while True:
  435. time.sleep(5 * 60)
  436. response = urllib.request.urlopen(req)
  437. resp = json.loads(response.read())
  438. if len(resp["workflow_runs"]) == 0:
  439. continue
  440. if all(
  441. workflow["status"] != "in_progress" for workflow in resp["workflow_runs"]
  442. ):
  443. success = (
  444. workflow["status"] == "completed" for workflow in resp["workflow_runs"]
  445. )
  446. if success:
  447. _notify("Workflows successful. You can now continue the release.")
  448. else:
  449. _notify("Workflows failed.")
  450. click.confirm("Continue anyway?", abort=True)
  451. break
  452. def _notify(message: str) -> None:
  453. # Send a bell character. Most terminals will play a sound or show a notification
  454. # for this.
  455. click.echo(f"\a{message}")
  456. # Try and run notify-send, but don't raise an Exception if this fails
  457. # (This is best-effort)
  458. # TODO Support other platforms?
  459. subprocess.run(
  460. [
  461. "notify-send",
  462. "--app-name",
  463. "Synapse Release Script",
  464. "--expire-time",
  465. "3600000",
  466. message,
  467. ]
  468. )
  469. @cli.command()
  470. def merge_back() -> None:
  471. _merge_back()
  472. def _merge_back() -> None:
  473. """Merge the release branch back into the appropriate branches.
  474. All branches will be automatically pulled from the remote and the results
  475. will be pushed to the remote."""
  476. synapse_repo = get_repo_and_check_clean_checkout()
  477. branch_name = synapse_repo.active_branch.name
  478. if not branch_name.startswith("release-v"):
  479. raise RuntimeError("Not on a release branch. This does not seem sensible.")
  480. # Pull so we're up to date
  481. synapse_repo.remote().pull()
  482. current_version = get_package_version()
  483. if current_version.is_prerelease:
  484. # Release candidate
  485. if click.confirm(f"Merge {branch_name} → develop?", default=True):
  486. _merge_into(synapse_repo, branch_name, "develop")
  487. else:
  488. # Full release
  489. sytest_repo = get_repo_and_check_clean_checkout("../sytest", "sytest")
  490. if click.confirm(f"Merge {branch_name} → master?", default=True):
  491. _merge_into(synapse_repo, branch_name, "master")
  492. if click.confirm("Merge master → develop?", default=True):
  493. _merge_into(synapse_repo, "master", "develop")
  494. if click.confirm(f"On SyTest, merge {branch_name} → master?", default=True):
  495. _merge_into(sytest_repo, branch_name, "master")
  496. if click.confirm("On SyTest, merge master → develop?", default=True):
  497. _merge_into(sytest_repo, "master", "develop")
  498. @cli.command()
  499. def announce() -> None:
  500. _announce()
  501. def _announce() -> None:
  502. """Generate markdown to announce the release."""
  503. current_version = get_package_version()
  504. tag_name = f"v{current_version}"
  505. click.echo(
  506. f"""
  507. Hi everyone. Synapse {current_version} has just been released.
  508. [notes](https://github.com/matrix-org/synapse/releases/tag/{tag_name}) | \
  509. [docker](https://hub.docker.com/r/matrixdotorg/synapse/tags?name={tag_name}) | \
  510. [debs](https://packages.matrix.org/debian/) | \
  511. [pypi](https://pypi.org/project/matrix-synapse/{current_version}/)"""
  512. )
  513. if "rc" in tag_name:
  514. click.echo(
  515. """
  516. Announce the RC in
  517. - #homeowners:matrix.org (Synapse Announcements)
  518. - #synapse-dev:matrix.org"""
  519. )
  520. else:
  521. click.echo(
  522. """
  523. Announce the release in
  524. - #homeowners:matrix.org (Synapse Announcements), bumping the version in the topic
  525. - #synapse:matrix.org (Synapse Admins), bumping the version in the topic
  526. - #synapse-dev:matrix.org
  527. - #synapse-package-maintainers:matrix.org
  528. Ask the designated people to do the blog and tweets."""
  529. )
  530. @cli.command()
  531. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"], required=True)
  532. def full(gh_token: str) -> None:
  533. click.echo("1. If this is a security release, read the security wiki page.")
  534. click.echo("2. Check for any release blockers before proceeding.")
  535. click.echo(" https://github.com/matrix-org/synapse/labels/X-Release-Blocker")
  536. click.confirm("Ready?", abort=True)
  537. click.echo("\n*** prepare ***")
  538. _prepare()
  539. click.echo("Deploy to matrix.org and ensure that it hasn't fallen over.")
  540. click.echo("Remember to silence the alerts to prevent alert spam.")
  541. click.confirm("Deployed?", abort=True)
  542. click.echo("\n*** tag ***")
  543. _tag(gh_token)
  544. click.echo("\n*** wait for actions ***")
  545. _wait_for_actions(gh_token)
  546. click.echo("\n*** publish ***")
  547. _publish(gh_token)
  548. click.echo("\n*** upload ***")
  549. _upload(gh_token)
  550. click.echo("\n*** merge back ***")
  551. _merge_back()
  552. click.echo("\nUpdate the Debian repository")
  553. click.confirm("Started updating Debian repository?", abort=True)
  554. click.echo("\nWait for all release methods to be ready.")
  555. # Docker should be ready because it was done by the workflows earlier
  556. # PyPI should be ready because we just ran upload().
  557. # TODO Automatically poll until the Debs have made it to packages.matrix.org
  558. click.confirm("Debs ready?", abort=True)
  559. click.echo("\n*** announce ***")
  560. _announce()
  561. def get_package_version() -> version.Version:
  562. version_string = subprocess.check_output(["poetry", "version", "--short"]).decode(
  563. "utf-8"
  564. )
  565. return version.Version(version_string)
  566. def get_release_branch_name(version_number: version.Version) -> str:
  567. return f"release-v{version_number.major}.{version_number.minor}"
  568. def get_repo_and_check_clean_checkout(
  569. path: str = ".", name: str = "synapse"
  570. ) -> git.Repo:
  571. """Get the project repo and check it's not got any uncommitted changes."""
  572. try:
  573. repo = git.Repo(path=path)
  574. except git.InvalidGitRepositoryError:
  575. raise click.ClickException(
  576. f"{path} is not a git repository (expecting a {name} repository)."
  577. )
  578. if repo.is_dirty():
  579. raise click.ClickException(f"Uncommitted changes exist in {path}.")
  580. return repo
  581. def find_ref(repo: git.Repo, ref_name: str) -> Optional[git.HEAD]:
  582. """Find the branch/ref, looking first locally then in the remote."""
  583. if ref_name in repo.references:
  584. return repo.references[ref_name]
  585. elif ref_name in repo.remote().refs:
  586. return repo.remote().refs[ref_name]
  587. else:
  588. return None
  589. def update_branch(repo: git.Repo) -> None:
  590. """Ensure branch is up to date if it has a remote"""
  591. tracking_branch = repo.active_branch.tracking_branch()
  592. if tracking_branch:
  593. repo.git.merge(tracking_branch.name)
  594. def get_changes_for_version(wanted_version: version.Version) -> str:
  595. """Get the changelogs for the given version.
  596. If an RC then will only get the changelog for that RC version, otherwise if
  597. its a full release will get the changelog for the release and all its RCs.
  598. """
  599. with open("CHANGES.md") as f:
  600. changes = f.read()
  601. # First we parse the changelog so that we can split it into sections based
  602. # on the release headings.
  603. ast = commonmark.Parser().parse(changes)
  604. @attr.s(auto_attribs=True)
  605. class VersionSection:
  606. title: str
  607. # These are 0-based.
  608. start_line: int
  609. end_line: Optional[int] = None # Is none if its the last entry
  610. headings: List[VersionSection] = []
  611. for node, _ in ast.walker():
  612. # We look for all text nodes that are in a level 1 heading.
  613. if node.t != "text":
  614. continue
  615. if node.parent.t != "heading" or node.parent.level != 1:
  616. continue
  617. # If we have a previous heading then we update its `end_line`.
  618. if headings:
  619. headings[-1].end_line = node.parent.sourcepos[0][0] - 1
  620. headings.append(VersionSection(node.literal, node.parent.sourcepos[0][0] - 1))
  621. changes_by_line = changes.split("\n")
  622. version_changelog = [] # The lines we want to include in the changelog
  623. # Go through each section and find any that match the requested version.
  624. regex = re.compile(r"^Synapse v?(\S+)")
  625. for section in headings:
  626. groups = regex.match(section.title)
  627. if not groups:
  628. continue
  629. heading_version = version.parse(groups.group(1))
  630. heading_base_version = version.parse(heading_version.base_version)
  631. # Check if heading version matches the requested version, or if its an
  632. # RC of the requested version.
  633. if wanted_version not in (heading_version, heading_base_version):
  634. continue
  635. version_changelog.extend(changes_by_line[section.start_line : section.end_line])
  636. return "\n".join(version_changelog)
  637. def generate_and_write_changelog(
  638. repo: Repo, current_version: version.Version, new_version: str
  639. ) -> None:
  640. # We do this by getting a draft so that we can edit it before writing to the
  641. # changelog.
  642. result = run_until_successful(
  643. f"python3 -m towncrier build --draft --version {new_version}",
  644. shell=True,
  645. capture_output=True,
  646. )
  647. new_changes = result.stdout.decode("utf-8")
  648. new_changes = new_changes.replace(
  649. "No significant changes.", f"No significant changes since {current_version}."
  650. )
  651. new_changes += build_dependabot_changelog(
  652. repo,
  653. 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. def build_dependabot_changelog(repo: Repo, current_version: version.Version) -> str:
  666. """Summarise dependabot commits between `current_version` and `release_branch`.
  667. Returns an empty string if there have been no such commits; otherwise outputs a
  668. third-level markdown header followed by an unordered list."""
  669. last_release_commit = repo.tag("v" + str(current_version)).commit
  670. rev_spec = f"{last_release_commit.hexsha}.."
  671. commits = list(git.objects.Commit.iter_items(repo, rev_spec))
  672. messages = []
  673. for commit in reversed(commits):
  674. if commit.author.name == "dependabot[bot]":
  675. message: Union[str, bytes] = commit.message
  676. if isinstance(message, bytes):
  677. message = message.decode("utf-8")
  678. messages.append(message.split("\n", maxsplit=1)[0])
  679. if not messages:
  680. print(f"No dependabot commits in range {rev_spec}", file=sys.stderr)
  681. return ""
  682. messages.sort()
  683. def replacer(match: Match[str]) -> str:
  684. desc = match.group(1)
  685. number = match.group(2)
  686. return f"* {desc}. ([\\#{number}](https://github.com/matrix-org/synapse/issues/{number}))"
  687. for i, message in enumerate(messages):
  688. messages[i] = re.sub(r"(.*) \(#(\d+)\)$", replacer, message)
  689. messages.insert(0, "### Updates to locked dependencies\n")
  690. # Add an extra blank line to the bottom of the section
  691. messages.append("")
  692. return "\n".join(messages)
  693. @cli.command()
  694. @click.argument("since")
  695. def test_dependabot_changelog(since: str) -> None:
  696. """Test building the dependabot changelog.
  697. Summarises all dependabot commits between the SINCE tag and the current git HEAD."""
  698. print(build_dependabot_changelog(git.Repo("."), version.Version(since)))
  699. if __name__ == "__main__":
  700. cli()