new_proposal.py 6.9 KB

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