split_cl.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. #!/usr/bin/env python3
  2. # Copyright 2017 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Splits a branch into smaller branches and uploads CLs."""
  6. from __future__ import print_function
  7. import collections
  8. import os
  9. import re
  10. import subprocess2
  11. import sys
  12. import gclient_utils
  13. import git_footers
  14. import scm
  15. import git_common as git
  16. # If a call to `git cl split` will generate more than this number of CLs, the
  17. # command will prompt the user to make sure they know what they're doing. Large
  18. # numbers of CLs generated by `git cl split` have caused infrastructure issues
  19. # in the past.
  20. CL_SPLIT_FORCE_LIMIT = 10
  21. # The maximum number of top reviewers to list. `git cl split` may send many CLs
  22. # to a single reviewer, so the top reviewers with the most CLs sent to them
  23. # will be listed.
  24. CL_SPLIT_TOP_REVIEWERS = 5
  25. FilesAndOwnersDirectory = collections.namedtuple("FilesAndOwnersDirectory",
  26. "files owners_directories")
  27. def EnsureInGitRepository():
  28. """Throws an exception if the current directory is not a git repository."""
  29. git.run('rev-parse')
  30. def CreateBranchForDirectories(prefix, directories, upstream):
  31. """Creates a branch named |prefix| + "_" + |directories[0]| + "_split".
  32. Return false if the branch already exists. |upstream| is used as upstream for
  33. the created branch.
  34. """
  35. existing_branches = set(git.branches(use_limit=False))
  36. branch_name = prefix + '_' + directories[0] + '_split'
  37. if branch_name in existing_branches:
  38. return False
  39. git.run('checkout', '-t', upstream, '-b', branch_name)
  40. return True
  41. def FormatDirectoriesForPrinting(directories, prefix=None):
  42. """Formats directory list for printing
  43. Uses dedicated format for single-item list."""
  44. prefixed = directories
  45. if prefix:
  46. prefixed = [(prefix + d) for d in directories]
  47. return str(prefixed) if len(prefixed) > 1 else str(prefixed[0])
  48. def FormatDescriptionOrComment(txt, directories):
  49. """Replaces $directory with |directories| in |txt|."""
  50. to_insert = FormatDirectoriesForPrinting(directories, prefix='/')
  51. return txt.replace('$directory', to_insert)
  52. def AddUploadedByGitClSplitToDescription(description):
  53. """Adds a 'This CL was uploaded by git cl split.' line to |description|.
  54. The line is added before footers, or at the end of |description| if it has no
  55. footers.
  56. """
  57. split_footers = git_footers.split_footers(description)
  58. lines = split_footers[0]
  59. if lines[-1] and not lines[-1].isspace():
  60. lines = lines + ['']
  61. lines = lines + ['This CL was uploaded by git cl split.']
  62. if split_footers[1]:
  63. lines += [''] + split_footers[1]
  64. return '\n'.join(lines)
  65. def UploadCl(refactor_branch, refactor_branch_upstream, directories, files,
  66. description, comment, reviewers, changelist, cmd_upload,
  67. cq_dry_run, enable_auto_submit, topic, repository_root):
  68. """Uploads a CL with all changes to |files| in |refactor_branch|.
  69. Args:
  70. refactor_branch: Name of the branch that contains the changes to upload.
  71. refactor_branch_upstream: Name of the upstream of |refactor_branch|.
  72. directories: Paths to the directories that contain the OWNERS files for
  73. which to upload a CL.
  74. files: List of AffectedFile instances to include in the uploaded CL.
  75. description: Description of the uploaded CL.
  76. comment: Comment to post on the uploaded CL.
  77. reviewers: A set of reviewers for the CL.
  78. changelist: The Changelist class.
  79. cmd_upload: The function associated with the git cl upload command.
  80. cq_dry_run: If CL uploads should also do a cq dry run.
  81. enable_auto_submit: If CL uploads should also enable auto submit.
  82. topic: Topic to associate with uploaded CLs.
  83. """
  84. # Create a branch.
  85. if not CreateBranchForDirectories(refactor_branch, directories,
  86. refactor_branch_upstream):
  87. print('Skipping ' + FormatDirectoriesForPrinting(directories) +
  88. ' for which a branch already exists.')
  89. return
  90. # Checkout all changes to files in |files|.
  91. deleted_files = []
  92. modified_files = []
  93. for action, f in files:
  94. abspath = os.path.abspath(os.path.join(repository_root, f))
  95. if action == 'D':
  96. deleted_files.append(abspath)
  97. else:
  98. modified_files.append(abspath)
  99. if deleted_files:
  100. git.run(*['rm'] + deleted_files)
  101. if modified_files:
  102. git.run(*['checkout', refactor_branch, '--'] + modified_files)
  103. # Commit changes. The temporary file is created with delete=False so that it
  104. # can be deleted manually after git has read it rather than automatically
  105. # when it is closed.
  106. with gclient_utils.temporary_file() as tmp_file:
  107. gclient_utils.FileWrite(
  108. tmp_file, FormatDescriptionOrComment(description, directories))
  109. git.run('commit', '-F', tmp_file)
  110. # Upload a CL.
  111. upload_args = ['-f']
  112. if reviewers:
  113. upload_args.extend(['-r', ','.join(sorted(reviewers))])
  114. if cq_dry_run:
  115. upload_args.append('--cq-dry-run')
  116. if not comment:
  117. upload_args.append('--send-mail')
  118. if enable_auto_submit:
  119. upload_args.append('--enable-auto-submit')
  120. if topic:
  121. upload_args.append('--topic={}'.format(topic))
  122. print('Uploading CL for ' + FormatDirectoriesForPrinting(directories) +
  123. '...')
  124. ret = cmd_upload(upload_args)
  125. if ret != 0:
  126. print('Uploading failed.')
  127. print('Note: git cl split has built-in resume capabilities.')
  128. print('Delete ' + git.current_branch() +
  129. ' then run git cl split again to resume uploading.')
  130. if comment:
  131. changelist().AddComment(FormatDescriptionOrComment(
  132. comment, directories),
  133. publish=True)
  134. def GetFilesSplitByOwners(files, max_depth):
  135. """Returns a map of files split by OWNERS file.
  136. Returns:
  137. A map where keys are paths to directories containing an OWNERS file and
  138. values are lists of files sharing an OWNERS file.
  139. """
  140. files_split_by_owners = {}
  141. for action, path in files:
  142. # normpath() is important to normalize separators here, in prepration
  143. # for str.split() before. It would be nicer to use something like
  144. # pathlib here but alas...
  145. dir_with_owners = os.path.normpath(os.path.dirname(path))
  146. if max_depth >= 1:
  147. dir_with_owners = os.path.join(
  148. *dir_with_owners.split(os.path.sep)[:max_depth])
  149. # Find the closest parent directory with an OWNERS file.
  150. while (dir_with_owners not in files_split_by_owners
  151. and not os.path.isfile(os.path.join(dir_with_owners, 'OWNERS'))):
  152. dir_with_owners = os.path.dirname(dir_with_owners)
  153. files_split_by_owners.setdefault(dir_with_owners, []).append(
  154. (action, path))
  155. return files_split_by_owners
  156. def PrintClInfo(cl_index, num_cls, directories, file_paths, description,
  157. reviewers, enable_auto_submit, topic):
  158. """Prints info about a CL.
  159. Args:
  160. cl_index: The index of this CL in the list of CLs to upload.
  161. num_cls: The total number of CLs that will be uploaded.
  162. directories: Paths to directories that contains the OWNERS files for which
  163. to upload a CL.
  164. file_paths: A list of files in this CL.
  165. description: The CL description.
  166. reviewers: A set of reviewers for this CL.
  167. enable_auto_submit: If the CL should also have auto submit enabled.
  168. topic: Topic to set for this CL.
  169. """
  170. description_lines = FormatDescriptionOrComment(description,
  171. directories).splitlines()
  172. indented_description = '\n'.join([' ' + l for l in description_lines])
  173. print('CL {}/{}'.format(cl_index, num_cls))
  174. print('Paths: {}'.format(FormatDirectoriesForPrinting(directories)))
  175. print('Reviewers: {}'.format(', '.join(reviewers)))
  176. print('Auto-Submit: {}'.format(enable_auto_submit))
  177. print('Topic: {}'.format(topic))
  178. print('\n' + indented_description + '\n')
  179. print('\n'.join(file_paths))
  180. print()
  181. def SplitCl(description_file, comment_file, changelist, cmd_upload, dry_run,
  182. cq_dry_run, enable_auto_submit, max_depth, topic, repository_root):
  183. """"Splits a branch into smaller branches and uploads CLs.
  184. Args:
  185. description_file: File containing the description of uploaded CLs.
  186. comment_file: File containing the comment of uploaded CLs.
  187. changelist: The Changelist class.
  188. cmd_upload: The function associated with the git cl upload command.
  189. dry_run: Whether this is a dry run (no branches or CLs created).
  190. cq_dry_run: If CL uploads should also do a cq dry run.
  191. enable_auto_submit: If CL uploads should also enable auto submit.
  192. max_depth: The maximum directory depth to search for OWNERS files. A value
  193. less than 1 means no limit.
  194. topic: Topic to associate with split CLs.
  195. Returns:
  196. 0 in case of success. 1 in case of error.
  197. """
  198. description = AddUploadedByGitClSplitToDescription(
  199. gclient_utils.FileRead(description_file))
  200. comment = gclient_utils.FileRead(comment_file) if comment_file else None
  201. try:
  202. EnsureInGitRepository()
  203. cl = changelist()
  204. upstream = cl.GetCommonAncestorWithUpstream()
  205. files = [
  206. (action.strip(), f)
  207. for action, f in scm.GIT.CaptureStatus(repository_root, upstream)
  208. ]
  209. if not files:
  210. print('Cannot split an empty CL.')
  211. return 1
  212. author = git.run('config', 'user.email').strip() or None
  213. refactor_branch = git.current_branch()
  214. assert refactor_branch, "Can't run from detached branch."
  215. refactor_branch_upstream = git.upstream(refactor_branch)
  216. assert refactor_branch_upstream, \
  217. "Branch %s must have an upstream." % refactor_branch
  218. if not CheckDescriptionBugLink(description):
  219. return 0
  220. files_split_by_reviewers = SelectReviewersForFiles(
  221. cl, author, files, max_depth)
  222. num_cls = len(files_split_by_reviewers)
  223. print('Will split current branch (' + refactor_branch + ') into ' +
  224. str(num_cls) + ' CLs.\n')
  225. if cq_dry_run and num_cls > CL_SPLIT_FORCE_LIMIT:
  226. print(
  227. 'This will generate "%r" CLs. This many CLs can potentially'
  228. ' generate too much load on the build infrastructure. Please'
  229. ' email infra-dev@chromium.org to ensure that this won\'t break'
  230. ' anything. The infra team reserves the right to cancel your'
  231. ' jobs if they are overloading the CQ.' % num_cls)
  232. answer = gclient_utils.AskForData('Proceed? (y/n):')
  233. if answer.lower() != 'y':
  234. return 0
  235. cls_per_reviewer = collections.defaultdict(int)
  236. for cl_index, (reviewers, cl_info) in \
  237. enumerate(files_split_by_reviewers.items(), 1):
  238. # Convert reviewers from tuple to set.
  239. reviewer_set = set(reviewers)
  240. if dry_run:
  241. file_paths = [f for _, f in cl_info.files]
  242. PrintClInfo(cl_index, num_cls, cl_info.owners_directories,
  243. file_paths, description, reviewer_set,
  244. enable_auto_submit, topic)
  245. else:
  246. UploadCl(refactor_branch, refactor_branch_upstream,
  247. cl_info.owners_directories, cl_info.files, description,
  248. comment, reviewer_set, changelist, cmd_upload,
  249. cq_dry_run, enable_auto_submit, topic, repository_root)
  250. for reviewer in reviewers:
  251. cls_per_reviewer[reviewer] += 1
  252. # List the top reviewers that will be sent the most CLs as a result of
  253. # the split.
  254. reviewer_rankings = sorted(cls_per_reviewer.items(),
  255. key=lambda item: item[1],
  256. reverse=True)
  257. print('The top reviewers are:')
  258. for reviewer, count in reviewer_rankings[:CL_SPLIT_TOP_REVIEWERS]:
  259. print(f' {reviewer}: {count} CLs')
  260. # Go back to the original branch.
  261. git.run('checkout', refactor_branch)
  262. except subprocess2.CalledProcessError as cpe:
  263. sys.stderr.write(cpe.stderr)
  264. return 1
  265. return 0
  266. def CheckDescriptionBugLink(description):
  267. """Verifies that the description contains a bug link.
  268. Examples:
  269. Bug: 123
  270. Bug: chromium:456
  271. Prompts user if the description does not contain a bug link.
  272. """
  273. bug_pattern = re.compile(r"^Bug:\s*(?:[a-zA-Z]+:)?[0-9]+", re.MULTILINE)
  274. matches = re.findall(bug_pattern, description)
  275. answer = 'y'
  276. if not matches:
  277. answer = gclient_utils.AskForData(
  278. 'Description does not include a bug link. Proceed? (y/n):')
  279. return answer.lower() == 'y'
  280. def SelectReviewersForFiles(cl, author, files, max_depth):
  281. """Selects reviewers for passed-in files
  282. Args:
  283. cl: Changelist class instance
  284. author: Email of person running 'git cl split'
  285. files: List of files
  286. max_depth: The maximum directory depth to search for OWNERS files. A value
  287. less than 1 means no limit.
  288. """
  289. info_split_by_owners = GetFilesSplitByOwners(files, max_depth)
  290. info_split_by_reviewers = {}
  291. for (directory, split_files) in info_split_by_owners.items():
  292. # Use '/' as a path separator in the branch name and the CL description
  293. # and comment.
  294. directory = directory.replace(os.path.sep, '/')
  295. file_paths = [f for _, f in split_files]
  296. # Convert reviewers list to tuple in order to use reviewers as key to
  297. # dictionary.
  298. reviewers = tuple(
  299. cl.owners_client.SuggestOwners(
  300. file_paths, exclude=[author, cl.owners_client.EVERYONE]))
  301. if not reviewers in info_split_by_reviewers:
  302. info_split_by_reviewers[reviewers] = FilesAndOwnersDirectory([], [])
  303. info_split_by_reviewers[reviewers].files.extend(split_files)
  304. info_split_by_reviewers[reviewers].owners_directories.append(directory)
  305. return info_split_by_reviewers