new_proposal.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 typing import List, Optional
  16. _PROMPT = """This will:
  17. - Create and switch to a new branch named '%s'.
  18. - Create a new proposal titled '%s'.
  19. - Create a PR for the proposal.
  20. Continue? (Y/n) """
  21. _LINK_TEMPLATE = """Proposal links (add links as proposal evolves):
  22. - Evolution links:
  23. - [Proposal PR](https://github.com/carbon-language/carbon-lang/pull/%s)
  24. - `[RFC topic](TODO)`
  25. - `[Decision topic](TODO)`
  26. - `[Decision PR](TODO)`
  27. - `[Announcement](TODO)`
  28. - Related links (optional):
  29. - `[Idea topic](TODO)`
  30. - `[TODO](TODO)`
  31. """
  32. def _parse_args(args: Optional[List[str]] = None) -> argparse.Namespace:
  33. """Parses command-line arguments and flags."""
  34. parser = argparse.ArgumentParser(
  35. description="Generates a branch and PR for a new proposal with the "
  36. "specified title."
  37. )
  38. parser.add_argument(
  39. "title",
  40. metavar="TITLE",
  41. help="The title of the proposal.",
  42. )
  43. parser.add_argument(
  44. "--branch",
  45. metavar="BRANCH",
  46. help="The name of the branch. Automatically generated from the title "
  47. "by default.",
  48. )
  49. parser.add_argument(
  50. "--remote",
  51. metavar="REMOTE",
  52. default="origin",
  53. help="The git remote name where the branch will be pushed. Defaults to "
  54. "'origin'.",
  55. )
  56. parser.add_argument(
  57. "--proposals-dir",
  58. metavar="PROPOSALS_DIR",
  59. help="The proposals directory, mainly for testing cross-repository. "
  60. "Automatically found by default.",
  61. )
  62. parser.add_argument(
  63. "--branch-start-point",
  64. metavar="BRANCH_START_POINT",
  65. default="trunk",
  66. type=str,
  67. help="The starting point for the new branch.",
  68. )
  69. return parser.parse_args(args=args)
  70. def _calculate_branch(parsed_args: argparse.Namespace) -> str:
  71. """Returns the branch name."""
  72. if parsed_args.branch:
  73. assert isinstance(parsed_args.branch, str)
  74. return parsed_args.branch
  75. # Only use the first 20 chars of the title for branch names.
  76. return "proposal-%s" % (parsed_args.title.lower().replace(" ", "-")[0:20])
  77. def _find_tool(tool: str) -> str:
  78. """Checks if a tool is present."""
  79. tool_path = shutil.which(tool)
  80. if not tool_path:
  81. exit("ERROR: Missing the '%s' command-line tool." % tool)
  82. return tool_path
  83. def _fill_template(template_path: str, title: str, pr_num: int) -> str:
  84. """Fills out template TODO fields."""
  85. with open(template_path) as template_file:
  86. content = template_file.read()
  87. content = re.sub(r"^# TODO\n", "# %s\n" % title, content)
  88. content = re.sub(
  89. r"(https://github.com/[^/]+/[^/]+/pull/)####",
  90. r"\g<1>%d" % pr_num,
  91. content,
  92. )
  93. content = re.sub(r"\n## TODO(?:.|\n)*?(\n## )", r"\1", content)
  94. return content
  95. def _get_proposals_dir(parsed_args: argparse.Namespace) -> str:
  96. """Returns the path to the proposals directory."""
  97. if parsed_args.proposals_dir:
  98. assert isinstance(parsed_args.proposals_dir, str)
  99. return parsed_args.proposals_dir
  100. return os.path.realpath(
  101. os.path.join(os.path.dirname(__file__), "../../proposals")
  102. )
  103. def _run(
  104. argv: List[str], check: bool = True, get_stdout: bool = False
  105. ) -> Optional[str]:
  106. """Runs a command."""
  107. cmd = " ".join([shlex.quote(x) for x in argv])
  108. print("\n+ RUNNING: %s" % cmd, file=sys.stderr)
  109. stdout_pipe = None
  110. if get_stdout:
  111. stdout_pipe = subprocess.PIPE
  112. p = subprocess.Popen(argv, stdout=stdout_pipe)
  113. stdout, _ = p.communicate()
  114. if get_stdout:
  115. out = stdout.decode("utf-8")
  116. print(out, end="")
  117. if check and p.returncode != 0:
  118. exit("ERROR: Command failed: %s" % cmd)
  119. if get_stdout:
  120. return out
  121. return None
  122. def _run_pr_create(argv: List[str]) -> int:
  123. """Runs a command and returns the PR#."""
  124. out = _run(argv, get_stdout=True)
  125. assert out is not None
  126. match = re.search(
  127. r"^https://github.com/[^/]+/[^/]+/pull/(\d+)$", out, re.MULTILINE
  128. )
  129. if not match:
  130. exit("ERROR: Failed to find PR# in output.")
  131. return int(match.group(1))
  132. def main() -> None:
  133. parsed_args = _parse_args()
  134. title = parsed_args.title
  135. branch = _calculate_branch(parsed_args)
  136. # Verify tools are available.
  137. gh_bin = _find_tool("gh")
  138. git_bin = _find_tool("git")
  139. precommit_bin = _find_tool("pre-commit")
  140. # Ensure a good working directory.
  141. proposals_dir = _get_proposals_dir(parsed_args)
  142. os.chdir(proposals_dir)
  143. # Verify there are no uncommitted changes.
  144. p = subprocess.run([git_bin, "diff-index", "--quiet", "HEAD", "--"])
  145. if p.returncode != 0:
  146. exit("ERROR: There are uncommitted changes in your git repo.")
  147. # Prompt before proceeding.
  148. response = "?"
  149. while response not in ("y", "n", ""):
  150. response = input(_PROMPT % (branch, title)).lower()
  151. if response == "n":
  152. exit("ERROR: Cancelled")
  153. # Create a proposal branch.
  154. _run(
  155. [git_bin, "switch", "--create", branch, parsed_args.branch_start_point]
  156. )
  157. _run([git_bin, "push", "-u", parsed_args.remote, branch])
  158. # Copy template.md to a temp file.
  159. template_path = os.path.join(proposals_dir, "scripts/template.md")
  160. temp_path = os.path.join(proposals_dir, "new-proposal.tmp.md")
  161. shutil.copyfile(template_path, temp_path)
  162. _run([git_bin, "add", temp_path])
  163. _run([git_bin, "commit", "-m", "Creating new proposal: %s" % title])
  164. # Create a PR with WIP+proposal labels.
  165. _run([git_bin, "push"])
  166. pr_num = _run_pr_create(
  167. [
  168. gh_bin,
  169. "pr",
  170. "create",
  171. "--draft",
  172. "--label",
  173. "proposal",
  174. "--label",
  175. "proposal draft",
  176. "--repo",
  177. "carbon-language/carbon-lang",
  178. "--title",
  179. title,
  180. "--body",
  181. "TODO: add summary and links here",
  182. ]
  183. )
  184. # Remove the temp file, create p####.md, and fill in PR information.
  185. os.remove(temp_path)
  186. final_path = os.path.join(proposals_dir, "p%04d.md" % pr_num)
  187. content = _fill_template(template_path, title, pr_num)
  188. with open(final_path, "w") as final_file:
  189. final_file.write(content)
  190. _run([git_bin, "add", temp_path, final_path])
  191. _run([precommit_bin, "run"], check=False) # Needs a ToC update.
  192. _run([git_bin, "add", final_path, os.path.join(proposals_dir, "README.md")])
  193. _run(
  194. [
  195. git_bin,
  196. "commit",
  197. "--amend",
  198. "-m",
  199. "Filling out template with PR %d" % pr_num,
  200. ]
  201. )
  202. # Push the PR update.
  203. _run([git_bin, "push", "--force-with-lease"])
  204. print(
  205. "\nCreated PR %d for %s. Make changes to:\n %s"
  206. % (pr_num, title, final_path)
  207. )
  208. if __name__ == "__main__":
  209. main()