release.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 re
  19. import subprocess
  20. import sys
  21. import urllib.request
  22. from os import path
  23. from tempfile import TemporaryDirectory
  24. from typing import List, Optional, Tuple
  25. import attr
  26. import click
  27. import commonmark
  28. import git
  29. import redbaron
  30. from click.exceptions import ClickException
  31. from github import Github
  32. from packaging import version
  33. @click.group()
  34. def cli():
  35. """An interactive script to walk through the parts of creating a release.
  36. Requires the dev dependencies be installed, which can be done via:
  37. pip install -e .[dev]
  38. Then to use:
  39. ./scripts-dev/release.py prepare
  40. # ... ask others to look at the changelog ...
  41. ./scripts-dev/release.py tag
  42. # ... wait for asssets to build ...
  43. ./scripts-dev/release.py publish
  44. ./scripts-dev/release.py upload
  45. If the env var GH_TOKEN (or GITHUB_TOKEN) is set, or passed into the
  46. `tag`/`publish` command, then a new draft release will be created/published.
  47. """
  48. @cli.command()
  49. def prepare():
  50. """Do the initial stages of creating a release, including creating release
  51. branch, updating changelog and pushing to GitHub.
  52. """
  53. # Make sure we're in a git repo.
  54. try:
  55. repo = git.Repo()
  56. except git.InvalidGitRepositoryError:
  57. raise click.ClickException("Not in Synapse repo.")
  58. if repo.is_dirty():
  59. raise click.ClickException("Uncommitted changes exist.")
  60. click.secho("Updating git repo...")
  61. repo.remote().fetch()
  62. # Get the current version and AST from root Synapse module.
  63. current_version, parsed_synapse_ast, version_node = parse_version_from_module()
  64. # Figure out what sort of release we're doing and calcuate the new version.
  65. rc = click.confirm("RC", default=True)
  66. if current_version.pre:
  67. # If the current version is an RC we don't need to bump any of the
  68. # version numbers (other than the RC number).
  69. if rc:
  70. new_version = "{}.{}.{}rc{}".format(
  71. current_version.major,
  72. current_version.minor,
  73. current_version.micro,
  74. current_version.pre[1] + 1,
  75. )
  76. else:
  77. new_version = "{}.{}.{}".format(
  78. current_version.major,
  79. current_version.minor,
  80. current_version.micro,
  81. )
  82. else:
  83. # If this is a new release cycle then we need to know if it's a minor
  84. # or a patch version bump.
  85. release_type = click.prompt(
  86. "Release type",
  87. type=click.Choice(("minor", "patch")),
  88. show_choices=True,
  89. default="minor",
  90. )
  91. if release_type == "minor":
  92. if rc:
  93. new_version = "{}.{}.{}rc1".format(
  94. current_version.major,
  95. current_version.minor + 1,
  96. 0,
  97. )
  98. else:
  99. new_version = "{}.{}.{}".format(
  100. current_version.major,
  101. current_version.minor + 1,
  102. 0,
  103. )
  104. else:
  105. if rc:
  106. new_version = "{}.{}.{}rc1".format(
  107. current_version.major,
  108. current_version.minor,
  109. current_version.micro + 1,
  110. )
  111. else:
  112. new_version = "{}.{}.{}".format(
  113. current_version.major,
  114. current_version.minor,
  115. current_version.micro + 1,
  116. )
  117. # Confirm the calculated version is OK.
  118. if not click.confirm(f"Create new version: {new_version}?", default=True):
  119. click.get_current_context().abort()
  120. # Switch to the release branch.
  121. parsed_new_version = version.parse(new_version)
  122. # We assume for debian changelogs that we only do RCs or full releases.
  123. assert not parsed_new_version.is_devrelease
  124. assert not parsed_new_version.is_postrelease
  125. release_branch_name = (
  126. f"release-v{parsed_new_version.major}.{parsed_new_version.minor}"
  127. )
  128. release_branch = find_ref(repo, release_branch_name)
  129. if release_branch:
  130. if release_branch.is_remote():
  131. # If the release branch only exists on the remote we check it out
  132. # locally.
  133. repo.git.checkout(release_branch_name)
  134. release_branch = repo.active_branch
  135. else:
  136. # If a branch doesn't exist we create one. We ask which one branch it
  137. # should be based off, defaulting to sensible values depending on the
  138. # release type.
  139. if current_version.is_prerelease:
  140. default = release_branch_name
  141. elif release_type == "minor":
  142. default = "develop"
  143. else:
  144. default = "master"
  145. branch_name = click.prompt(
  146. "Which branch should the release be based on?", default=default
  147. )
  148. base_branch = find_ref(repo, branch_name)
  149. if not base_branch:
  150. print(f"Could not find base branch {branch_name}!")
  151. click.get_current_context().abort()
  152. # Check out the base branch and ensure it's up to date
  153. repo.head.reference = base_branch
  154. repo.head.reset(index=True, working_tree=True)
  155. if not base_branch.is_remote():
  156. update_branch(repo)
  157. # Create the new release branch
  158. release_branch = repo.create_head(release_branch_name, commit=base_branch)
  159. # Switch to the release branch and ensure its up to date.
  160. repo.git.checkout(release_branch_name)
  161. update_branch(repo)
  162. # Update the `__version__` variable and write it back to the file.
  163. version_node.value = '"' + new_version + '"'
  164. with open("synapse/__init__.py", "w") as f:
  165. f.write(parsed_synapse_ast.dumps())
  166. # Generate changelogs
  167. subprocess.run("python3 -m towncrier", shell=True)
  168. # Generate debian changelogs
  169. if parsed_new_version.pre is not None:
  170. # If this is an RC then we need to coerce the version string to match
  171. # Debian norms, e.g. 1.39.0rc2 gets converted to 1.39.0~rc2.
  172. base_ver = parsed_new_version.base_version
  173. pre_type, pre_num = parsed_new_version.pre
  174. debian_version = f"{base_ver}~{pre_type}{pre_num}"
  175. else:
  176. debian_version = new_version
  177. subprocess.run(
  178. f'dch -M -v {debian_version} "New synapse release {debian_version}."',
  179. shell=True,
  180. )
  181. subprocess.run('dch -M -r -D stable ""', shell=True)
  182. # Show the user the changes and ask if they want to edit the change log.
  183. repo.git.add("-u")
  184. subprocess.run("git diff --cached", shell=True)
  185. if click.confirm("Edit changelog?", default=False):
  186. click.edit(filename="CHANGES.md")
  187. # Commit the changes.
  188. repo.git.add("-u")
  189. repo.git.commit(f"-m {new_version}")
  190. # We give the option to bail here in case the user wants to make sure things
  191. # are OK before pushing.
  192. if not click.confirm("Push branch to github?", default=True):
  193. print("")
  194. print("Run when ready to push:")
  195. print("")
  196. print(f"\tgit push -u {repo.remote().name} {repo.active_branch.name}")
  197. print("")
  198. sys.exit(0)
  199. # Otherwise, push and open the changelog in the browser.
  200. repo.git.push("-u", repo.remote().name, repo.active_branch.name)
  201. click.launch(
  202. f"https://github.com/matrix-org/synapse/blob/{repo.active_branch.name}/CHANGES.md"
  203. )
  204. @cli.command()
  205. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"])
  206. def tag(gh_token: Optional[str]):
  207. """Tags the release and generates a draft GitHub release"""
  208. # Make sure we're in a git repo.
  209. try:
  210. repo = git.Repo()
  211. except git.InvalidGitRepositoryError:
  212. raise click.ClickException("Not in Synapse repo.")
  213. if repo.is_dirty():
  214. raise click.ClickException("Uncommitted changes exist.")
  215. click.secho("Updating git repo...")
  216. repo.remote().fetch()
  217. # Find out the version and tag name.
  218. current_version, _, _ = parse_version_from_module()
  219. tag_name = f"v{current_version}"
  220. # Check we haven't released this version.
  221. if tag_name in repo.tags:
  222. raise click.ClickException(f"Tag {tag_name} already exists!\n")
  223. # Get the appropriate changelogs and tag.
  224. changes = get_changes_for_version(current_version)
  225. click.echo_via_pager(changes)
  226. if click.confirm("Edit text?", default=False):
  227. changes = click.edit(changes, require_save=False)
  228. repo.create_tag(tag_name, message=changes)
  229. if not click.confirm("Push tag to GitHub?", default=True):
  230. print("")
  231. print("Run when ready to push:")
  232. print("")
  233. print(f"\tgit push {repo.remote().name} tag {current_version}")
  234. print("")
  235. return
  236. repo.git.push(repo.remote().name, "tag", tag_name)
  237. # If no token was given, we bail here
  238. if not gh_token:
  239. click.launch(f"https://github.com/matrix-org/synapse/releases/edit/{tag_name}")
  240. return
  241. # Create a new draft release
  242. gh = Github(gh_token)
  243. gh_repo = gh.get_repo("matrix-org/synapse")
  244. release = gh_repo.create_git_release(
  245. tag=tag_name,
  246. name=tag_name,
  247. message=changes,
  248. draft=True,
  249. prerelease=current_version.is_prerelease,
  250. )
  251. # Open the release and the actions where we are building the assets.
  252. click.launch(release.html_url)
  253. click.launch(
  254. f"https://github.com/matrix-org/synapse/actions?query=branch%3A{tag_name}"
  255. )
  256. click.echo("Wait for release assets to be built")
  257. @cli.command()
  258. @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"], required=True)
  259. def publish(gh_token: str):
  260. """Publish release."""
  261. # Make sure we're in a git repo.
  262. try:
  263. repo = git.Repo()
  264. except git.InvalidGitRepositoryError:
  265. raise click.ClickException("Not in Synapse repo.")
  266. if repo.is_dirty():
  267. raise click.ClickException("Uncommitted changes exist.")
  268. current_version, _, _ = parse_version_from_module()
  269. tag_name = f"v{current_version}"
  270. if not click.confirm(f"Publish {tag_name}?", default=True):
  271. return
  272. # Publish the draft release
  273. gh = Github(gh_token)
  274. gh_repo = gh.get_repo("matrix-org/synapse")
  275. for release in gh_repo.get_releases():
  276. if release.title == tag_name:
  277. break
  278. else:
  279. raise ClickException(f"Failed to find GitHub release for {tag_name}")
  280. assert release.title == tag_name
  281. if not release.draft:
  282. click.echo("Release already published.")
  283. return
  284. release = release.update_release(
  285. name=release.title,
  286. message=release.body,
  287. tag_name=release.tag_name,
  288. prerelease=release.prerelease,
  289. draft=False,
  290. )
  291. @cli.command()
  292. def upload():
  293. """Upload release to pypi."""
  294. current_version, _, _ = parse_version_from_module()
  295. tag_name = f"v{current_version}"
  296. pypi_asset_names = [
  297. f"matrix_synapse-{current_version}-py3-none-any.whl",
  298. f"matrix-synapse-{current_version}.tar.gz",
  299. ]
  300. with TemporaryDirectory(prefix=f"synapse_upload_{tag_name}_") as tmpdir:
  301. for name in pypi_asset_names:
  302. filename = path.join(tmpdir, name)
  303. url = f"https://github.com/matrix-org/synapse/releases/download/{tag_name}/{name}"
  304. click.echo(f"Downloading {name} into {filename}")
  305. urllib.request.urlretrieve(url, filename=filename)
  306. if click.confirm("Upload to PyPI?", default=True):
  307. subprocess.run("twine upload *", shell=True, cwd=tmpdir)
  308. click.echo(
  309. f"Done! Remember to merge the tag {tag_name} into the appropriate branches"
  310. )
  311. def parse_version_from_module() -> Tuple[
  312. version.Version, redbaron.RedBaron, redbaron.Node
  313. ]:
  314. # Parse the AST and load the `__version__` node so that we can edit it
  315. # later.
  316. with open("synapse/__init__.py") as f:
  317. red = redbaron.RedBaron(f.read())
  318. version_node = None
  319. for node in red:
  320. if node.type != "assignment":
  321. continue
  322. if node.target.type != "name":
  323. continue
  324. if node.target.value != "__version__":
  325. continue
  326. version_node = node
  327. break
  328. if not version_node:
  329. print("Failed to find '__version__' definition in synapse/__init__.py")
  330. sys.exit(1)
  331. # Parse the current version.
  332. current_version = version.parse(version_node.value.value.strip('"'))
  333. assert isinstance(current_version, version.Version)
  334. return current_version, red, version_node
  335. def find_ref(repo: git.Repo, ref_name: str) -> Optional[git.HEAD]:
  336. """Find the branch/ref, looking first locally then in the remote."""
  337. if ref_name in repo.refs:
  338. return repo.refs[ref_name]
  339. elif ref_name in repo.remote().refs:
  340. return repo.remote().refs[ref_name]
  341. else:
  342. return None
  343. def update_branch(repo: git.Repo):
  344. """Ensure branch is up to date if it has a remote"""
  345. if repo.active_branch.tracking_branch():
  346. repo.git.merge(repo.active_branch.tracking_branch().name)
  347. def get_changes_for_version(wanted_version: version.Version) -> str:
  348. """Get the changelogs for the given version.
  349. If an RC then will only get the changelog for that RC version, otherwise if
  350. its a full release will get the changelog for the release and all its RCs.
  351. """
  352. with open("CHANGES.md") as f:
  353. changes = f.read()
  354. # First we parse the changelog so that we can split it into sections based
  355. # on the release headings.
  356. ast = commonmark.Parser().parse(changes)
  357. @attr.s(auto_attribs=True)
  358. class VersionSection:
  359. title: str
  360. # These are 0-based.
  361. start_line: int
  362. end_line: Optional[int] = None # Is none if its the last entry
  363. headings: List[VersionSection] = []
  364. for node, _ in ast.walker():
  365. # We look for all text nodes that are in a level 1 heading.
  366. if node.t != "text":
  367. continue
  368. if node.parent.t != "heading" or node.parent.level != 1:
  369. continue
  370. # If we have a previous heading then we update its `end_line`.
  371. if headings:
  372. headings[-1].end_line = node.parent.sourcepos[0][0] - 1
  373. headings.append(VersionSection(node.literal, node.parent.sourcepos[0][0] - 1))
  374. changes_by_line = changes.split("\n")
  375. version_changelog = [] # The lines we want to include in the changelog
  376. # Go through each section and find any that match the requested version.
  377. regex = re.compile(r"^Synapse v?(\S+)")
  378. for section in headings:
  379. groups = regex.match(section.title)
  380. if not groups:
  381. continue
  382. heading_version = version.parse(groups.group(1))
  383. heading_base_version = version.parse(heading_version.base_version)
  384. # Check if heading version matches the requested version, or if its an
  385. # RC of the requested version.
  386. if wanted_version not in (heading_version, heading_base_version):
  387. continue
  388. version_changelog.extend(changes_by_line[section.start_line : section.end_line])
  389. return "\n".join(version_changelog)
  390. if __name__ == "__main__":
  391. cli()