1
0

release.py 30 KB

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