blob: e501329d868d30a305b14d98b7bb8dca56e02600 [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,
78 cq_dry_run):
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.
Francois Dorayd42c6812017-05-30 15:10:20 -040093 """
Francois Dorayd42c6812017-05-30 15:10:20 -040094 # Create a branch.
95 if not CreateBranchForDirectory(
96 refactor_branch, directory, refactor_branch_upstream):
97 print 'Skipping ' + directory + ' for which a branch already exists.'
98 return
99
100 # Checkout all changes to files in |files|.
101 deleted_files = [f.AbsoluteLocalPath() for f in files if f.Action() == 'D']
102 if deleted_files:
103 git.run(*['rm'] + deleted_files)
104 modified_files = [f.AbsoluteLocalPath() for f in files if f.Action() != 'D']
105 if modified_files:
106 git.run(*['checkout', refactor_branch, '--'] + modified_files)
107
108 # Commit changes. The temporary file is created with delete=False so that it
109 # can be deleted manually after git has read it rather than automatically
110 # when it is closed.
111 with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
112 tmp_file.write(FormatDescriptionOrComment(description, directory))
113 # Close the file to let git open it at the next line.
114 tmp_file.close()
115 git.run('commit', '-F', tmp_file.name)
116 os.remove(tmp_file.name)
117
118 # Upload a CL.
Stephen Martiniscb326682018-08-29 21:06:30 +0000119 upload_args = ['-f', '-r', ','.join(reviewers)]
120 if cq_dry_run:
121 upload_args.append('--cq-dry-run')
Francois Dorayd42c6812017-05-30 15:10:20 -0400122 if not comment:
Aaron Gablee5adf612017-07-14 10:43:58 -0700123 upload_args.append('--send-mail')
Francois Dorayd42c6812017-05-30 15:10:20 -0400124 print 'Uploading CL for ' + directory + '.'
125 cmd_upload(upload_args)
126 if comment:
Aaron Gablee5adf612017-07-14 10:43:58 -0700127 changelist().AddComment(FormatDescriptionOrComment(comment, directory),
128 publish=True)
Francois Dorayd42c6812017-05-30 15:10:20 -0400129
130
131def GetFilesSplitByOwners(owners_database, files):
132 """Returns a map of files split by OWNERS file.
133
134 Returns:
135 A map where keys are paths to directories containing an OWNERS file and
136 values are lists of files sharing an OWNERS file.
137 """
138 files_split_by_owners = collections.defaultdict(list)
139 for f in files:
140 files_split_by_owners[owners_database.enclosing_dir_with_owners(
141 f.LocalPath())].append(f)
142 return files_split_by_owners
143
144
Chris Watkinsba28e462017-12-13 11:22:17 +1100145def PrintClInfo(cl_index, num_cls, directory, file_paths, description,
146 reviewers):
147 """Prints info about a CL.
148
149 Args:
150 cl_index: The index of this CL in the list of CLs to upload.
151 num_cls: The total number of CLs that will be uploaded.
152 directory: Path to the directory that contains the OWNERS file for which
153 to upload a CL.
154 file_paths: A list of files in this CL.
155 description: The CL description.
156 reviewers: A set of reviewers for this CL.
157 """
158 description_lines = FormatDescriptionOrComment(description,
159 directory).splitlines()
160 indented_description = '\n'.join([' ' + l for l in description_lines])
161
162 print 'CL {}/{}'.format(cl_index, num_cls)
163 print 'Path: {}'.format(directory)
164 print 'Reviewers: {}'.format(', '.join(reviewers))
165 print '\n' + indented_description + '\n'
166 print '\n'.join(file_paths)
167 print
168
169
Stephen Martiniscb326682018-08-29 21:06:30 +0000170def SplitCl(description_file, comment_file, changelist, cmd_upload, dry_run,
171 cq_dry_run):
Francois Dorayd42c6812017-05-30 15:10:20 -0400172 """"Splits a branch into smaller branches and uploads CLs.
173
174 Args:
175 description_file: File containing the description of uploaded CLs.
176 comment_file: File containing the comment of uploaded CLs.
177 changelist: The Changelist class.
178 cmd_upload: The function associated with the git cl upload command.
Chris Watkinsba28e462017-12-13 11:22:17 +1100179 dry_run: Whether this is a dry run (no branches or CLs created).
Stephen Martiniscb326682018-08-29 21:06:30 +0000180 cq_dry_run: If CL uploads should also do a cq dry run.
Francois Dorayd42c6812017-05-30 15:10:20 -0400181
182 Returns:
183 0 in case of success. 1 in case of error.
184 """
185 description = AddUploadedByGitClSplitToDescription(ReadFile(description_file))
186 comment = ReadFile(comment_file) if comment_file else None
187
188 try:
Chris Watkinsba28e462017-12-13 11:22:17 +1100189 EnsureInGitRepository()
Francois Dorayd42c6812017-05-30 15:10:20 -0400190
191 cl = changelist()
192 change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
193 files = change.AffectedFiles()
194
195 if not files:
196 print 'Cannot split an empty CL.'
197 return 1
198
199 author = git.run('config', 'user.email').strip() or None
200 refactor_branch = git.current_branch()
Gabriel Charette09baacd2017-11-09 13:30:41 -0500201 assert refactor_branch, "Can't run from detached branch."
Francois Dorayd42c6812017-05-30 15:10:20 -0400202 refactor_branch_upstream = git.upstream(refactor_branch)
Gabriel Charette09baacd2017-11-09 13:30:41 -0500203 assert refactor_branch_upstream, \
204 "Branch %s must have an upstream." % refactor_branch
Francois Dorayd42c6812017-05-30 15:10:20 -0400205
206 owners_database = owners.Database(change.RepositoryRoot(), file, os.path)
207 owners_database.load_data_needed_for([f.LocalPath() for f in files])
208
Chris Watkinsba28e462017-12-13 11:22:17 +1100209 files_split_by_owners = GetFilesSplitByOwners(owners_database, files)
Francois Dorayd42c6812017-05-30 15:10:20 -0400210
Chris Watkinsba28e462017-12-13 11:22:17 +1100211 num_cls = len(files_split_by_owners)
212 print('Will split current branch (' + refactor_branch + ') into ' +
213 str(num_cls) + ' CLs.\n')
Stephen Martinisf53f82c2018-09-07 20:58:05 +0000214 if cq_dry_run and num_cls > CL_SPLIT_FORCE_LIMIT:
Stephen Martiniscb326682018-08-29 21:06:30 +0000215 print (
216 'This will generate "%r" CLs. This many CLs can potentially generate'
217 ' too much load on the build infrastructure. Please email'
218 ' infra-dev@chromium.org to ensure that this won\'t break anything.'
219 ' The infra team reserves the right to cancel your jobs if they are'
220 ' overloading the CQ.') % num_cls
221 answer = raw_input('Proceed? (y/n):')
222 if answer.lower() != 'y':
223 return 0
Francois Dorayd42c6812017-05-30 15:10:20 -0400224
Chris Watkinsba28e462017-12-13 11:22:17 +1100225 for cl_index, (directory, files) in \
226 enumerate(files_split_by_owners.iteritems(), 1):
Francois Dorayd42c6812017-05-30 15:10:20 -0400227 # Use '/' as a path separator in the branch name and the CL description
228 # and comment.
229 directory = directory.replace(os.path.sep, '/')
Chris Watkinsba28e462017-12-13 11:22:17 +1100230 file_paths = [f.LocalPath() for f in files]
231 reviewers = owners_database.reviewers_for(file_paths, author)
232
233 if dry_run:
234 PrintClInfo(cl_index, num_cls, directory, file_paths, description,
235 reviewers)
236 else:
237 UploadCl(refactor_branch, refactor_branch_upstream, directory, files,
Stephen Martiniscb326682018-08-29 21:06:30 +0000238 description, comment, reviewers, changelist, cmd_upload,
239 cq_dry_run)
Francois Dorayd42c6812017-05-30 15:10:20 -0400240
241 # Go back to the original branch.
242 git.run('checkout', refactor_branch)
243
244 except subprocess2.CalledProcessError as cpe:
245 sys.stderr.write(cpe.stderr)
246 return 1
247 return 0