blob: 55879540345661f8a70b79f6082e0afea7faec64 [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
15import tempfile
16
Edward Lemur1773f372020-02-22 00:27:14 +000017import gclient_utils
Francois Dorayd42c6812017-05-30 15:10:20 -040018import git_footers
Josip Sokcevic7958e302023-03-01 23:02:21 +000019import scm
Francois Dorayd42c6812017-05-30 15:10:20 -040020
21import git_common as git
22
23
Stephen Martinisf53f82c2018-09-07 20:58:05 +000024# If a call to `git cl split` will generate more than this number of CLs, the
25# command will prompt the user to make sure they know what they're doing. Large
26# numbers of CLs generated by `git cl split` have caused infrastructure issues
27# in the past.
28CL_SPLIT_FORCE_LIMIT = 10
29
Anne Redullab5509952023-07-27 01:27:02 +000030# The maximum number of top reviewers to list. `git cl split` may send many CLs
31# to a single reviewer, so the top reviewers with the most CLs sent to them
32# will be listed.
33CL_SPLIT_TOP_REVIEWERS = 5
34
Peter Kotwicz70d971a2023-08-01 22:26:14 +000035FilesAndOwnersDirectory = collections.namedtuple("FilesAndOwnersDirectory",
36 "files owners_directories")
37
Stephen Martinisf53f82c2018-09-07 20:58:05 +000038
Francois Dorayd42c6812017-05-30 15:10:20 -040039def EnsureInGitRepository():
40 """Throws an exception if the current directory is not a git repository."""
41 git.run('rev-parse')
42
43
Peter Kotwicz70d971a2023-08-01 22:26:14 +000044def CreateBranchForDirectories(prefix, directories, upstream):
45 """Creates a branch named |prefix| + "_" + |directories[0]| + "_split".
Francois Dorayd42c6812017-05-30 15:10:20 -040046
47 Return false if the branch already exists. |upstream| is used as upstream for
48 the created branch.
49 """
50 existing_branches = set(git.branches(use_limit = False))
Peter Kotwicz70d971a2023-08-01 22:26:14 +000051 branch_name = prefix + '_' + directories[0] + '_split'
Francois Dorayd42c6812017-05-30 15:10:20 -040052 if branch_name in existing_branches:
53 return False
54 git.run('checkout', '-t', upstream, '-b', branch_name)
55 return True
56
57
Peter Kotwicz70d971a2023-08-01 22:26:14 +000058def FormatDirectoriesForPrinting(directories, prefix=None):
59 """Formats directory list for printing
60
61 Uses dedicated format for single-item list."""
62
63 prefixed = directories
64 if prefix:
65 prefixed = [(prefix + d) for d in directories]
66
67 return str(prefixed) if len(prefixed) > 1 else str(prefixed[0])
68
69
70def FormatDescriptionOrComment(txt, directories):
71 """Replaces $directory with |directories| in |txt|."""
72 to_insert = FormatDirectoriesForPrinting(directories, prefix='/')
73 return txt.replace('$directory', to_insert)
Francois Dorayd42c6812017-05-30 15:10:20 -040074
75
76def AddUploadedByGitClSplitToDescription(description):
77 """Adds a 'This CL was uploaded by git cl split.' line to |description|.
78
79 The line is added before footers, or at the end of |description| if it has no
80 footers.
81 """
82 split_footers = git_footers.split_footers(description)
83 lines = split_footers[0]
Song Fangzhen534f5052021-06-23 08:51:34 +000084 if lines[-1] and not lines[-1].isspace():
Francois Dorayd42c6812017-05-30 15:10:20 -040085 lines = lines + ['']
86 lines = lines + ['This CL was uploaded by git cl split.']
87 if split_footers[1]:
88 lines += [''] + split_footers[1]
89 return '\n'.join(lines)
90
91
Peter Kotwicz70d971a2023-08-01 22:26:14 +000092def UploadCl(refactor_branch, refactor_branch_upstream, directories, files,
Edward Lemurac5c55f2020-02-29 00:17:16 +000093 description, comment, reviewers, changelist, cmd_upload,
Rachael Newitt03e49122023-06-28 21:39:21 +000094 cq_dry_run, enable_auto_submit, topic, repository_root):
Francois Dorayd42c6812017-05-30 15:10:20 -040095 """Uploads a CL with all changes to |files| in |refactor_branch|.
96
97 Args:
98 refactor_branch: Name of the branch that contains the changes to upload.
99 refactor_branch_upstream: Name of the upstream of |refactor_branch|.
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000100 directories: Paths to the directories that contain the OWNERS files for
101 which to upload a CL.
Francois Dorayd42c6812017-05-30 15:10:20 -0400102 files: List of AffectedFile instances to include in the uploaded CL.
Francois Dorayd42c6812017-05-30 15:10:20 -0400103 description: Description of the uploaded CL.
104 comment: Comment to post on the uploaded CL.
Edward Lemurac5c55f2020-02-29 00:17:16 +0000105 reviewers: A set of reviewers for the CL.
Francois Dorayd42c6812017-05-30 15:10:20 -0400106 changelist: The Changelist class.
107 cmd_upload: The function associated with the git cl upload command.
Stephen Martiniscb326682018-08-29 21:06:30 +0000108 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +0000109 enable_auto_submit: If CL uploads should also enable auto submit.
Rachael Newitt03e49122023-06-28 21:39:21 +0000110 topic: Topic to associate with uploaded CLs.
Francois Dorayd42c6812017-05-30 15:10:20 -0400111 """
Francois Dorayd42c6812017-05-30 15:10:20 -0400112 # Create a branch.
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000113 if not CreateBranchForDirectories(refactor_branch, directories,
114 refactor_branch_upstream):
115 print('Skipping ' + FormatDirectoriesForPrinting(directories) +
116 ' for which a branch already exists.')
Francois Dorayd42c6812017-05-30 15:10:20 -0400117 return
118
119 # Checkout all changes to files in |files|.
Edward Lemur2c62b332020-03-12 22:12:33 +0000120 deleted_files = []
121 modified_files = []
122 for action, f in files:
123 abspath = os.path.abspath(os.path.join(repository_root, f))
124 if action == 'D':
125 deleted_files.append(abspath)
126 else:
127 modified_files.append(abspath)
128
Francois Dorayd42c6812017-05-30 15:10:20 -0400129 if deleted_files:
130 git.run(*['rm'] + deleted_files)
Francois Dorayd42c6812017-05-30 15:10:20 -0400131 if modified_files:
132 git.run(*['checkout', refactor_branch, '--'] + modified_files)
133
134 # Commit changes. The temporary file is created with delete=False so that it
135 # can be deleted manually after git has read it rather than automatically
136 # when it is closed.
Edward Lemur1773f372020-02-22 00:27:14 +0000137 with gclient_utils.temporary_file() as tmp_file:
138 gclient_utils.FileWrite(
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000139 tmp_file, FormatDescriptionOrComment(description, directories))
Edward Lemur1773f372020-02-22 00:27:14 +0000140 git.run('commit', '-F', tmp_file)
Francois Dorayd42c6812017-05-30 15:10:20 -0400141
142 # Upload a CL.
Anthony Politoc08c71b2020-08-26 23:45:30 +0000143 upload_args = ['-f']
144 if reviewers:
Peter Kotwiczcaeef7b2023-08-24 02:34:52 +0000145 upload_args.extend(['-r', ','.join(sorted(reviewers))])
Stephen Martiniscb326682018-08-29 21:06:30 +0000146 if cq_dry_run:
147 upload_args.append('--cq-dry-run')
Francois Dorayd42c6812017-05-30 15:10:20 -0400148 if not comment:
Aaron Gablee5adf612017-07-14 10:43:58 -0700149 upload_args.append('--send-mail')
Takuto Ikuta51eca592019-02-14 19:40:52 +0000150 if enable_auto_submit:
151 upload_args.append('--enable-auto-submit')
Rachael Newitt03e49122023-06-28 21:39:21 +0000152 if topic:
153 upload_args.append('--topic={}'.format(topic))
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000154 print('Uploading CL for ' + FormatDirectoriesForPrinting(directories) + '...')
Olivier Li06145912021-05-12 23:59:24 +0000155
156 ret = cmd_upload(upload_args)
157 if ret != 0:
Peter Kotwicz729de572023-08-03 03:20:22 +0000158 print('Uploading failed.')
Olivier Li06145912021-05-12 23:59:24 +0000159 print('Note: git cl split has built-in resume capabilities.')
160 print('Delete ' + git.current_branch() +
161 ' then run git cl split again to resume uploading.')
162
Francois Dorayd42c6812017-05-30 15:10:20 -0400163 if comment:
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000164 changelist().AddComment(FormatDescriptionOrComment(comment, directories),
Edward Lemurac5c55f2020-02-29 00:17:16 +0000165 publish=True)
Francois Dorayd42c6812017-05-30 15:10:20 -0400166
167
Daniel Cheng403c44e2022-10-05 22:24:58 +0000168def GetFilesSplitByOwners(files, max_depth):
Francois Dorayd42c6812017-05-30 15:10:20 -0400169 """Returns a map of files split by OWNERS file.
170
171 Returns:
172 A map where keys are paths to directories containing an OWNERS file and
173 values are lists of files sharing an OWNERS file.
174 """
Edward Lesmesb1174d72021-02-02 20:31:34 +0000175 files_split_by_owners = {}
Edward Lesmes17ffd982020-03-31 17:33:16 +0000176 for action, path in files:
Daniel Cheng403c44e2022-10-05 22:24:58 +0000177 # normpath() is important to normalize separators here, in prepration for
178 # str.split() before. It would be nicer to use something like pathlib here
179 # but alas...
180 dir_with_owners = os.path.normpath(os.path.dirname(path))
181 if max_depth >= 1:
182 dir_with_owners = os.path.join(
183 *dir_with_owners.split(os.path.sep)[:max_depth])
Edward Lesmesb1174d72021-02-02 20:31:34 +0000184 # Find the closest parent directory with an OWNERS file.
185 while (dir_with_owners not in files_split_by_owners
186 and not os.path.isfile(os.path.join(dir_with_owners, 'OWNERS'))):
187 dir_with_owners = os.path.dirname(dir_with_owners)
188 files_split_by_owners.setdefault(dir_with_owners, []).append((action, path))
Edward Lemurac5c55f2020-02-29 00:17:16 +0000189 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):
Chris Watkinsba28e462017-12-13 11:22:17 +1100194 """Prints info about a CL.
195
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 """
Edward Lemurac5c55f2020-02-29 00:17:16 +0000207 description_lines = FormatDescriptionOrComment(description,
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000208 directories).splitlines()
Chris Watkinsba28e462017-12-13 11:22:17 +1100209 indented_description = '\n'.join([' ' + l for l in description_lines])
210
Raul Tambre80ee78e2019-05-06 22:41:05 +0000211 print('CL {}/{}'.format(cl_index, num_cls))
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000212 print('Paths: {}'.format(FormatDirectoriesForPrinting(directories)))
Edward Lemurac5c55f2020-02-29 00:17:16 +0000213 print('Reviewers: {}'.format(', '.join(reviewers)))
Anne Redulla072d06e2023-07-06 23:12:16 +0000214 print('Auto-Submit: {}'.format(enable_auto_submit))
Rachael Newitt03e49122023-06-28 21:39:21 +0000215 print('Topic: {}'.format(topic))
Raul Tambre80ee78e2019-05-06 22:41:05 +0000216 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):
Francois Dorayd42c6812017-05-30 15:10:20 -0400223 """"Splits a branch into smaller branches and uploads CLs.
224
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 """
Edward Lesmesb1174d72021-02-02 20:31:34 +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
244 try:
Chris Watkinsba28e462017-12-13 11:22:17 +1100245 EnsureInGitRepository()
Francois Dorayd42c6812017-05-30 15:10:20 -0400246
247 cl = changelist()
Edward Lemur2c62b332020-03-12 22:12:33 +0000248 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
254 if not files:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000255 print('Cannot split an empty CL.')
Francois Dorayd42c6812017-05-30 15:10:20 -0400256 return 1
257
258 author = git.run('config', 'user.email').strip() or None
259 refactor_branch = git.current_branch()
Gabriel Charette09baacd2017-11-09 13:30:41 -0500260 assert refactor_branch, "Can't run from detached branch."
Francois Dorayd42c6812017-05-30 15:10:20 -0400261 refactor_branch_upstream = git.upstream(refactor_branch)
Gabriel Charette09baacd2017-11-09 13:30:41 -0500262 assert refactor_branch_upstream, \
263 "Branch %s must have an upstream." % refactor_branch
Francois Dorayd42c6812017-05-30 15:10:20 -0400264
Peter Kotwiczcaeef7b2023-08-24 02:34:52 +0000265 if not CheckDescriptionBugLink(description):
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000266 return 0
Francois Dorayd42c6812017-05-30 15:10:20 -0400267
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000268 files_split_by_reviewers = SelectReviewersForFiles(cl, author, files,
269 max_depth)
270
271 num_cls = len(files_split_by_reviewers)
Edward Lemurac5c55f2020-02-29 00:17:16 +0000272 print('Will split current branch (' + refactor_branch + ') into ' +
273 str(num_cls) + ' CLs.\n')
Stephen Martinisf53f82c2018-09-07 20:58:05 +0000274 if cq_dry_run and num_cls > CL_SPLIT_FORCE_LIMIT:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000275 print(
Stephen Martiniscb326682018-08-29 21:06:30 +0000276 'This will generate "%r" CLs. This many CLs can potentially generate'
277 ' too much load on the build infrastructure. Please email'
278 ' infra-dev@chromium.org to ensure that this won\'t break anything.'
279 ' The infra team reserves the right to cancel your jobs if they are'
Raul Tambre80ee78e2019-05-06 22:41:05 +0000280 ' overloading the CQ.' % num_cls)
Edward Lesmesae3586b2020-03-23 21:21:14 +0000281 answer = gclient_utils.AskForData('Proceed? (y/n):')
Stephen Martiniscb326682018-08-29 21:06:30 +0000282 if answer.lower() != 'y':
283 return 0
Francois Dorayd42c6812017-05-30 15:10:20 -0400284
Anne Redullab5509952023-07-27 01:27:02 +0000285 cls_per_reviewer = collections.defaultdict(int)
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000286 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)
Chris Watkinsba28e462017-12-13 11:22:17 +1100290 if dry_run:
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000291 file_paths = [f for _, f in cl_info.files]
292 PrintClInfo(cl_index, num_cls, cl_info.owners_directories, file_paths,
293 description, reviewer_set, enable_auto_submit, topic)
Chris Watkinsba28e462017-12-13 11:22:17 +1100294 else:
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000295 UploadCl(refactor_branch, refactor_branch_upstream,
296 cl_info.owners_directories, cl_info.files, description,
297 comment, reviewer_set, changelist, cmd_upload, cq_dry_run,
298 enable_auto_submit, topic, repository_root)
Francois Dorayd42c6812017-05-30 15:10:20 -0400299
Anne Redullab5509952023-07-27 01:27:02 +0000300 for reviewer in reviewers:
301 cls_per_reviewer[reviewer] += 1
302
303 # List the top reviewers that will be sent the most CLs as a result of the
304 # split.
305 reviewer_rankings = sorted(cls_per_reviewer.items(),
306 key=lambda item: item[1],
307 reverse=True)
308 print('The top reviewers are:')
309 for reviewer, count in reviewer_rankings[:CL_SPLIT_TOP_REVIEWERS]:
310 print(f' {reviewer}: {count} CLs')
311
Francois Dorayd42c6812017-05-30 15:10:20 -0400312 # Go back to the original branch.
313 git.run('checkout', refactor_branch)
314
315 except subprocess2.CalledProcessError as cpe:
316 sys.stderr.write(cpe.stderr)
317 return 1
318 return 0
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000319
320
Peter Kotwiczcaeef7b2023-08-24 02:34:52 +0000321def CheckDescriptionBugLink(description):
322 """Verifies that the description contains a bug link.
323
324 Examples:
325 Bug: 123
326 Bug: chromium:456
327
328 Prompts user if the description does not contain a bug link.
329 """
330 bug_pattern = re.compile(r"^Bug:\s*(?:[a-zA-Z]+:)?[0-9]+", re.MULTILINE)
331 matches = re.findall(bug_pattern, description)
332 answer = 'y'
333 if not matches:
334 answer = gclient_utils.AskForData(
335 'Description does not include a bug link. Proceed? (y/n):')
336 return answer.lower() == 'y'
337
338
Peter Kotwicz70d971a2023-08-01 22:26:14 +0000339def SelectReviewersForFiles(cl, author, files, max_depth):
340 """Selects reviewers for passed-in files
341
342 Args:
343 cl: Changelist class instance
344 author: Email of person running 'git cl split'
345 files: List of files
346 max_depth: The maximum directory depth to search for OWNERS files. A value
347 less than 1 means no limit.
348 """
349 info_split_by_owners = GetFilesSplitByOwners(files, max_depth)
350
351 info_split_by_reviewers = {}
352
353 for (directory, split_files) in info_split_by_owners.items():
354 # Use '/' as a path separator in the branch name and the CL description
355 # and comment.
356 directory = directory.replace(os.path.sep, '/')
357 file_paths = [f for _, f in split_files]
358 # Convert reviewers list to tuple in order to use reviewers as key to
359 # dictionary.
360 reviewers = tuple(
361 cl.owners_client.SuggestOwners(
362 file_paths, exclude=[author, cl.owners_client.EVERYONE]))
363
364 if not reviewers in info_split_by_reviewers:
365 info_split_by_reviewers[reviewers] = FilesAndOwnersDirectory([], [])
366 info_split_by_reviewers[reviewers].files.extend(split_files)
367 info_split_by_reviewers[reviewers].owners_directories.append(directory)
368
369 return info_split_by_reviewers