blob: 16cb8f25defaef85e4ca62e0dd67885fc31e81c2 [file] [log] [blame]
Josip Sokcevic4de5dea2022-03-23 21:15:14 +00001#!/usr/bin/env python3
Francois Dorayd42c6812017-05-30 15:10:20 -04002# 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
6"""Splits a branch into smaller branches and uploads CLs."""
7
Raul Tambre80ee78e2019-05-06 22:41:05 +00008from __future__ import print_function
9
Francois Dorayd42c6812017-05-30 15:10:20 -040010import collections
11import os
12import re
13import subprocess2
14import sys
Francois Dorayd42c6812017-05-30 15:10:20 -040015
Edward Lemur1773f372020-02-22 00:27:14 +000016import gclient_utils
Francois Dorayd42c6812017-05-30 15:10:20 -040017import git_footers
Josip Sokcevic7958e302023-03-01 23:02:21 +000018import scm
Francois Dorayd42c6812017-05-30 15:10:20 -040019
20import git_common as git
21
22
Stephen Martinisf53f82c2018-09-07 20:58:05 +000023# If a call to `git cl split` will generate more than this number of CLs, the
24# command will prompt the user to make sure they know what they're doing. Large
25# numbers of CLs generated by `git cl split` have caused infrastructure issues
26# in the past.
27CL_SPLIT_FORCE_LIMIT = 10
28
Anne Redullab5509952023-07-27 01:27:02 +000029# The maximum number of top reviewers to list. `git cl split` may send many CLs
30# to a single reviewer, so the top reviewers with the most CLs sent to them
31# will be listed.
32CL_SPLIT_TOP_REVIEWERS = 5
33
Peter Kotwicz70d971a2023-08-01 22:26:14 +000034FilesAndOwnersDirectory = collections.namedtuple("FilesAndOwnersDirectory",
35 "files owners_directories")
36
Stephen Martinisf53f82c2018-09-07 20:58:05 +000037
Francois Dorayd42c6812017-05-30 15:10:20 -040038def EnsureInGitRepository():
39 """Throws an exception if the current directory is not a git repository."""
40 git.run('rev-parse')
41
42
Peter Kotwicz70d971a2023-08-01 22:26:14 +000043def CreateBranchForDirectories(prefix, directories, upstream):
44 """Creates a branch named |prefix| + "_" + |directories[0]| + "_split".
Francois Dorayd42c6812017-05-30 15:10:20 -040045
46 Return false if the branch already exists. |upstream| is used as upstream for
47 the created branch.
48 """
49 existing_branches = set(git.branches(use_limit = False))
Peter Kotwicz70d971a2023-08-01 22:26:14 +000050 branch_name = prefix + '_' + directories[0] + '_split'
Francois Dorayd42c6812017-05-30 15:10:20 -040051 if branch_name in existing_branches:
52 return False
53 git.run('checkout', '-t', upstream, '-b', branch_name)
54 return True
55
56
Peter Kotwicz70d971a2023-08-01 22:26:14 +000057def FormatDirectoriesForPrinting(directories, prefix=None):
58 """Formats directory list for printing
59
60 Uses dedicated format for single-item list."""
61
62 prefixed = directories
63 if prefix:
64 prefixed = [(prefix + d) for d in directories]
65
66 return str(prefixed) if len(prefixed) > 1 else str(prefixed[0])
67
68
69def FormatDescriptionOrComment(txt, directories):
70 """Replaces $directory with |directories| in |txt|."""
71 to_insert = FormatDirectoriesForPrinting(directories, prefix='/')
72 return txt.replace('$directory', to_insert)
Francois Dorayd42c6812017-05-30 15:10:20 -040073
74
75def AddUploadedByGitClSplitToDescription(description):
76 """Adds a 'This CL was uploaded by git cl split.' line to |description|.
77
78 The line is added before footers, or at the end of |description| if it has no
79 footers.
80 """
81 split_footers = git_footers.split_footers(description)
82 lines = split_footers[0]
Song Fangzhen534f5052021-06-23 08:51:34 +000083 if lines[-1] and not lines[-1].isspace():
Francois Dorayd42c6812017-05-30 15:10:20 -040084 lines = lines + ['']
85 lines = lines + ['This CL was uploaded by git cl split.']
86 if split_footers[1]:
87 lines += [''] + split_footers[1]
88 return '\n'.join(lines)
89
90
Peter Kotwicz70d971a2023-08-01 22:26:14 +000091def UploadCl(refactor_branch, refactor_branch_upstream, directories, files,
Edward Lemurac5c55f2020-02-29 00:17:16 +000092 description, comment, reviewers, changelist, cmd_upload,
Rachael Newitt03e49122023-06-28 21:39:21 +000093 cq_dry_run, enable_auto_submit, topic, repository_root):
Francois Dorayd42c6812017-05-30 15:10:20 -040094 """Uploads a CL with all changes to |files| in |refactor_branch|.
95
96 Args:
97 refactor_branch: Name of the branch that contains the changes to upload.
98 refactor_branch_upstream: Name of the upstream of |refactor_branch|.
Peter Kotwicz70d971a2023-08-01 22:26:14 +000099 directories: Paths to the directories that contain the OWNERS files for
100 which to upload a CL.
Francois Dorayd42c6812017-05-30 15:10:20 -0400101 files: List of AffectedFile instances to include in the uploaded CL.
Francois Dorayd42c6812017-05-30 15:10:20 -0400102 description: Description of the uploaded CL.
103 comment: Comment to post on the uploaded CL.
Edward Lemurac5c55f2020-02-29 00:17:16 +0000104 reviewers: A set of reviewers for the CL.
Francois Dorayd42c6812017-05-30 15:10:20 -0400105 changelist: The Changelist class.
106 cmd_upload: The function associated with the git cl upload command.
Stephen Martiniscb326682018-08-29 21:06:30 +0000107 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +0000108 enable_auto_submit: If CL uploads should also enable auto submit.
Rachael Newitt03e49122023-06-28 21:39:21 +0000109 topic: Topic to associate with uploaded CLs.
Francois Dorayd42c6812017-05-30 15:10:20 -0400110 """
Francois Dorayd42c6812017-05-30 15:10:20 -0400111 # Create a branch.
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000112 if not CreateBranchForDirectories(refactor_branch, directories,
113 refactor_branch_upstream):
114 print('Skipping ' + FormatDirectoriesForPrinting(directories) +
115 ' for which a branch already exists.')
Francois Dorayd42c6812017-05-30 15:10:20 -0400116 return
117
118 # Checkout all changes to files in |files|.
Edward Lemur2c62b332020-03-12 22:12:33 +0000119 deleted_files = []
120 modified_files = []
121 for action, f in files:
122 abspath = os.path.abspath(os.path.join(repository_root, f))
123 if action == 'D':
124 deleted_files.append(abspath)
125 else:
126 modified_files.append(abspath)
127
Francois Dorayd42c6812017-05-30 15:10:20 -0400128 if deleted_files:
129 git.run(*['rm'] + deleted_files)
Francois Dorayd42c6812017-05-30 15:10:20 -0400130 if modified_files:
131 git.run(*['checkout', refactor_branch, '--'] + modified_files)
132
133 # Commit changes. The temporary file is created with delete=False so that it
134 # can be deleted manually after git has read it rather than automatically
135 # when it is closed.
Edward Lemur1773f372020-02-22 00:27:14 +0000136 with gclient_utils.temporary_file() as tmp_file:
137 gclient_utils.FileWrite(
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000138 tmp_file, FormatDescriptionOrComment(description, directories))
Edward Lemur1773f372020-02-22 00:27:14 +0000139 git.run('commit', '-F', tmp_file)
Francois Dorayd42c6812017-05-30 15:10:20 -0400140
141 # Upload a CL.
Anthony Politoc08c71b2020-08-26 23:45:30 +0000142 upload_args = ['-f']
143 if reviewers:
Peter Kotwiczcaeef7b2023-08-24 02:34:52 +0000144 upload_args.extend(['-r', ','.join(sorted(reviewers))])
Stephen Martiniscb326682018-08-29 21:06:30 +0000145 if cq_dry_run:
146 upload_args.append('--cq-dry-run')
Francois Dorayd42c6812017-05-30 15:10:20 -0400147 if not comment:
Aaron Gablee5adf612017-07-14 10:43:58 -0700148 upload_args.append('--send-mail')
Takuto Ikuta51eca592019-02-14 19:40:52 +0000149 if enable_auto_submit:
150 upload_args.append('--enable-auto-submit')
Rachael Newitt03e49122023-06-28 21:39:21 +0000151 if topic:
152 upload_args.append('--topic={}'.format(topic))
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000153 print('Uploading CL for ' + FormatDirectoriesForPrinting(directories) + '...')
Olivier Li06145912021-05-12 23:59:24 +0000154
155 ret = cmd_upload(upload_args)
156 if ret != 0:
Peter Kotwicz729de572023-08-03 03:20:22 +0000157 print('Uploading failed.')
Olivier Li06145912021-05-12 23:59:24 +0000158 print('Note: git cl split has built-in resume capabilities.')
159 print('Delete ' + git.current_branch() +
160 ' then run git cl split again to resume uploading.')
161
Francois Dorayd42c6812017-05-30 15:10:20 -0400162 if comment:
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000163 changelist().AddComment(FormatDescriptionOrComment(comment, directories),
Edward Lemurac5c55f2020-02-29 00:17:16 +0000164 publish=True)
Francois Dorayd42c6812017-05-30 15:10:20 -0400165
166
Daniel Cheng403c44e2022-10-05 22:24:58 +0000167def GetFilesSplitByOwners(files, max_depth):
Francois Dorayd42c6812017-05-30 15:10:20 -0400168 """Returns a map of files split by OWNERS file.
169
170 Returns:
171 A map where keys are paths to directories containing an OWNERS file and
172 values are lists of files sharing an OWNERS file.
173 """
Edward Lesmesb1174d72021-02-02 20:31:34 +0000174 files_split_by_owners = {}
Edward Lesmes17ffd982020-03-31 17:33:16 +0000175 for action, path in files:
Daniel Cheng403c44e2022-10-05 22:24:58 +0000176 # normpath() is important to normalize separators here, in prepration for
177 # str.split() before. It would be nicer to use something like pathlib here
178 # but alas...
179 dir_with_owners = os.path.normpath(os.path.dirname(path))
180 if max_depth >= 1:
181 dir_with_owners = os.path.join(
182 *dir_with_owners.split(os.path.sep)[:max_depth])
Edward Lesmesb1174d72021-02-02 20:31:34 +0000183 # Find the closest parent directory with an OWNERS file.
184 while (dir_with_owners not in files_split_by_owners
185 and not os.path.isfile(os.path.join(dir_with_owners, 'OWNERS'))):
186 dir_with_owners = os.path.dirname(dir_with_owners)
187 files_split_by_owners.setdefault(dir_with_owners, []).append((action, path))
Edward Lemurac5c55f2020-02-29 00:17:16 +0000188 return files_split_by_owners
Francois Dorayd42c6812017-05-30 15:10:20 -0400189
190
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000191def PrintClInfo(cl_index, num_cls, directories, file_paths, description,
Anne Redulla072d06e2023-07-06 23:12:16 +0000192 reviewers, enable_auto_submit, topic):
Chris Watkinsba28e462017-12-13 11:22:17 +1100193 """Prints info about a CL.
194
195 Args:
196 cl_index: The index of this CL in the list of CLs to upload.
197 num_cls: The total number of CLs that will be uploaded.
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000198 directories: Paths to directories that contains the OWNERS files for which
Chris Watkinsba28e462017-12-13 11:22:17 +1100199 to upload a CL.
200 file_paths: A list of files in this CL.
201 description: The CL description.
Edward Lemurac5c55f2020-02-29 00:17:16 +0000202 reviewers: A set of reviewers for this CL.
Anne Redulla072d06e2023-07-06 23:12:16 +0000203 enable_auto_submit: If the CL should also have auto submit enabled.
Rachael Newitt03e49122023-06-28 21:39:21 +0000204 topic: Topic to set for this CL.
Chris Watkinsba28e462017-12-13 11:22:17 +1100205 """
Edward Lemurac5c55f2020-02-29 00:17:16 +0000206 description_lines = FormatDescriptionOrComment(description,
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000207 directories).splitlines()
Chris Watkinsba28e462017-12-13 11:22:17 +1100208 indented_description = '\n'.join([' ' + l for l in description_lines])
209
Raul Tambre80ee78e2019-05-06 22:41:05 +0000210 print('CL {}/{}'.format(cl_index, num_cls))
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000211 print('Paths: {}'.format(FormatDirectoriesForPrinting(directories)))
Edward Lemurac5c55f2020-02-29 00:17:16 +0000212 print('Reviewers: {}'.format(', '.join(reviewers)))
Anne Redulla072d06e2023-07-06 23:12:16 +0000213 print('Auto-Submit: {}'.format(enable_auto_submit))
Rachael Newitt03e49122023-06-28 21:39:21 +0000214 print('Topic: {}'.format(topic))
Raul Tambre80ee78e2019-05-06 22:41:05 +0000215 print('\n' + indented_description + '\n')
216 print('\n'.join(file_paths))
217 print()
Chris Watkinsba28e462017-12-13 11:22:17 +1100218
219
Stephen Martiniscb326682018-08-29 21:06:30 +0000220def SplitCl(description_file, comment_file, changelist, cmd_upload, dry_run,
Rachael Newitt03e49122023-06-28 21:39:21 +0000221 cq_dry_run, enable_auto_submit, max_depth, topic, repository_root):
Francois Dorayd42c6812017-05-30 15:10:20 -0400222 """"Splits a branch into smaller branches and uploads CLs.
223
224 Args:
225 description_file: File containing the description of uploaded CLs.
226 comment_file: File containing the comment of uploaded CLs.
227 changelist: The Changelist class.
228 cmd_upload: The function associated with the git cl upload command.
Chris Watkinsba28e462017-12-13 11:22:17 +1100229 dry_run: Whether this is a dry run (no branches or CLs created).
Stephen Martiniscb326682018-08-29 21:06:30 +0000230 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +0000231 enable_auto_submit: If CL uploads should also enable auto submit.
Daniel Cheng403c44e2022-10-05 22:24:58 +0000232 max_depth: The maximum directory depth to search for OWNERS files. A value
233 less than 1 means no limit.
Rachael Newitt03e49122023-06-28 21:39:21 +0000234 topic: Topic to associate with split CLs.
Francois Dorayd42c6812017-05-30 15:10:20 -0400235
236 Returns:
237 0 in case of success. 1 in case of error.
238 """
Edward Lesmesb1174d72021-02-02 20:31:34 +0000239 description = AddUploadedByGitClSplitToDescription(
240 gclient_utils.FileRead(description_file))
241 comment = gclient_utils.FileRead(comment_file) if comment_file else None
Francois Dorayd42c6812017-05-30 15:10:20 -0400242
243 try:
Chris Watkinsba28e462017-12-13 11:22:17 +1100244 EnsureInGitRepository()
Francois Dorayd42c6812017-05-30 15:10:20 -0400245
246 cl = changelist()
Edward Lemur2c62b332020-03-12 22:12:33 +0000247 upstream = cl.GetCommonAncestorWithUpstream()
248 files = [
249 (action.strip(), f)
250 for action, f in scm.GIT.CaptureStatus(repository_root, upstream)
251 ]
Francois Dorayd42c6812017-05-30 15:10:20 -0400252
253 if not files:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000254 print('Cannot split an empty CL.')
Francois Dorayd42c6812017-05-30 15:10:20 -0400255 return 1
256
257 author = git.run('config', 'user.email').strip() or None
258 refactor_branch = git.current_branch()
Gabriel Charette09baacd2017-11-09 13:30:41 -0500259 assert refactor_branch, "Can't run from detached branch."
Francois Dorayd42c6812017-05-30 15:10:20 -0400260 refactor_branch_upstream = git.upstream(refactor_branch)
Gabriel Charette09baacd2017-11-09 13:30:41 -0500261 assert refactor_branch_upstream, \
262 "Branch %s must have an upstream." % refactor_branch
Francois Dorayd42c6812017-05-30 15:10:20 -0400263
Peter Kotwiczcaeef7b2023-08-24 02:34:52 +0000264 if not CheckDescriptionBugLink(description):
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000265 return 0
Francois Dorayd42c6812017-05-30 15:10:20 -0400266
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000267 files_split_by_reviewers = SelectReviewersForFiles(cl, author, files,
268 max_depth)
269
270 num_cls = len(files_split_by_reviewers)
Edward Lemurac5c55f2020-02-29 00:17:16 +0000271 print('Will split current branch (' + refactor_branch + ') into ' +
272 str(num_cls) + ' CLs.\n')
Stephen Martinisf53f82c2018-09-07 20:58:05 +0000273 if cq_dry_run and num_cls > CL_SPLIT_FORCE_LIMIT:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000274 print(
Stephen Martiniscb326682018-08-29 21:06:30 +0000275 'This will generate "%r" CLs. This many CLs can potentially generate'
276 ' too much load on the build infrastructure. Please email'
277 ' infra-dev@chromium.org to ensure that this won\'t break anything.'
278 ' The infra team reserves the right to cancel your jobs if they are'
Raul Tambre80ee78e2019-05-06 22:41:05 +0000279 ' overloading the CQ.' % num_cls)
Edward Lesmesae3586b2020-03-23 21:21:14 +0000280 answer = gclient_utils.AskForData('Proceed? (y/n):')
Stephen Martiniscb326682018-08-29 21:06:30 +0000281 if answer.lower() != 'y':
282 return 0
Francois Dorayd42c6812017-05-30 15:10:20 -0400283
Anne Redullab5509952023-07-27 01:27:02 +0000284 cls_per_reviewer = collections.defaultdict(int)
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000285 for cl_index, (reviewers, cl_info) in \
286 enumerate(files_split_by_reviewers.items(), 1):
287 # Convert reviewers from tuple to set.
288 reviewer_set = set(reviewers)
Chris Watkinsba28e462017-12-13 11:22:17 +1100289 if dry_run:
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000290 file_paths = [f for _, f in cl_info.files]
291 PrintClInfo(cl_index, num_cls, cl_info.owners_directories, file_paths,
292 description, reviewer_set, enable_auto_submit, topic)
Chris Watkinsba28e462017-12-13 11:22:17 +1100293 else:
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000294 UploadCl(refactor_branch, refactor_branch_upstream,
295 cl_info.owners_directories, cl_info.files, description,
296 comment, reviewer_set, changelist, cmd_upload, cq_dry_run,
297 enable_auto_submit, topic, repository_root)
Francois Dorayd42c6812017-05-30 15:10:20 -0400298
Anne Redullab5509952023-07-27 01:27:02 +0000299 for reviewer in reviewers:
300 cls_per_reviewer[reviewer] += 1
301
302 # List the top reviewers that will be sent the most CLs as a result of the
303 # split.
304 reviewer_rankings = sorted(cls_per_reviewer.items(),
305 key=lambda item: item[1],
306 reverse=True)
307 print('The top reviewers are:')
308 for reviewer, count in reviewer_rankings[:CL_SPLIT_TOP_REVIEWERS]:
309 print(f' {reviewer}: {count} CLs')
310
Francois Dorayd42c6812017-05-30 15:10:20 -0400311 # Go back to the original branch.
312 git.run('checkout', refactor_branch)
313
314 except subprocess2.CalledProcessError as cpe:
315 sys.stderr.write(cpe.stderr)
316 return 1
317 return 0
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000318
319
Peter Kotwiczcaeef7b2023-08-24 02:34:52 +0000320def CheckDescriptionBugLink(description):
321 """Verifies that the description contains a bug link.
322
323 Examples:
324 Bug: 123
325 Bug: chromium:456
326
327 Prompts user if the description does not contain a bug link.
328 """
329 bug_pattern = re.compile(r"^Bug:\s*(?:[a-zA-Z]+:)?[0-9]+", re.MULTILINE)
330 matches = re.findall(bug_pattern, description)
331 answer = 'y'
332 if not matches:
333 answer = gclient_utils.AskForData(
334 'Description does not include a bug link. Proceed? (y/n):')
335 return answer.lower() == 'y'
336
337
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000338def SelectReviewersForFiles(cl, author, files, max_depth):
339 """Selects reviewers for passed-in files
340
341 Args:
342 cl: Changelist class instance
343 author: Email of person running 'git cl split'
344 files: List of files
345 max_depth: The maximum directory depth to search for OWNERS files. A value
346 less than 1 means no limit.
347 """
348 info_split_by_owners = GetFilesSplitByOwners(files, max_depth)
349
350 info_split_by_reviewers = {}
351
352 for (directory, split_files) in info_split_by_owners.items():
353 # Use '/' as a path separator in the branch name and the CL description
354 # and comment.
355 directory = directory.replace(os.path.sep, '/')
356 file_paths = [f for _, f in split_files]
357 # Convert reviewers list to tuple in order to use reviewers as key to
358 # dictionary.
359 reviewers = tuple(
360 cl.owners_client.SuggestOwners(
361 file_paths, exclude=[author, cl.owners_client.EVERYONE]))
362
363 if not reviewers in info_split_by_reviewers:
364 info_split_by_reviewers[reviewers] = FilesAndOwnersDirectory([], [])
365 info_split_by_reviewers[reviewers].files.extend(split_files)
366 info_split_by_reviewers[reviewers].owners_directories.append(directory)
367
368 return info_split_by_reviewers