new_proposal.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #!/usr/bin/env python3
  2. """Prepares a new proposal file and PR."""
  3. __copyright__ = """
  4. Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  5. Exceptions. See /LICENSE for license information.
  6. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. """
  8. import argparse
  9. import os
  10. import re
  11. import shlex
  12. import shutil
  13. import subprocess
  14. import sys
  15. from pathlib import Path
  16. from typing import List, Optional
  17. _PROMPT = """This will:
  18. - Create and switch to a new branch named '%s'.
  19. - Create a new proposal titled '%s'.
  20. - Create a PR for the proposal.
  21. Continue? (Y/n) """
  22. _LINK_TEMPLATE = """Proposal links (add links as proposal evolves):
  23. - Evolution links:
  24. - [Proposal PR](https://github.com/carbon-language/carbon-lang/pull/%s)
  25. - `[RFC topic](TODO)`
  26. - `[Decision topic](TODO)`
  27. - `[Decision PR](TODO)`
  28. - `[Announcement](TODO)`
  29. - Related links (optional):
  30. - `[Idea topic](TODO)`
  31. - `[TODO](TODO)`
  32. """
  33. def _parse_args(args: Optional[List[str]] = None) -> argparse.Namespace:
  34. """Parses command-line arguments and flags."""
  35. parser = argparse.ArgumentParser(
  36. description="Generates a branch and PR for a new proposal with the "
  37. "specified title."
  38. )
  39. parser.add_argument(
  40. "title",
  41. metavar="TITLE",
  42. help="The title of the proposal.",
  43. )
  44. parser.add_argument(
  45. "--branch",
  46. metavar="BRANCH",
  47. help="The name of the branch. Automatically generated from the title "
  48. "by default.",
  49. )
  50. parser.add_argument(
  51. "--remote",
  52. metavar="REMOTE",
  53. default="origin",
  54. help="The git remote name where the branch will be pushed. Defaults to "
  55. "'origin'.",
  56. )
  57. parser.add_argument(
  58. "--repo_root",
  59. metavar="REPO_ROOT",
  60. default=Path(__file__).parents[2],
  61. help="The repository root, mainly for testing cross-repository. "
  62. "Automatically found by default.",
  63. )
  64. parser.add_argument(
  65. "--branch-start-point",
  66. metavar="BRANCH_START_POINT",
  67. default="trunk",
  68. type=str,
  69. help="The starting point for the new branch.",
  70. )
  71. return parser.parse_args(args=args)
  72. def _calculate_branch(parsed_args: argparse.Namespace) -> str:
  73. """Returns the branch name."""
  74. if parsed_args.branch:
  75. assert isinstance(parsed_args.branch, str)
  76. return parsed_args.branch
  77. # Only use the first 20 chars of the title for branch names.
  78. return "proposal-%s" % (parsed_args.title.lower().replace(" ", "-")[0:20])
  79. def _find_tool(tool: str) -> str:
  80. """Checks if a tool is present."""
  81. tool_path = shutil.which(tool)
  82. if not tool_path:
  83. exit("ERROR: Missing the '%s' command-line tool." % tool)
  84. return tool_path
  85. def _fill_template(template_path: str, title: str, pr_num: int) -> str:
  86. """Fills out template TODO fields."""
  87. with open(template_path) as template_file:
  88. content = template_file.read()
  89. content = re.sub(r"^# TODO\n", "# %s\n" % title, content)
  90. content = re.sub(
  91. r"(https://github.com/[^/]+/[^/]+/pull/)####",
  92. r"\g<1>%d" % pr_num,
  93. content,
  94. )
  95. content = re.sub(r"\n## TODO(?:.|\n)*?(\n## )", r"\1", content)
  96. return content
  97. def _run(
  98. argv: List[str], check: bool = True, get_stdout: bool = False
  99. ) -> Optional[str]:
  100. """Runs a command."""
  101. cmd = " ".join([shlex.quote(x) for x in argv])
  102. print("\n+ RUNNING: %s" % cmd, file=sys.stderr)
  103. stdout_pipe = None
  104. if get_stdout:
  105. stdout_pipe = subprocess.PIPE
  106. p = subprocess.Popen(argv, stdout=stdout_pipe)
  107. stdout, _ = p.communicate()
  108. if get_stdout:
  109. out = stdout.decode("utf-8")
  110. print(out, end="")
  111. if check and p.returncode != 0:
  112. exit("ERROR: Command failed: %s" % cmd)
  113. if get_stdout:
  114. return out
  115. return None
  116. def _run_pr_create(argv: List[str]) -> int:
  117. """Runs a command and returns the PR#."""
  118. out = _run(argv, get_stdout=True)
  119. assert out is not None
  120. match = re.search(
  121. r"^https://github.com/[^/]+/[^/]+/pull/(\d+)$", out, re.MULTILINE
  122. )
  123. if not match:
  124. exit("ERROR: Failed to find PR# in output.")
  125. return int(match.group(1))
  126. def main() -> None:
  127. parsed_args = _parse_args()
  128. # Switch to repo root early for consistent execution.
  129. os.chdir(parsed_args.repo_root)
  130. title = parsed_args.title
  131. branch = _calculate_branch(parsed_args)
  132. # Verify tools are available.
  133. gh_bin = _find_tool("gh")
  134. if Path(".jj").is_dir():
  135. jj_bin = _find_tool("jj")
  136. git_bin = None
  137. else:
  138. git_bin = _find_tool("git")
  139. jj_bin = None
  140. precommit_bin = _find_tool("pre-commit")
  141. # Verify there are no uncommitted changes (jj has no equivalent).
  142. if git_bin:
  143. p = subprocess.run([git_bin, "diff-index", "--quiet", "HEAD", "--"])
  144. if p.returncode != 0:
  145. exit("ERROR: There are uncommitted changes in your git repo.")
  146. # Prompt before proceeding.
  147. response = "?"
  148. while response not in ("y", "n", ""):
  149. response = input(_PROMPT % (branch, title)).lower()
  150. if response == "n":
  151. exit("ERROR: Cancelled")
  152. # Create a proposal branch.
  153. if git_bin:
  154. _run(
  155. [
  156. git_bin,
  157. "switch",
  158. "--create",
  159. branch,
  160. parsed_args.branch_start_point,
  161. ]
  162. )
  163. _run([git_bin, "push", "-u", parsed_args.remote, branch])
  164. else:
  165. assert jj_bin # For mypy.
  166. _run([jj_bin, "new", parsed_args.branch_start_point])
  167. _run([jj_bin, "bookmark", "create", branch])
  168. _run(
  169. [
  170. jj_bin,
  171. "bookmark",
  172. "track",
  173. branch,
  174. "--remote",
  175. parsed_args.remote,
  176. ]
  177. )
  178. # Copy template.md to a temp file.
  179. template_path = "proposals/scripts/template.md"
  180. temp_path = "proposals/new-proposal.tmp.md"
  181. shutil.copyfile(template_path, temp_path)
  182. initial_desc = "Creating new proposal: %s" % title
  183. if git_bin:
  184. _run([git_bin, "add", temp_path])
  185. _run([git_bin, "commit", "-m", initial_desc])
  186. else:
  187. assert jj_bin # For mypy.
  188. _run([jj_bin, "describe", "-m", initial_desc])
  189. # Create a PR with WIP+proposal labels.
  190. if git_bin:
  191. _run([git_bin, "push"])
  192. user = _run([git_bin, "config", "get", "user.name"], get_stdout=True)
  193. else:
  194. assert jj_bin # For mypy.
  195. _run([jj_bin, "git", "push"])
  196. user = _run([jj_bin, "config", "get", "user.name"], get_stdout=True)
  197. assert user # For mypy.
  198. user = user.strip()
  199. pr_num = _run_pr_create(
  200. [
  201. gh_bin,
  202. "pr",
  203. "create",
  204. "--head",
  205. "%s:%s" % (user, branch),
  206. "--draft",
  207. "--label",
  208. "proposal",
  209. "--label",
  210. "proposal draft",
  211. "--repo",
  212. "carbon-language/carbon-lang",
  213. "--title",
  214. title,
  215. "--body",
  216. "TODO: add summary and links here",
  217. ]
  218. )
  219. # Remove the temp file, create p####.md, and fill in PR information.
  220. os.remove(temp_path)
  221. final_path = "proposals/p%04d.md" % pr_num
  222. content = _fill_template(template_path, title, pr_num)
  223. with open(final_path, "w") as final_file:
  224. final_file.write(content)
  225. # Run pre-commit for a ToC update, then push the PR update.
  226. final_desc = "Filling out template with PR %d" % pr_num
  227. if git_bin:
  228. _run([git_bin, "add", temp_path, final_path])
  229. _run([precommit_bin, "run"], check=False)
  230. _run([git_bin, "commit", "--amend", "-m", final_desc])
  231. _run([git_bin, "push", "--force-with-lease"])
  232. else:
  233. assert jj_bin # For mypy.
  234. _run(
  235. [precommit_bin, "run", "--files", "$(jj diff --name-only)"],
  236. check=False,
  237. )
  238. _run([jj_bin, "describe", "-m", final_desc])
  239. _run([jj_bin, "git", "push"])
  240. print(
  241. "\nCreated PR %d for %s. Make changes to:\n %s"
  242. % (pr_num, title, final_path)
  243. )
  244. if __name__ == "__main__":
  245. main()