blob: d54a09a9a1c46c58a7afb5529c74746901926ecd [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
17import git_footers
18import owners
19import owners_finder
20
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 ReadFile(file_path):
32 """Returns the content of |file_path|."""
33 with open(file_path) as f:
34 content = f.read()
35 return content
36
37
38def EnsureInGitRepository():
39 """Throws an exception if the current directory is not a git repository."""
40 git.run('rev-parse')
41
42
43def CreateBranchForDirectory(prefix, directory, upstream):
44 """Creates a branch named |prefix| + "_" + |directory| + "_split".
45
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))
50 branch_name = prefix + '_' + directory + '_split'
51 if branch_name in existing_branches:
52 return False
53 git.run('checkout', '-t', upstream, '-b', branch_name)
54 return True
55
56
57def FormatDescriptionOrComment(txt, directory):
58 """Replaces $directory with |directory| in |txt|."""
59 return txt.replace('$directory', '/' + directory)
60
61
62def AddUploadedByGitClSplitToDescription(description):
63 """Adds a 'This CL was uploaded by git cl split.' line to |description|.
64
65 The line is added before footers, or at the end of |description| if it has no
66 footers.
67 """
68 split_footers = git_footers.split_footers(description)
69 lines = split_footers[0]
70 if not lines[-1] or lines[-1].isspace():
71 lines = lines + ['']
72 lines = lines + ['This CL was uploaded by git cl split.']
73 if split_footers[1]:
74 lines += [''] + split_footers[1]
75 return '\n'.join(lines)
76
77
78def UploadCl(refactor_branch, refactor_branch_upstream, directory, files,
Stephen Martiniscb326682018-08-29 21:06:30 +000079 description, comment, reviewers, changelist, cmd_upload,
Takuto Ikuta51eca592019-02-14 19:40:52 +000080 cq_dry_run, enable_auto_submit):
Francois Dorayd42c6812017-05-30 15:10:20 -040081 """Uploads a CL with all changes to |files| in |refactor_branch|.
82
83 Args:
84 refactor_branch: Name of the branch that contains the changes to upload.
85 refactor_branch_upstream: Name of the upstream of |refactor_branch|.
86 directory: Path to the directory that contains the OWNERS file for which
87 to upload a CL.
88 files: List of AffectedFile instances to include in the uploaded CL.
Francois Dorayd42c6812017-05-30 15:10:20 -040089 description: Description of the uploaded CL.
90 comment: Comment to post on the uploaded CL.
Chris Watkinsba28e462017-12-13 11:22:17 +110091 reviewers: A set of reviewers for the CL.
Francois Dorayd42c6812017-05-30 15:10:20 -040092 changelist: The Changelist class.
93 cmd_upload: The function associated with the git cl upload command.
Stephen Martiniscb326682018-08-29 21:06:30 +000094 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +000095 enable_auto_submit: If CL uploads should also enable auto submit.
Francois Dorayd42c6812017-05-30 15:10:20 -040096 """
Francois Dorayd42c6812017-05-30 15:10:20 -040097 # Create a branch.
98 if not CreateBranchForDirectory(
99 refactor_branch, directory, refactor_branch_upstream):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000100 print('Skipping ' + directory + ' for which a branch already exists.')
Francois Dorayd42c6812017-05-30 15:10:20 -0400101 return
102
103 # Checkout all changes to files in |files|.
104 deleted_files = [f.AbsoluteLocalPath() for f in files if f.Action() == 'D']
105 if deleted_files:
106 git.run(*['rm'] + deleted_files)
107 modified_files = [f.AbsoluteLocalPath() for f in files if f.Action() != 'D']
108 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.
114 with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
115 tmp_file.write(FormatDescriptionOrComment(description, directory))
116 # Close the file to let git open it at the next line.
117 tmp_file.close()
118 git.run('commit', '-F', tmp_file.name)
119 os.remove(tmp_file.name)
120
121 # Upload a CL.
Stephen Martiniscb326682018-08-29 21:06:30 +0000122 upload_args = ['-f', '-r', ','.join(reviewers)]
123 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:
Aaron Gablee5adf612017-07-14 10:43:58 -0700132 changelist().AddComment(FormatDescriptionOrComment(comment, directory),
133 publish=True)
Francois Dorayd42c6812017-05-30 15:10:20 -0400134
135
136def GetFilesSplitByOwners(owners_database, files):
137 """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 """
143 files_split_by_owners = collections.defaultdict(list)
144 for f in files:
145 files_split_by_owners[owners_database.enclosing_dir_with_owners(
146 f.LocalPath())].append(f)
147 return files_split_by_owners
148
149
Chris Watkinsba28e462017-12-13 11:22:17 +1100150def PrintClInfo(cl_index, num_cls, directory, file_paths, description,
151 reviewers):
152 """Prints info about a CL.
153
154 Args:
155 cl_index: The index of this CL in the list of CLs to upload.
156 num_cls: The total number of CLs that will be uploaded.
157 directory: Path to the directory that contains the OWNERS file for which
158 to upload a CL.
159 file_paths: A list of files in this CL.
160 description: The CL description.
161 reviewers: A set of reviewers for this CL.
162 """
163 description_lines = FormatDescriptionOrComment(description,
164 directory).splitlines()
165 indented_description = '\n'.join([' ' + l for l in description_lines])
166
Raul Tambre80ee78e2019-05-06 22:41:05 +0000167 print('CL {}/{}'.format(cl_index, num_cls))
168 print('Path: {}'.format(directory))
169 print('Reviewers: {}'.format(', '.join(reviewers)))
170 print('\n' + indented_description + '\n')
171 print('\n'.join(file_paths))
172 print()
Chris Watkinsba28e462017-12-13 11:22:17 +1100173
174
Stephen Martiniscb326682018-08-29 21:06:30 +0000175def SplitCl(description_file, comment_file, changelist, cmd_upload, dry_run,
Takuto Ikuta51eca592019-02-14 19:40:52 +0000176 cq_dry_run, enable_auto_submit):
Francois Dorayd42c6812017-05-30 15:10:20 -0400177 """"Splits a branch into smaller branches and uploads CLs.
178
179 Args:
180 description_file: File containing the description of uploaded CLs.
181 comment_file: File containing the comment of uploaded CLs.
182 changelist: The Changelist class.
183 cmd_upload: The function associated with the git cl upload command.
Chris Watkinsba28e462017-12-13 11:22:17 +1100184 dry_run: Whether this is a dry run (no branches or CLs created).
Stephen Martiniscb326682018-08-29 21:06:30 +0000185 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +0000186 enable_auto_submit: If CL uploads should also enable auto submit.
Francois Dorayd42c6812017-05-30 15:10:20 -0400187
188 Returns:
189 0 in case of success. 1 in case of error.
190 """
191 description = AddUploadedByGitClSplitToDescription(ReadFile(description_file))
192 comment = ReadFile(comment_file) if comment_file else None
193
194 try:
Chris Watkinsba28e462017-12-13 11:22:17 +1100195 EnsureInGitRepository()
Francois Dorayd42c6812017-05-30 15:10:20 -0400196
197 cl = changelist()
198 change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
199 files = change.AffectedFiles()
200
201 if not files:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000202 print('Cannot split an empty CL.')
Francois Dorayd42c6812017-05-30 15:10:20 -0400203 return 1
204
205 author = git.run('config', 'user.email').strip() or None
206 refactor_branch = git.current_branch()
Gabriel Charette09baacd2017-11-09 13:30:41 -0500207 assert refactor_branch, "Can't run from detached branch."
Francois Dorayd42c6812017-05-30 15:10:20 -0400208 refactor_branch_upstream = git.upstream(refactor_branch)
Gabriel Charette09baacd2017-11-09 13:30:41 -0500209 assert refactor_branch_upstream, \
210 "Branch %s must have an upstream." % refactor_branch
Francois Dorayd42c6812017-05-30 15:10:20 -0400211
212 owners_database = owners.Database(change.RepositoryRoot(), file, os.path)
213 owners_database.load_data_needed_for([f.LocalPath() for f in files])
214
Chris Watkinsba28e462017-12-13 11:22:17 +1100215 files_split_by_owners = GetFilesSplitByOwners(owners_database, files)
Francois Dorayd42c6812017-05-30 15:10:20 -0400216
Chris Watkinsba28e462017-12-13 11:22:17 +1100217 num_cls = len(files_split_by_owners)
218 print('Will split current branch (' + refactor_branch + ') into ' +
219 str(num_cls) + ' CLs.\n')
Stephen Martinisf53f82c2018-09-07 20:58:05 +0000220 if cq_dry_run and num_cls > CL_SPLIT_FORCE_LIMIT:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000221 print(
Stephen Martiniscb326682018-08-29 21:06:30 +0000222 'This will generate "%r" CLs. This many CLs can potentially generate'
223 ' too much load on the build infrastructure. Please email'
224 ' infra-dev@chromium.org to ensure that this won\'t break anything.'
225 ' The infra team reserves the right to cancel your jobs if they are'
Raul Tambre80ee78e2019-05-06 22:41:05 +0000226 ' overloading the CQ.' % num_cls)
Stephen Martiniscb326682018-08-29 21:06:30 +0000227 answer = raw_input('Proceed? (y/n):')
228 if answer.lower() != 'y':
229 return 0
Francois Dorayd42c6812017-05-30 15:10:20 -0400230
Chris Watkinsba28e462017-12-13 11:22:17 +1100231 for cl_index, (directory, files) in \
232 enumerate(files_split_by_owners.iteritems(), 1):
Francois Dorayd42c6812017-05-30 15:10:20 -0400233 # Use '/' as a path separator in the branch name and the CL description
234 # and comment.
235 directory = directory.replace(os.path.sep, '/')
Chris Watkinsba28e462017-12-13 11:22:17 +1100236 file_paths = [f.LocalPath() for f in files]
237 reviewers = owners_database.reviewers_for(file_paths, author)
238
239 if dry_run:
240 PrintClInfo(cl_index, num_cls, directory, file_paths, description,
241 reviewers)
242 else:
243 UploadCl(refactor_branch, refactor_branch_upstream, directory, files,
Stephen Martiniscb326682018-08-29 21:06:30 +0000244 description, comment, reviewers, changelist, cmd_upload,
Takuto Ikuta51eca592019-02-14 19:40:52 +0000245 cq_dry_run, enable_auto_submit)
Francois Dorayd42c6812017-05-30 15:10:20 -0400246
247 # Go back to the original branch.
248 git.run('checkout', refactor_branch)
249
250 except subprocess2.CalledProcessError as cpe:
251 sys.stderr.write(cpe.stderr)
252 return 1
253 return 0