blob: 37cb1e245c01b265e43b8801a9d22af7797a5880 [file] [log] [blame]
Francois Dorayd42c6812017-05-30 15:10:20 -04001#!/usr/bin/env python
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
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
Edward Lesmes17ffd982020-03-31 17:33:16 +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
30
Francois Dorayd42c6812017-05-30 15:10:20 -040031def EnsureInGitRepository():
32 """Throws an exception if the current directory is not a git repository."""
33 git.run('rev-parse')
34
35
Edward Lemurac5c55f2020-02-29 00:17:16 +000036def CreateBranchForDirectory(prefix, directory, upstream):
37 """Creates a branch named |prefix| + "_" + |directory| + "_split".
Francois Dorayd42c6812017-05-30 15:10:20 -040038
39 Return false if the branch already exists. |upstream| is used as upstream for
40 the created branch.
41 """
42 existing_branches = set(git.branches(use_limit = False))
Edward Lemurac5c55f2020-02-29 00:17:16 +000043 branch_name = prefix + '_' + directory + '_split'
Francois Dorayd42c6812017-05-30 15:10:20 -040044 if branch_name in existing_branches:
45 return False
46 git.run('checkout', '-t', upstream, '-b', branch_name)
47 return True
48
49
Edward Lemurac5c55f2020-02-29 00:17:16 +000050def FormatDescriptionOrComment(txt, directory):
51 """Replaces $directory with |directory| in |txt|."""
52 return txt.replace('$directory', '/' + directory)
Francois Dorayd42c6812017-05-30 15:10:20 -040053
54
55def AddUploadedByGitClSplitToDescription(description):
56 """Adds a 'This CL was uploaded by git cl split.' line to |description|.
57
58 The line is added before footers, or at the end of |description| if it has no
59 footers.
60 """
61 split_footers = git_footers.split_footers(description)
62 lines = split_footers[0]
63 if not lines[-1] or lines[-1].isspace():
64 lines = lines + ['']
65 lines = lines + ['This CL was uploaded by git cl split.']
66 if split_footers[1]:
67 lines += [''] + split_footers[1]
68 return '\n'.join(lines)
69
70
Edward Lemurac5c55f2020-02-29 00:17:16 +000071def UploadCl(refactor_branch, refactor_branch_upstream, directory, files,
72 description, comment, reviewers, changelist, cmd_upload,
Edward Lemur2c62b332020-03-12 22:12:33 +000073 cq_dry_run, enable_auto_submit, repository_root):
Francois Dorayd42c6812017-05-30 15:10:20 -040074 """Uploads a CL with all changes to |files| in |refactor_branch|.
75
76 Args:
77 refactor_branch: Name of the branch that contains the changes to upload.
78 refactor_branch_upstream: Name of the upstream of |refactor_branch|.
79 directory: Path to the directory that contains the OWNERS file for which
80 to upload a CL.
81 files: List of AffectedFile instances to include in the uploaded CL.
Francois Dorayd42c6812017-05-30 15:10:20 -040082 description: Description of the uploaded CL.
83 comment: Comment to post on the uploaded CL.
Edward Lemurac5c55f2020-02-29 00:17:16 +000084 reviewers: A set of reviewers for the CL.
Francois Dorayd42c6812017-05-30 15:10:20 -040085 changelist: The Changelist class.
86 cmd_upload: The function associated with the git cl upload command.
Stephen Martiniscb326682018-08-29 21:06:30 +000087 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +000088 enable_auto_submit: If CL uploads should also enable auto submit.
Francois Dorayd42c6812017-05-30 15:10:20 -040089 """
Francois Dorayd42c6812017-05-30 15:10:20 -040090 # Create a branch.
Edward Lemurac5c55f2020-02-29 00:17:16 +000091 if not CreateBranchForDirectory(
92 refactor_branch, directory, refactor_branch_upstream):
93 print('Skipping ' + directory + ' for which a branch already exists.')
Francois Dorayd42c6812017-05-30 15:10:20 -040094 return
95
96 # Checkout all changes to files in |files|.
Edward Lemur2c62b332020-03-12 22:12:33 +000097 deleted_files = []
98 modified_files = []
99 for action, f in files:
100 abspath = os.path.abspath(os.path.join(repository_root, f))
101 if action == 'D':
102 deleted_files.append(abspath)
103 else:
104 modified_files.append(abspath)
105
Francois Dorayd42c6812017-05-30 15:10:20 -0400106 if deleted_files:
107 git.run(*['rm'] + deleted_files)
Francois Dorayd42c6812017-05-30 15:10:20 -0400108 if modified_files:
109 git.run(*['checkout', refactor_branch, '--'] + modified_files)
110
111 # Commit changes. The temporary file is created with delete=False so that it
112 # can be deleted manually after git has read it rather than automatically
113 # when it is closed.
Edward Lemur1773f372020-02-22 00:27:14 +0000114 with gclient_utils.temporary_file() as tmp_file:
115 gclient_utils.FileWrite(
Edward Lemurac5c55f2020-02-29 00:17:16 +0000116 tmp_file, FormatDescriptionOrComment(description, directory))
Edward Lemur1773f372020-02-22 00:27:14 +0000117 git.run('commit', '-F', tmp_file)
Francois Dorayd42c6812017-05-30 15:10:20 -0400118
119 # Upload a CL.
Anthony Politoc08c71b2020-08-26 23:45:30 +0000120 upload_args = ['-f']
121 if reviewers:
122 upload_args.extend(['-r', ','.join(reviewers)])
Stephen Martiniscb326682018-08-29 21:06:30 +0000123 if cq_dry_run:
124 upload_args.append('--cq-dry-run')
Francois Dorayd42c6812017-05-30 15:10:20 -0400125 if not comment:
Aaron Gablee5adf612017-07-14 10:43:58 -0700126 upload_args.append('--send-mail')
Takuto Ikuta51eca592019-02-14 19:40:52 +0000127 if enable_auto_submit:
128 upload_args.append('--enable-auto-submit')
Raul Tambre80ee78e2019-05-06 22:41:05 +0000129 print('Uploading CL for ' + directory + '.')
Francois Dorayd42c6812017-05-30 15:10:20 -0400130 cmd_upload(upload_args)
131 if comment:
Edward Lemurac5c55f2020-02-29 00:17:16 +0000132 changelist().AddComment(FormatDescriptionOrComment(comment, directory),
133 publish=True)
Francois Dorayd42c6812017-05-30 15:10:20 -0400134
135
Edward Lesmesb1174d72021-02-02 20:31:34 +0000136def GetFilesSplitByOwners(files):
Francois Dorayd42c6812017-05-30 15:10:20 -0400137 """Returns a map of files split by OWNERS file.
138
139 Returns:
140 A map where keys are paths to directories containing an OWNERS file and
141 values are lists of files sharing an OWNERS file.
142 """
Edward Lesmesb1174d72021-02-02 20:31:34 +0000143 files_split_by_owners = {}
Edward Lesmes17ffd982020-03-31 17:33:16 +0000144 for action, path in files:
Edward Lesmesb1174d72021-02-02 20:31:34 +0000145 dir_with_owners = os.path.dirname(path)
146 # Find the closest parent directory with an OWNERS file.
147 while (dir_with_owners not in files_split_by_owners
148 and not os.path.isfile(os.path.join(dir_with_owners, 'OWNERS'))):
149 dir_with_owners = os.path.dirname(dir_with_owners)
150 files_split_by_owners.setdefault(dir_with_owners, []).append((action, path))
Edward Lemurac5c55f2020-02-29 00:17:16 +0000151 return files_split_by_owners
Francois Dorayd42c6812017-05-30 15:10:20 -0400152
153
Chris Watkinsba28e462017-12-13 11:22:17 +1100154def PrintClInfo(cl_index, num_cls, directory, file_paths, description,
Edward Lemurac5c55f2020-02-29 00:17:16 +0000155 reviewers):
Chris Watkinsba28e462017-12-13 11:22:17 +1100156 """Prints info about a CL.
157
158 Args:
159 cl_index: The index of this CL in the list of CLs to upload.
160 num_cls: The total number of CLs that will be uploaded.
161 directory: Path to the directory that contains the OWNERS file for which
162 to upload a CL.
163 file_paths: A list of files in this CL.
164 description: The CL description.
Edward Lemurac5c55f2020-02-29 00:17:16 +0000165 reviewers: A set of reviewers for this CL.
Chris Watkinsba28e462017-12-13 11:22:17 +1100166 """
Edward Lemurac5c55f2020-02-29 00:17:16 +0000167 description_lines = FormatDescriptionOrComment(description,
168 directory).splitlines()
Chris Watkinsba28e462017-12-13 11:22:17 +1100169 indented_description = '\n'.join([' ' + l for l in description_lines])
170
Raul Tambre80ee78e2019-05-06 22:41:05 +0000171 print('CL {}/{}'.format(cl_index, num_cls))
172 print('Path: {}'.format(directory))
Edward Lemurac5c55f2020-02-29 00:17:16 +0000173 print('Reviewers: {}'.format(', '.join(reviewers)))
Raul Tambre80ee78e2019-05-06 22:41:05 +0000174 print('\n' + indented_description + '\n')
175 print('\n'.join(file_paths))
176 print()
Chris Watkinsba28e462017-12-13 11:22:17 +1100177
178
Stephen Martiniscb326682018-08-29 21:06:30 +0000179def SplitCl(description_file, comment_file, changelist, cmd_upload, dry_run,
Edward Lemur2c62b332020-03-12 22:12:33 +0000180 cq_dry_run, enable_auto_submit, repository_root):
Francois Dorayd42c6812017-05-30 15:10:20 -0400181 """"Splits a branch into smaller branches and uploads CLs.
182
183 Args:
184 description_file: File containing the description of uploaded CLs.
185 comment_file: File containing the comment of uploaded CLs.
186 changelist: The Changelist class.
187 cmd_upload: The function associated with the git cl upload command.
Chris Watkinsba28e462017-12-13 11:22:17 +1100188 dry_run: Whether this is a dry run (no branches or CLs created).
Stephen Martiniscb326682018-08-29 21:06:30 +0000189 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +0000190 enable_auto_submit: If CL uploads should also enable auto submit.
Francois Dorayd42c6812017-05-30 15:10:20 -0400191
192 Returns:
193 0 in case of success. 1 in case of error.
194 """
Edward Lesmesb1174d72021-02-02 20:31:34 +0000195 description = AddUploadedByGitClSplitToDescription(
196 gclient_utils.FileRead(description_file))
197 comment = gclient_utils.FileRead(comment_file) if comment_file else None
Francois Dorayd42c6812017-05-30 15:10:20 -0400198
199 try:
Chris Watkinsba28e462017-12-13 11:22:17 +1100200 EnsureInGitRepository()
Francois Dorayd42c6812017-05-30 15:10:20 -0400201
202 cl = changelist()
Edward Lemur2c62b332020-03-12 22:12:33 +0000203 upstream = cl.GetCommonAncestorWithUpstream()
204 files = [
205 (action.strip(), f)
206 for action, f in scm.GIT.CaptureStatus(repository_root, upstream)
207 ]
Francois Dorayd42c6812017-05-30 15:10:20 -0400208
209 if not files:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000210 print('Cannot split an empty CL.')
Francois Dorayd42c6812017-05-30 15:10:20 -0400211 return 1
212
213 author = git.run('config', 'user.email').strip() or None
214 refactor_branch = git.current_branch()
Gabriel Charette09baacd2017-11-09 13:30:41 -0500215 assert refactor_branch, "Can't run from detached branch."
Francois Dorayd42c6812017-05-30 15:10:20 -0400216 refactor_branch_upstream = git.upstream(refactor_branch)
Gabriel Charette09baacd2017-11-09 13:30:41 -0500217 assert refactor_branch_upstream, \
218 "Branch %s must have an upstream." % refactor_branch
Francois Dorayd42c6812017-05-30 15:10:20 -0400219
Edward Lesmesb1174d72021-02-02 20:31:34 +0000220 files_split_by_owners = GetFilesSplitByOwners(files)
Francois Dorayd42c6812017-05-30 15:10:20 -0400221
Edward Lemurac5c55f2020-02-29 00:17:16 +0000222 num_cls = len(files_split_by_owners)
223 print('Will split current branch (' + refactor_branch + ') into ' +
224 str(num_cls) + ' CLs.\n')
Stephen Martinisf53f82c2018-09-07 20:58:05 +0000225 if cq_dry_run and num_cls > CL_SPLIT_FORCE_LIMIT:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000226 print(
Stephen Martiniscb326682018-08-29 21:06:30 +0000227 'This will generate "%r" CLs. This many CLs can potentially generate'
228 ' too much load on the build infrastructure. Please email'
229 ' infra-dev@chromium.org to ensure that this won\'t break anything.'
230 ' The infra team reserves the right to cancel your jobs if they are'
Raul Tambre80ee78e2019-05-06 22:41:05 +0000231 ' overloading the CQ.' % num_cls)
Edward Lesmesae3586b2020-03-23 21:21:14 +0000232 answer = gclient_utils.AskForData('Proceed? (y/n):')
Stephen Martiniscb326682018-08-29 21:06:30 +0000233 if answer.lower() != 'y':
234 return 0
Francois Dorayd42c6812017-05-30 15:10:20 -0400235
Edward Lemurac5c55f2020-02-29 00:17:16 +0000236 for cl_index, (directory, files) in \
237 enumerate(files_split_by_owners.items(), 1):
Francois Dorayd42c6812017-05-30 15:10:20 -0400238 # Use '/' as a path separator in the branch name and the CL description
239 # and comment.
Edward Lemurac5c55f2020-02-29 00:17:16 +0000240 directory = directory.replace(os.path.sep, '/')
Edward Lemur2c62b332020-03-12 22:12:33 +0000241 file_paths = [f for _, f in files]
Edward Lesmes15234012021-02-17 17:25:03 +0000242 reviewers = cl.owners_client.SuggestOwners(
243 file_paths, exclude=[author, cl.owners_client.EVERYONE])
Chris Watkinsba28e462017-12-13 11:22:17 +1100244 if dry_run:
245 PrintClInfo(cl_index, num_cls, directory, file_paths, description,
Edward Lemurac5c55f2020-02-29 00:17:16 +0000246 reviewers)
Chris Watkinsba28e462017-12-13 11:22:17 +1100247 else:
Edward Lemurac5c55f2020-02-29 00:17:16 +0000248 UploadCl(refactor_branch, refactor_branch_upstream, directory, files,
249 description, comment, reviewers, changelist, cmd_upload,
Edward Lemur2c62b332020-03-12 22:12:33 +0000250 cq_dry_run, enable_auto_submit, repository_root)
Francois Dorayd42c6812017-05-30 15:10:20 -0400251
252 # Go back to the original branch.
253 git.run('checkout', refactor_branch)
254
255 except subprocess2.CalledProcessError as cpe:
256 sys.stderr.write(cpe.stderr)
257 return 1
258 return 0