release.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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 os
  20. import re
  21. import subprocess
  22. import sys
  23. import urllib.request
  24. from os import path
  25. from tempfile import TemporaryDirectory
  26. from typing import Any, List, Optional, cast
  27. import attr
  28. import click
  29. import commonmark
  30. import git
  31. from click.exceptions import ClickException
  32. from github import Github
  33. from packaging import version
  34. def run_until_successful(
  35. command: str, *args: Any, **kwargs: Any
  36. ) -> subprocess.CompletedProcess:
  37. while True:
  38. completed_process = subprocess.run(command, *args, **kwargs)
  39. exit_code = completed_process.returncode
  40. if exit_code == 0:
  41. # successful, so nothing more to do here.
  42. return completed_process
  43. print(f"The command {command!r} failed with exit code {exit_code}.")
  44. print("Please try to correct the failure and then re-run.")
  45. click.confirm("Try again?", abort=True)
  46. @click.group()
  47. def cli() -> None:
  48. """An interactive script to walk through the parts of creating a release.
  49. Requires the dev dependencies be installed, which can be done via:
  50. pip install -e .[dev]
  51. Then to use:
  52. ./scripts-dev/release.py prepare
  53. # ... ask others to look at the changelog ...
  54. ./scripts-dev/release.py tag
  55. # ... wait for assets to build ...
  56. ./scripts-dev/release.py publish
  57. ./scripts-dev/release.py upload
  58. # Optional: generate some nice links for the announcement
  59. ./scripts-dev/release.py announce
  60. If the env var GH_TOKEN (or GITHUB_TOKEN) is set, or passed into the
  61. `tag`/`publish` command, then a new draft release will be created/published.
  62. """
  63. @cli.command()
  64. def prepare() -> None:
  65. """Do the initial stages of creating a release, including creating release
  66. branch, updating changelog and pushing to GitHub.
  67. """
  68. # Make sure we're in a git repo.
  69. try:
  70. repo = git.Repo()
  71. except git.InvalidGitRepositoryError:
  72. raise click.ClickException("Not in Synapse repo.")
  73. if repo.is_dirty():
  74. raise click.ClickException("Uncommitted changes exist.")
  75. click.secho("Updating git repo...")
  76. repo.remote().fetch()
  77. # Get the current version and AST from root Synapse module.
  78. current_version = get_package_version()
  79. # Figure out what sort of release we're doing and calcuate the new version.
  80. rc = click.confirm("RC", default=True)
  81. if current_version.pre:
  82. # If the current version is an RC we don't need to bump any of the
  83. # version numbers (other than the RC number).
  84. if rc:
  85. new_version = "{}.{}.{}rc{}".format(
  86. current_version.major,
  87. current_version.minor,
  88. current_version.micro,
  89. current_version.pre[1] + 1,
  90. )
  91. else:
  92. new_version = "{}.{}.{}".format(
  93. current_version.major,
  94. current_version.minor,
  95. current_version.micro,
  96. )
  97. else:
  98. # If this is a new release cycle then we need to know if it's a minor
  99. # or a patch version bump.
  100. release_type = click.prompt(
  101. "Release type",
  102. type=click.Choice(("minor", "patch")),
  103. show_choices=True,
  104. default="minor",
  105. )
  106. if release_type == "minor":
  107. if rc:
  108. new_version = "{}.{}.{}rc1".format(
  109. current_version.major,
  110. current_version.minor + 1,
  111. 0,
  112. )
  113. else:
  114. new_version = "{}.{}.{}".format(
  115. current_version.major,
  116. current_version.minor + 1,
  117. 0,
  118. )
  119. else:
  120. if rc:
  121. new_version = "{}.{}.{}rc1".format(
  122. current_version.major,
  123. current_version.minor,
  124. current_version.micro + 1,
  125. )
  126. else:
  127. new_version = "{}.{}.{}".format(
  128. current_version.major,
  129. current_version.minor,
  130. current_version.micro + 1,
  131. )
  132. # Confirm the calculated version is OK.
  133. if not click.confirm(f"Create new version: {new_version}?", default=True):
  134. click.get_current_context().abort()
  135. # Switch to the release branch.
  136. # Cast safety: parse() won't return a version.LegacyVersion from our
  137. # version string format.
  138. parsed_new_version = cast(version.Version, version.parse(new_version))
  139. # We assume for debian changelogs that we only do RCs or full releases.
  140. assert not parsed_new_version.is_devrelease
  141. assert not parsed_new_version.is_postrelease
  142. release_branch_name = (
  143. f"release-v{parsed_new_version.major}.{parsed_new_version.minor}"
  144. )
  145. release_branch = find_ref(repo, release_branch_name)
  146. if release_branch:
  147. if release_branch.is_remote():
  148. # If the release branch only exists on the remote we check it out
  149. # locally.
  150. repo.git.checkout(release_branch_name)
  151. else:
  152. # If a branch doesn't exist we create one. We ask which one branch it
  153. # should be based off, defaulting to sensible values depending on the
  154. # release type.
  155. if current_version.is_prerelease:
  156. default = release_branch_name
  157. elif release_type == "minor":
  158. default = "develop"
  159. else:
  160. default = "master"
  161. branch_name = click.prompt(
  162. "Which branch should the release be based on?", default=default
  163. )
  164. base_branch = find_ref(repo, branch_name)
  165. if not base_branch:
  166. print(f"Could not find base branch {branch_name}!")
  167. click.get_current_context().abort()
  168. # Check out the base branch and ensure it's up to date
  169. repo.head.set_reference(base_branch, "check out the base branch")
  170. repo.head.reset(index=True, working_tree=True)
  171. if not base_branch.is_remote():
  172. update_branch(repo)
  173. # Create the new release branch
  174. # Type ignore will no longer be needed after GitPython 3.1.28.
  175. # See https://github.com/gitpython-developers/GitPython/pull/1419
  176. repo.create_head(release_branch_name, commit=base_branch) # type: ignore[arg-type]
  177. # Switch to the release branch and ensure it's up to date.
  178. repo.git.checkout(release_branch_name)
  179. update_branch(repo)
  180. # Update the version specified in pyproject.toml.
  181. subprocess.check_output(["poetry", "version", new_version])
  182. # Generate changelogs.
  183. generate_and_write_changelog(current_version, new_version)
  184. # Generate debian changelogs
  185. if parsed_new_version.pre is not None:
  186. # If this is an RC then we need to coerce the version string to match
  187. # Debian norms, e.g. 1.39.0rc2 gets converted to 1.39.0~rc2.
  188. base_ver = parsed_new_version.base_version
  189. pre_type, pre_num = parsed_new_version.pre
  190. debian_version = f"{base_ver}~{pre_type}{pre_num}"
  191. else:
  192. debian_version = new_version
  193. run_until_successful(
  194. f'dch -M -v {debian_version} "New Synapse release {new_version}."',
  195. shell=True,
  196. )
  197. run_until_successful('dch -M -r -D stable ""', shell=True)
  198. # Show the user the changes and ask if they want to edit the change log.
  199. repo.git.add("-u")
  200. subprocess.run("git diff --cached", shell=True)
  201. if click.confirm("Edit changelog?", default=False):
  202. click.edit(filename="CHANGES.md")
  203. # Commit the changes.
  204. repo.git.add("-u")
  205. repo.git.commit("-m", new_version)
  206. # We give the option to bail here in case the user wants to make sure things
  207. # are OK before pushing.
  208. if not click.confirm("Push branch to github?", default=True):
  209. print("")
  210. print("Run when ready to push:")
  211. print("")
  212. print(f"\tgit push -u {repo.remote().name} {repo.active_branch.name}")
  213. print("")
  214. sys.exit(0)
  215. # Otherwise, push and open the changelog in the browser.
  216. repo.git.push("-u", repo.remote().name, repo.active_branch.name)
  217. print("Opening the changelog in your browser...")
  218. print("Please ask others to give it a check.")
  219. click.launch(
  220. f"https://github.com/matrix-org/synapse/blob/{repo.active_branch.name}/CHANGES.md"
  221. )
  222. @cli.command()
  223. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"])
  224. def tag(gh_token: Optional[str]) -> None:
  225. """Tags the release and generates a draft GitHub release"""
  226. # Make sure we're in a git repo.
  227. try:
  228. repo = git.Repo()
  229. except git.InvalidGitRepositoryError:
  230. raise click.ClickException("Not in Synapse repo.")
  231. if repo.is_dirty():
  232. raise click.ClickException("Uncommitted changes exist.")
  233. click.secho("Updating git repo...")
  234. repo.remote().fetch()
  235. # Find out the version and tag name.
  236. current_version = get_package_version()
  237. tag_name = f"v{current_version}"
  238. # Check we haven't released this version.
  239. if tag_name in repo.tags:
  240. raise click.ClickException(f"Tag {tag_name} already exists!\n")
  241. # Get the appropriate changelogs and tag.
  242. changes = get_changes_for_version(current_version)
  243. click.echo_via_pager(changes)
  244. if click.confirm("Edit text?", default=False):
  245. edited_changes = click.edit(changes, require_save=False)
  246. # This assert is for mypy's benefit. click's docs are a little unclear, but
  247. # when `require_save=False`, not saving the temp file in the editor returns
  248. # the original string.
  249. assert edited_changes is not None
  250. changes = edited_changes
  251. repo.create_tag(tag_name, message=changes, sign=True)
  252. if not click.confirm("Push tag to GitHub?", default=True):
  253. print("")
  254. print("Run when ready to push:")
  255. print("")
  256. print(f"\tgit push {repo.remote().name} tag {current_version}")
  257. print("")
  258. return
  259. repo.git.push(repo.remote().name, "tag", tag_name)
  260. # If no token was given, we bail here
  261. if not gh_token:
  262. print("Launching the GitHub release page in your browser.")
  263. print("Please correct the title and create a draft.")
  264. if current_version.is_prerelease:
  265. print("As this is an RC, remember to mark it as a pre-release!")
  266. print("(by the way, this step can be automated by passing --gh-token,")
  267. print("or one of the GH_TOKEN or GITHUB_TOKEN env vars.)")
  268. click.launch(f"https://github.com/matrix-org/synapse/releases/edit/{tag_name}")
  269. print("Once done, you need to wait for the release assets to build.")
  270. if click.confirm("Launch the release assets actions page?", default=True):
  271. click.launch(
  272. f"https://github.com/matrix-org/synapse/actions?query=branch%3A{tag_name}"
  273. )
  274. return
  275. # Create a new draft release
  276. gh = Github(gh_token)
  277. gh_repo = gh.get_repo("matrix-org/synapse")
  278. release = gh_repo.create_git_release(
  279. tag=tag_name,
  280. name=tag_name,
  281. message=changes,
  282. draft=True,
  283. prerelease=current_version.is_prerelease,
  284. )
  285. # Open the release and the actions where we are building the assets.
  286. print("Launching the release page and the actions page.")
  287. click.launch(release.html_url)
  288. click.launch(
  289. f"https://github.com/matrix-org/synapse/actions?query=branch%3A{tag_name}"
  290. )
  291. click.echo("Wait for release assets to be built")
  292. @cli.command()
  293. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"], required=True)
  294. def publish(gh_token: str) -> None:
  295. """Publish release."""
  296. # Make sure we're in a git repo.
  297. try:
  298. repo = git.Repo()
  299. except git.InvalidGitRepositoryError:
  300. raise click.ClickException("Not in Synapse repo.")
  301. if repo.is_dirty():
  302. raise click.ClickException("Uncommitted changes exist.")
  303. current_version = get_package_version()
  304. tag_name = f"v{current_version}"
  305. if not click.confirm(f"Publish {tag_name}?", default=True):
  306. return
  307. # Publish the draft release
  308. gh = Github(gh_token)
  309. gh_repo = gh.get_repo("matrix-org/synapse")
  310. for release in gh_repo.get_releases():
  311. if release.title == tag_name:
  312. break
  313. else:
  314. raise ClickException(f"Failed to find GitHub release for {tag_name}")
  315. assert release.title == tag_name
  316. if not release.draft:
  317. click.echo("Release already published.")
  318. return
  319. release = release.update_release(
  320. name=release.title,
  321. message=release.body,
  322. tag_name=release.tag_name,
  323. prerelease=release.prerelease,
  324. draft=False,
  325. )
  326. @cli.command()
  327. def upload() -> None:
  328. """Upload release to pypi."""
  329. current_version = get_package_version()
  330. tag_name = f"v{current_version}"
  331. pypi_asset_names = [
  332. f"matrix_synapse-{current_version}-py3-none-any.whl",
  333. f"matrix-synapse-{current_version}.tar.gz",
  334. ]
  335. with TemporaryDirectory(prefix=f"synapse_upload_{tag_name}_") as tmpdir:
  336. for name in pypi_asset_names:
  337. filename = path.join(tmpdir, name)
  338. url = f"https://github.com/matrix-org/synapse/releases/download/{tag_name}/{name}"
  339. click.echo(f"Downloading {name} into {filename}")
  340. urllib.request.urlretrieve(url, filename=filename)
  341. if click.confirm("Upload to PyPI?", default=True):
  342. subprocess.run("twine upload *", shell=True, cwd=tmpdir)
  343. click.echo(
  344. f"Done! Remember to merge the tag {tag_name} into the appropriate branches"
  345. )
  346. @cli.command()
  347. def announce() -> None:
  348. """Generate markdown to announce the release."""
  349. current_version = get_package_version()
  350. tag_name = f"v{current_version}"
  351. click.echo(
  352. f"""
  353. Hi everyone. Synapse {current_version} has just been released.
  354. [notes](https://github.com/matrix-org/synapse/releases/tag/{tag_name}) |\
  355. [docker](https://hub.docker.com/r/matrixdotorg/synapse/tags?name={tag_name}) | \
  356. [debs](https://packages.matrix.org/debian/) | \
  357. [pypi](https://pypi.org/project/matrix-synapse/{current_version}/)"""
  358. )
  359. if "rc" in tag_name:
  360. click.echo(
  361. """
  362. Announce the RC in
  363. - #homeowners:matrix.org (Synapse Announcements)
  364. - #synapse-dev:matrix.org"""
  365. )
  366. else:
  367. click.echo(
  368. """
  369. Announce the release in
  370. - #homeowners:matrix.org (Synapse Announcements), bumping the version in the topic
  371. - #synapse:matrix.org (Synapse Admins), bumping the version in the topic
  372. - #synapse-dev:matrix.org
  373. - #synapse-package-maintainers:matrix.org"""
  374. )
  375. def get_package_version() -> version.Version:
  376. version_string = subprocess.check_output(["poetry", "version", "--short"]).decode(
  377. "utf-8"
  378. )
  379. return version.Version(version_string)
  380. def find_ref(repo: git.Repo, ref_name: str) -> Optional[git.HEAD]:
  381. """Find the branch/ref, looking first locally then in the remote."""
  382. if ref_name in repo.references:
  383. return repo.references[ref_name]
  384. elif ref_name in repo.remote().refs:
  385. return repo.remote().refs[ref_name]
  386. else:
  387. return None
  388. def update_branch(repo: git.Repo) -> None:
  389. """Ensure branch is up to date if it has a remote"""
  390. tracking_branch = repo.active_branch.tracking_branch()
  391. if tracking_branch:
  392. repo.git.merge(tracking_branch.name)
  393. def get_changes_for_version(wanted_version: version.Version) -> str:
  394. """Get the changelogs for the given version.
  395. If an RC then will only get the changelog for that RC version, otherwise if
  396. its a full release will get the changelog for the release and all its RCs.
  397. """
  398. with open("CHANGES.md") as f:
  399. changes = f.read()
  400. # First we parse the changelog so that we can split it into sections based
  401. # on the release headings.
  402. ast = commonmark.Parser().parse(changes)
  403. @attr.s(auto_attribs=True)
  404. class VersionSection:
  405. title: str
  406. # These are 0-based.
  407. start_line: int
  408. end_line: Optional[int] = None # Is none if its the last entry
  409. headings: List[VersionSection] = []
  410. for node, _ in ast.walker():
  411. # We look for all text nodes that are in a level 1 heading.
  412. if node.t != "text":
  413. continue
  414. if node.parent.t != "heading" or node.parent.level != 1:
  415. continue
  416. # If we have a previous heading then we update its `end_line`.
  417. if headings:
  418. headings[-1].end_line = node.parent.sourcepos[0][0] - 1
  419. headings.append(VersionSection(node.literal, node.parent.sourcepos[0][0] - 1))
  420. changes_by_line = changes.split("\n")
  421. version_changelog = [] # The lines we want to include in the changelog
  422. # Go through each section and find any that match the requested version.
  423. regex = re.compile(r"^Synapse v?(\S+)")
  424. for section in headings:
  425. groups = regex.match(section.title)
  426. if not groups:
  427. continue
  428. heading_version = version.parse(groups.group(1))
  429. heading_base_version = version.parse(heading_version.base_version)
  430. # Check if heading version matches the requested version, or if its an
  431. # RC of the requested version.
  432. if wanted_version not in (heading_version, heading_base_version):
  433. continue
  434. version_changelog.extend(changes_by_line[section.start_line : section.end_line])
  435. return "\n".join(version_changelog)
  436. def generate_and_write_changelog(
  437. current_version: version.Version, new_version: str
  438. ) -> None:
  439. # We do this by getting a draft so that we can edit it before writing to the
  440. # changelog.
  441. result = run_until_successful(
  442. f"python3 -m towncrier build --draft --version {new_version}",
  443. shell=True,
  444. capture_output=True,
  445. )
  446. new_changes = result.stdout.decode("utf-8")
  447. new_changes = new_changes.replace(
  448. "No significant changes.", f"No significant changes since {current_version}."
  449. )
  450. # Prepend changes to changelog
  451. with open("CHANGES.md", "r+") as f:
  452. existing_content = f.read()
  453. f.seek(0, 0)
  454. f.write(new_changes)
  455. f.write("\n")
  456. f.write(existing_content)
  457. # Remove all the news fragments
  458. for filename in glob.iglob("changelog.d/*.*"):
  459. os.remove(filename)
  460. if __name__ == "__main__":
  461. cli()