1
0

release.py 27 KB

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