release.py 29 KB

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