blob: 1e93975fbba63e608fe519945f54e63cea896469 [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
8import collections
9import os
10import re
11import subprocess2
12import sys
13import tempfile
14
15import git_footers
16import owners
17import owners_finder
18
19import git_common as git
20
21
Stephen Martinisf53f82c2018-09-07 20:58:05 +000022# If a call to `git cl split` will generate more than this number of CLs, the
23# command will prompt the user to make sure they know what they're doing. Large
24# numbers of CLs generated by `git cl split` have caused infrastructure issues
25# in the past.
26CL_SPLIT_FORCE_LIMIT = 10
27
28
Francois Dorayd42c6812017-05-30 15:10:20 -040029def ReadFile(file_path):
30 """Returns the content of |file_path|."""
31 with open(file_path) as f:
32 content = f.read()
33 return content
34
35
36def EnsureInGitRepository():
37 """Throws an exception if the current directory is not a git repository."""
38 git.run('rev-parse')
39
40
41def CreateBranchForDirectory(prefix, directory, upstream):
42 """Creates a branch named |prefix| + "_" + |directory| + "_split".
43
44 Return false if the branch already exists. |upstream| is used as upstream for
45 the created branch.
46 """
47 existing_branches = set(git.branches(use_limit = False))
48 branch_name = prefix + '_' + directory + '_split'
49 if branch_name in existing_branches:
50 return False
51 git.run('checkout', '-t', upstream, '-b', branch_name)
52 return True
53
54
55def FormatDescriptionOrComment(txt, directory):
56 """Replaces $directory with |directory| in |txt|."""
57 return txt.replace('$directory', '/' + directory)
58
59
60def AddUploadedByGitClSplitToDescription(description):
61 """Adds a 'This CL was uploaded by git cl split.' line to |description|.
62
63 The line is added before footers, or at the end of |description| if it has no
64 footers.
65 """
66 split_footers = git_footers.split_footers(description)
67 lines = split_footers[0]
68 if not lines[-1] or lines[-1].isspace():
69 lines = lines + ['']
70 lines = lines + ['This CL was uploaded by git cl split.']
71 if split_footers[1]:
72 lines += [''] + split_footers[1]
73 return '\n'.join(lines)
74
75
76def UploadCl(refactor_branch, refactor_branch_upstream, directory, files,
Stephen Martiniscb326682018-08-29 21:06:30 +000077 description, comment, reviewers, changelist, cmd_upload,
Takuto Ikuta51eca592019-02-14 19:40:52 +000078 cq_dry_run, enable_auto_submit):
Francois Dorayd42c6812017-05-30 15:10:20 -040079 """Uploads a CL with all changes to |files| in |refactor_branch|.
80
81 Args:
82 refactor_branch: Name of the branch that contains the changes to upload.
83 refactor_branch_upstream: Name of the upstream of |refactor_branch|.
84 directory: Path to the directory that contains the OWNERS file for which
85 to upload a CL.
86 files: List of AffectedFile instances to include in the uploaded CL.
Francois Dorayd42c6812017-05-30 15:10:20 -040087 description: Description of the uploaded CL.
88 comment: Comment to post on the uploaded CL.
Chris Watkinsba28e462017-12-13 11:22:17 +110089 reviewers: A set of reviewers for the CL.
Francois Dorayd42c6812017-05-30 15:10:20 -040090 changelist: The Changelist class.
91 cmd_upload: The function associated with the git cl upload command.
Stephen Martiniscb326682018-08-29 21:06:30 +000092 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +000093 enable_auto_submit: If CL uploads should also enable auto submit.
Francois Dorayd42c6812017-05-30 15:10:20 -040094 """
Francois Dorayd42c6812017-05-30 15:10:20 -040095 # Create a branch.
96 if not CreateBranchForDirectory(
97 refactor_branch, directory, refactor_branch_upstream):
98 print 'Skipping ' + directory + ' for which a branch already exists.'
99 return
100
101 # Checkout all changes to files in |files|.
102 deleted_files = [f.AbsoluteLocalPath() for f in files if f.Action() == 'D']
103 if deleted_files:
104 git.run(*['rm'] + deleted_files)
105 modified_files = [f.AbsoluteLocalPath() for f in files if f.Action() != 'D']
106 if modified_files:
107 git.run(*['checkout', refactor_branch, '--'] + modified_files)
108
109 # Commit changes. The temporary file is created with delete=False so that it
110 # can be deleted manually after git has read it rather than automatically
111 # when it is closed.
112 with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
113 tmp_file.write(FormatDescriptionOrComment(description, directory))
114 # Close the file to let git open it at the next line.
115 tmp_file.close()
116 git.run('commit', '-F', tmp_file.name)
117 os.remove(tmp_file.name)
118
119 # Upload a CL.
Stephen Martiniscb326682018-08-29 21:06:30 +0000120 upload_args = ['-f', '-r', ','.join(reviewers)]
121 if cq_dry_run:
122 upload_args.append('--cq-dry-run')
Francois Dorayd42c6812017-05-30 15:10:20 -0400123 if not comment:
Aaron Gablee5adf612017-07-14 10:43:58 -0700124 upload_args.append('--send-mail')
Takuto Ikuta51eca592019-02-14 19:40:52 +0000125 if enable_auto_submit:
126 upload_args.append('--enable-auto-submit')
Francois Dorayd42c6812017-05-30 15:10:20 -0400127 print 'Uploading CL for ' + directory + '.'
128 cmd_upload(upload_args)
129 if comment:
Aaron Gablee5adf612017-07-14 10:43:58 -0700130 changelist().AddComment(FormatDescriptionOrComment(comment, directory),
131 publish=True)
Francois Dorayd42c6812017-05-30 15:10:20 -0400132
133
134def GetFilesSplitByOwners(owners_database, files):
135 """Returns a map of files split by OWNERS file.
136
137 Returns:
138 A map where keys are paths to directories containing an OWNERS file and
139 values are lists of files sharing an OWNERS file.
140 """
141 files_split_by_owners = collections.defaultdict(list)
142 for f in files:
143 files_split_by_owners[owners_database.enclosing_dir_with_owners(
144 f.LocalPath())].append(f)
145 return files_split_by_owners
146
147
Chris Watkinsba28e462017-12-13 11:22:17 +1100148def PrintClInfo(cl_index, num_cls, directory, file_paths, description,
149 reviewers):
150 """Prints info about a CL.
151
152 Args:
153 cl_index: The index of this CL in the list of CLs to upload.
154 num_cls: The total number of CLs that will be uploaded.
155 directory: Path to the directory that contains the OWNERS file for which
156 to upload a CL.
157 file_paths: A list of files in this CL.
158 description: The CL description.
159 reviewers: A set of reviewers for this CL.
160 """
161 description_lines = FormatDescriptionOrComment(description,
162 directory).splitlines()
163 indented_description = '\n'.join([' ' + l for l in description_lines])
164
165 print 'CL {}/{}'.format(cl_index, num_cls)
166 print 'Path: {}'.format(directory)
167 print 'Reviewers: {}'.format(', '.join(reviewers))
168 print '\n' + indented_description + '\n'
169 print '\n'.join(file_paths)
170 print
171
172
Stephen Martiniscb326682018-08-29 21:06:30 +0000173def SplitCl(description_file, comment_file, changelist, cmd_upload, dry_run,
Takuto Ikuta51eca592019-02-14 19:40:52 +0000174 cq_dry_run, enable_auto_submit):
Francois Dorayd42c6812017-05-30 15:10:20 -0400175 """"Splits a branch into smaller branches and uploads CLs.
176
177 Args:
178 description_file: File containing the description of uploaded CLs.
179 comment_file: File containing the comment of uploaded CLs.
180 changelist: The Changelist class.
181 cmd_upload: The function associated with the git cl upload command.
Chris Watkinsba28e462017-12-13 11:22:17 +1100182 dry_run: Whether this is a dry run (no branches or CLs created).
Stephen Martiniscb326682018-08-29 21:06:30 +0000183 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +0000184 enable_auto_submit: If CL uploads should also enable auto submit.
Francois Dorayd42c6812017-05-30 15:10:20 -0400185
186 Returns:
187 0 in case of success. 1 in case of error.
188 """
189 description = AddUploadedByGitClSplitToDescription(ReadFile(description_file))
190 comment = ReadFile(comment_file) if comment_file else None
191
192 try:
Chris Watkinsba28e462017-12-13 11:22:17 +1100193 EnsureInGitRepository()
Francois Dorayd42c6812017-05-30 15:10:20 -0400194
195 cl = changelist()
196 change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
197 files = change.AffectedFiles()
198
199 if not files:
200 print 'Cannot split an empty CL.'
201 return 1
202
203 author = git.run('config', 'user.email').strip() or None
204 refactor_branch = git.current_branch()
Gabriel Charette09baacd2017-11-09 13:30:41 -0500205 assert refactor_branch, "Can't run from detached branch."
Francois Dorayd42c6812017-05-30 15:10:20 -0400206 refactor_branch_upstream = git.upstream(refactor_branch)
Gabriel Charette09baacd2017-11-09 13:30:41 -0500207 assert refactor_branch_upstream, \
208 "Branch %s must have an upstream." % refactor_branch
Francois Dorayd42c6812017-05-30 15:10:20 -0400209
210 owners_database = owners.Database(change.RepositoryRoot(), file, os.path)
211 owners_database.load_data_needed_for([f.LocalPath() for f in files])
212
Chris Watkinsba28e462017-12-13 11:22:17 +1100213 files_split_by_owners = GetFilesSplitByOwners(owners_database, files)
Francois Dorayd42c6812017-05-30 15:10:20 -0400214
Chris Watkinsba28e462017-12-13 11:22:17 +1100215 num_cls = len(files_split_by_owners)
216 print('Will split current branch (' + refactor_branch + ') into ' +
217 str(num_cls) + ' CLs.\n')
Stephen Martinisf53f82c2018-09-07 20:58:05 +0000218 if cq_dry_run and num_cls > CL_SPLIT_FORCE_LIMIT:
Stephen Martiniscb326682018-08-29 21:06:30 +0000219 print (
220 'This will generate "%r" CLs. This many CLs can potentially generate'
221 ' too much load on the build infrastructure. Please email'
222 ' infra-dev@chromium.org to ensure that this won\'t break anything.'
223 ' The infra team reserves the right to cancel your jobs if they are'
224 ' overloading the CQ.') % num_cls
225 answer = raw_input('Proceed? (y/n):')
226 if answer.lower() != 'y':
227 return 0
Francois Dorayd42c6812017-05-30 15:10:20 -0400228
Chris Watkinsba28e462017-12-13 11:22:17 +1100229 for cl_index, (directory, files) in \
230 enumerate(files_split_by_owners.iteritems(), 1):
Francois Dorayd42c6812017-05-30 15:10:20 -0400231 # Use '/' as a path separator in the branch name and the CL description
232 # and comment.
233 directory = directory.replace(os.path.sep, '/')
Chris Watkinsba28e462017-12-13 11:22:17 +1100234 file_paths = [f.LocalPath() for f in files]
235 reviewers = owners_database.reviewers_for(file_paths, author)
236
237 if dry_run:
238 PrintClInfo(cl_index, num_cls, directory, file_paths, description,
239 reviewers)
240 else:
241 UploadCl(refactor_branch, refactor_branch_upstream, directory, files,
Stephen Martiniscb326682018-08-29 21:06:30 +0000242 description, comment, reviewers, changelist, cmd_upload,
Takuto Ikuta51eca592019-02-14 19:40:52 +0000243 cq_dry_run, enable_auto_submit)
Francois Dorayd42c6812017-05-30 15:10:20 -0400244
245 # Go back to the original branch.
246 git.run('checkout', refactor_branch)
247
248 except subprocess2.CalledProcessError as cpe:
249 sys.stderr.write(cpe.stderr)
250 return 1
251 return 0