release.py 19 KB

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