blob: 70768755c6e6617013cfcc42277fe9f9e5d701b5 [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.
Francois Dorayd42c6812017-05-30 15:10:20 -04005"""Splits a branch into smaller branches and uploads CLs."""
6
Raul Tambre80ee78e2019-05-06 22:41:05 +00007from __future__ import print_function
8
Francois Dorayd42c6812017-05-30 15:10:20 -04009import collections
10import os
11import re
12import subprocess2
13import sys
Francois Dorayd42c6812017-05-30 15:10:20 -040014
Edward Lemur1773f372020-02-22 00:27:14 +000015import gclient_utils
Francois Dorayd42c6812017-05-30 15:10:20 -040016import git_footers
Josip Sokcevic7958e302023-03-01 23:02:21 +000017import scm
Francois Dorayd42c6812017-05-30 15:10:20 -040018
19import git_common as git
20
Stephen Martinisf53f82c2018-09-07 20:58:05 +000021# If a call to `git cl split` will generate more than this number of CLs, the
22# command will prompt the user to make sure they know what they're doing. Large
23# numbers of CLs generated by `git cl split` have caused infrastructure issues
24# in the past.
25CL_SPLIT_FORCE_LIMIT = 10
26
Anne Redullab5509952023-07-27 01:27:02 +000027# The maximum number of top reviewers to list. `git cl split` may send many CLs
28# to a single reviewer, so the top reviewers with the most CLs sent to them
29# will be listed.
30CL_SPLIT_TOP_REVIEWERS = 5
31
Peter Kotwicz70d971a2023-08-01 22:26:14 +000032FilesAndOwnersDirectory = collections.namedtuple("FilesAndOwnersDirectory",
33 "files owners_directories")
34
Stephen Martinisf53f82c2018-09-07 20:58:05 +000035
Francois Dorayd42c6812017-05-30 15:10:20 -040036def EnsureInGitRepository():
Mike Frysinger124bb8e2023-09-06 05:48:55 +000037 """Throws an exception if the current directory is not a git repository."""
38 git.run('rev-parse')
Francois Dorayd42c6812017-05-30 15:10:20 -040039
40
Peter Kotwicz70d971a2023-08-01 22:26:14 +000041def CreateBranchForDirectories(prefix, directories, upstream):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000042 """Creates a branch named |prefix| + "_" + |directories[0]| + "_split".
Francois Dorayd42c6812017-05-30 15:10:20 -040043
44 Return false if the branch already exists. |upstream| is used as upstream for
45 the created branch.
46 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +000047 existing_branches = set(git.branches(use_limit=False))
48 branch_name = prefix + '_' + directories[0] + '_split'
49 if branch_name in existing_branches:
50 return False
51 git.run('checkout', '-t', upstream, '-b', branch_name)
52 return True
Francois Dorayd42c6812017-05-30 15:10:20 -040053
54
Peter Kotwicz70d971a2023-08-01 22:26:14 +000055def FormatDirectoriesForPrinting(directories, prefix=None):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000056 """Formats directory list for printing
Peter Kotwicz70d971a2023-08-01 22:26:14 +000057
58 Uses dedicated format for single-item list."""
59
Mike Frysinger124bb8e2023-09-06 05:48:55 +000060 prefixed = directories
61 if prefix:
62 prefixed = [(prefix + d) for d in directories]
Peter Kotwicz70d971a2023-08-01 22:26:14 +000063
Mike Frysinger124bb8e2023-09-06 05:48:55 +000064 return str(prefixed) if len(prefixed) > 1 else str(prefixed[0])
Peter Kotwicz70d971a2023-08-01 22:26:14 +000065
66
67def FormatDescriptionOrComment(txt, directories):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000068 """Replaces $directory with |directories| in |txt|."""
69 to_insert = FormatDirectoriesForPrinting(directories, prefix='/')
70 return txt.replace('$directory', to_insert)
Francois Dorayd42c6812017-05-30 15:10:20 -040071
72
73def AddUploadedByGitClSplitToDescription(description):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000074 """Adds a 'This CL was uploaded by git cl split.' line to |description|.
Francois Dorayd42c6812017-05-30 15:10:20 -040075
76 The line is added before footers, or at the end of |description| if it has no
77 footers.
78 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +000079 split_footers = git_footers.split_footers(description)
80 lines = split_footers[0]
81 if lines[-1] and not lines[-1].isspace():
82 lines = lines + ['']
83 lines = lines + ['This CL was uploaded by git cl split.']
84 if split_footers[1]:
85 lines += [''] + split_footers[1]
86 return '\n'.join(lines)
Francois Dorayd42c6812017-05-30 15:10:20 -040087
88
Peter Kotwicz70d971a2023-08-01 22:26:14 +000089def UploadCl(refactor_branch, refactor_branch_upstream, directories, files,
Edward Lemurac5c55f2020-02-29 00:17:16 +000090 description, comment, reviewers, changelist, cmd_upload,
Rachael Newitt03e49122023-06-28 21:39:21 +000091 cq_dry_run, enable_auto_submit, topic, repository_root):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000092 """Uploads a CL with all changes to |files| in |refactor_branch|.
Francois Dorayd42c6812017-05-30 15:10:20 -040093
94 Args:
95 refactor_branch: Name of the branch that contains the changes to upload.
96 refactor_branch_upstream: Name of the upstream of |refactor_branch|.
Peter Kotwicz70d971a2023-08-01 22:26:14 +000097 directories: Paths to the directories that contain the OWNERS files for
98 which to upload a CL.
Francois Dorayd42c6812017-05-30 15:10:20 -040099 files: List of AffectedFile instances to include in the uploaded CL.
Francois Dorayd42c6812017-05-30 15:10:20 -0400100 description: Description of the uploaded CL.
101 comment: Comment to post on the uploaded CL.
Edward Lemurac5c55f2020-02-29 00:17:16 +0000102 reviewers: A set of reviewers for the CL.
Francois Dorayd42c6812017-05-30 15:10:20 -0400103 changelist: The Changelist class.
104 cmd_upload: The function associated with the git cl upload command.
Stephen Martiniscb326682018-08-29 21:06:30 +0000105 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +0000106 enable_auto_submit: If CL uploads should also enable auto submit.
Rachael Newitt03e49122023-06-28 21:39:21 +0000107 topic: Topic to associate with uploaded CLs.
Francois Dorayd42c6812017-05-30 15:10:20 -0400108 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000109 # Create a branch.
110 if not CreateBranchForDirectories(refactor_branch, directories,
111 refactor_branch_upstream):
112 print('Skipping ' + FormatDirectoriesForPrinting(directories) +
113 ' for which a branch already exists.')
114 return
Francois Dorayd42c6812017-05-30 15:10:20 -0400115
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000116 # Checkout all changes to files in |files|.
117 deleted_files = []
118 modified_files = []
119 for action, f in files:
120 abspath = os.path.abspath(os.path.join(repository_root, f))
121 if action == 'D':
122 deleted_files.append(abspath)
123 else:
124 modified_files.append(abspath)
Edward Lemur2c62b332020-03-12 22:12:33 +0000125
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000126 if deleted_files:
127 git.run(*['rm'] + deleted_files)
128 if modified_files:
129 git.run(*['checkout', refactor_branch, '--'] + modified_files)
Francois Dorayd42c6812017-05-30 15:10:20 -0400130
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000131 # Commit changes. The temporary file is created with delete=False so that it
132 # can be deleted manually after git has read it rather than automatically
133 # when it is closed.
134 with gclient_utils.temporary_file() as tmp_file:
135 gclient_utils.FileWrite(
136 tmp_file, FormatDescriptionOrComment(description, directories))
137 git.run('commit', '-F', tmp_file)
Francois Dorayd42c6812017-05-30 15:10:20 -0400138
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000139 # Upload a CL.
140 upload_args = ['-f']
141 if reviewers:
142 upload_args.extend(['-r', ','.join(sorted(reviewers))])
143 if cq_dry_run:
144 upload_args.append('--cq-dry-run')
145 if not comment:
146 upload_args.append('--send-mail')
147 if enable_auto_submit:
148 upload_args.append('--enable-auto-submit')
149 if topic:
150 upload_args.append('--topic={}'.format(topic))
151 print('Uploading CL for ' + FormatDirectoriesForPrinting(directories) +
152 '...')
Olivier Li06145912021-05-12 23:59:24 +0000153
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000154 ret = cmd_upload(upload_args)
155 if ret != 0:
156 print('Uploading failed.')
157 print('Note: git cl split has built-in resume capabilities.')
158 print('Delete ' + git.current_branch() +
159 ' then run git cl split again to resume uploading.')
Olivier Li06145912021-05-12 23:59:24 +0000160
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000161 if comment:
162 changelist().AddComment(FormatDescriptionOrComment(
163 comment, directories),
164 publish=True)
Francois Dorayd42c6812017-05-30 15:10:20 -0400165
166
Daniel Cheng403c44e2022-10-05 22:24:58 +0000167def GetFilesSplitByOwners(files, max_depth):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000168 """Returns a map of files split by OWNERS file.
Francois Dorayd42c6812017-05-30 15:10:20 -0400169
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 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000174 files_split_by_owners = {}
175 for action, path in files:
176 # normpath() is important to normalize separators here, in prepration
177 # for str.split() before. It would be nicer to use something like
178 # pathlib here 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])
183 # 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(
188 (action, path))
189 return files_split_by_owners
Francois Dorayd42c6812017-05-30 15:10:20 -0400190
191
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000192def PrintClInfo(cl_index, num_cls, directories, file_paths, description,
Anne Redulla072d06e2023-07-06 23:12:16 +0000193 reviewers, enable_auto_submit, topic):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000194 """Prints info about a CL.
Chris Watkinsba28e462017-12-13 11:22:17 +1100195
196 Args:
197 cl_index: The index of this CL in the list of CLs to upload.
198 num_cls: The total number of CLs that will be uploaded.
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000199 directories: Paths to directories that contains the OWNERS files for which
Chris Watkinsba28e462017-12-13 11:22:17 +1100200 to upload a CL.
201 file_paths: A list of files in this CL.
202 description: The CL description.
Edward Lemurac5c55f2020-02-29 00:17:16 +0000203 reviewers: A set of reviewers for this CL.
Anne Redulla072d06e2023-07-06 23:12:16 +0000204 enable_auto_submit: If the CL should also have auto submit enabled.
Rachael Newitt03e49122023-06-28 21:39:21 +0000205 topic: Topic to set for this CL.
Chris Watkinsba28e462017-12-13 11:22:17 +1100206 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000207 description_lines = FormatDescriptionOrComment(description,
208 directories).splitlines()
209 indented_description = '\n'.join([' ' + l for l in description_lines])
Chris Watkinsba28e462017-12-13 11:22:17 +1100210
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000211 print('CL {}/{}'.format(cl_index, num_cls))
212 print('Paths: {}'.format(FormatDirectoriesForPrinting(directories)))
213 print('Reviewers: {}'.format(', '.join(reviewers)))
214 print('Auto-Submit: {}'.format(enable_auto_submit))
215 print('Topic: {}'.format(topic))
216 print('\n' + indented_description + '\n')
217 print('\n'.join(file_paths))
218 print()
Chris Watkinsba28e462017-12-13 11:22:17 +1100219
220
Stephen Martiniscb326682018-08-29 21:06:30 +0000221def SplitCl(description_file, comment_file, changelist, cmd_upload, dry_run,
Rachael Newitt03e49122023-06-28 21:39:21 +0000222 cq_dry_run, enable_auto_submit, max_depth, topic, repository_root):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000223 """"Splits a branch into smaller branches and uploads CLs.
Francois Dorayd42c6812017-05-30 15:10:20 -0400224
225 Args:
226 description_file: File containing the description of uploaded CLs.
227 comment_file: File containing the comment of uploaded CLs.
228 changelist: The Changelist class.
229 cmd_upload: The function associated with the git cl upload command.
Chris Watkinsba28e462017-12-13 11:22:17 +1100230 dry_run: Whether this is a dry run (no branches or CLs created).
Stephen Martiniscb326682018-08-29 21:06:30 +0000231 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +0000232 enable_auto_submit: If CL uploads should also enable auto submit.
Daniel Cheng403c44e2022-10-05 22:24:58 +0000233 max_depth: The maximum directory depth to search for OWNERS files. A value
234 less than 1 means no limit.
Rachael Newitt03e49122023-06-28 21:39:21 +0000235 topic: Topic to associate with split CLs.
Francois Dorayd42c6812017-05-30 15:10:20 -0400236
237 Returns:
238 0 in case of success. 1 in case of error.
239 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000240 description = AddUploadedByGitClSplitToDescription(
241 gclient_utils.FileRead(description_file))
242 comment = gclient_utils.FileRead(comment_file) if comment_file else None
Francois Dorayd42c6812017-05-30 15:10:20 -0400243
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000244 try:
245 EnsureInGitRepository()
Francois Dorayd42c6812017-05-30 15:10:20 -0400246
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000247 cl = changelist()
248 upstream = cl.GetCommonAncestorWithUpstream()
249 files = [
250 (action.strip(), f)
251 for action, f in scm.GIT.CaptureStatus(repository_root, upstream)
252 ]
Francois Dorayd42c6812017-05-30 15:10:20 -0400253
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000254 if not files:
255 print('Cannot split an empty CL.')
256 return 1
Francois Dorayd42c6812017-05-30 15:10:20 -0400257
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000258 author = git.run('config', 'user.email').strip() or None
259 refactor_branch = git.current_branch()
260 assert refactor_branch, "Can't run from detached branch."
261 refactor_branch_upstream = git.upstream(refactor_branch)
262 assert refactor_branch_upstream, \
263 "Branch %s must have an upstream." % refactor_branch
Francois Dorayd42c6812017-05-30 15:10:20 -0400264
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000265 if not CheckDescriptionBugLink(description):
266 return 0
Francois Dorayd42c6812017-05-30 15:10:20 -0400267
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000268 files_split_by_reviewers = SelectReviewersForFiles(
269 cl, author, files, max_depth)
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000270
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000271 num_cls = len(files_split_by_reviewers)
272 print('Will split current branch (' + refactor_branch + ') into ' +
273 str(num_cls) + ' CLs.\n')
274 if cq_dry_run and num_cls > CL_SPLIT_FORCE_LIMIT:
275 print(
276 'This will generate "%r" CLs. This many CLs can potentially'
277 ' generate too much load on the build infrastructure. Please'
278 ' email infra-dev@chromium.org to ensure that this won\'t break'
279 ' anything. The infra team reserves the right to cancel your'
280 ' jobs if they are overloading the CQ.' % num_cls)
281 answer = gclient_utils.AskForData('Proceed? (y/n):')
282 if answer.lower() != 'y':
283 return 0
Francois Dorayd42c6812017-05-30 15:10:20 -0400284
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000285 cls_per_reviewer = collections.defaultdict(int)
286 for cl_index, (reviewers, cl_info) in \
287 enumerate(files_split_by_reviewers.items(), 1):
288 # Convert reviewers from tuple to set.
289 reviewer_set = set(reviewers)
290 if dry_run:
291 file_paths = [f for _, f in cl_info.files]
292 PrintClInfo(cl_index, num_cls, cl_info.owners_directories,
293 file_paths, description, reviewer_set,
294 enable_auto_submit, topic)
295 else:
296 UploadCl(refactor_branch, refactor_branch_upstream,
297 cl_info.owners_directories, cl_info.files, description,
298 comment, reviewer_set, changelist, cmd_upload,
299 cq_dry_run, enable_auto_submit, topic, repository_root)
Francois Dorayd42c6812017-05-30 15:10:20 -0400300
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000301 for reviewer in reviewers:
302 cls_per_reviewer[reviewer] += 1
Anne Redullab5509952023-07-27 01:27:02 +0000303
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000304 # List the top reviewers that will be sent the most CLs as a result of
305 # the split.
306 reviewer_rankings = sorted(cls_per_reviewer.items(),
307 key=lambda item: item[1],
308 reverse=True)
309 print('The top reviewers are:')
310 for reviewer, count in reviewer_rankings[:CL_SPLIT_TOP_REVIEWERS]:
311 print(f' {reviewer}: {count} CLs')
Anne Redullab5509952023-07-27 01:27:02 +0000312
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000313 # Go back to the original branch.
314 git.run('checkout', refactor_branch)
Francois Dorayd42c6812017-05-30 15:10:20 -0400315
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000316 except subprocess2.CalledProcessError as cpe:
317 sys.stderr.write(cpe.stderr)
318 return 1
319 return 0
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000320
321
Peter Kotwiczcaeef7b2023-08-24 02:34:52 +0000322def CheckDescriptionBugLink(description):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000323 """Verifies that the description contains a bug link.
Peter Kotwiczcaeef7b2023-08-24 02:34:52 +0000324
325 Examples:
326 Bug: 123
327 Bug: chromium:456
328
329 Prompts user if the description does not contain a bug link.
330 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000331 bug_pattern = re.compile(r"^Bug:\s*(?:[a-zA-Z]+:)?[0-9]+", re.MULTILINE)
332 matches = re.findall(bug_pattern, description)
333 answer = 'y'
334 if not matches:
335 answer = gclient_utils.AskForData(
336 'Description does not include a bug link. Proceed? (y/n):')
337 return answer.lower() == 'y'
Peter Kotwiczcaeef7b2023-08-24 02:34:52 +0000338
339
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000340def SelectReviewersForFiles(cl, author, files, max_depth):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000341 """Selects reviewers for passed-in files
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000342
343 Args:
344 cl: Changelist class instance
345 author: Email of person running 'git cl split'
346 files: List of files
347 max_depth: The maximum directory depth to search for OWNERS files. A value
348 less than 1 means no limit.
349 """
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000350 info_split_by_owners = GetFilesSplitByOwners(files, max_depth)
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000351
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000352 info_split_by_reviewers = {}
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000353
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000354 for (directory, split_files) in info_split_by_owners.items():
355 # Use '/' as a path separator in the branch name and the CL description
356 # and comment.
357 directory = directory.replace(os.path.sep, '/')
358 file_paths = [f for _, f in split_files]
359 # Convert reviewers list to tuple in order to use reviewers as key to
360 # dictionary.
361 reviewers = tuple(
362 cl.owners_client.SuggestOwners(
363 file_paths, exclude=[author, cl.owners_client.EVERYONE]))
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000364
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000365 if not reviewers in info_split_by_reviewers:
366 info_split_by_reviewers[reviewers] = FilesAndOwnersDirectory([], [])
367 info_split_by_reviewers[reviewers].files.extend(split_files)
368 info_split_by_reviewers[reviewers].owners_directories.append(directory)
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000369
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000370 return info_split_by_reviewers