blob: 37190295a8d88cf460b754db198fec96b9cec4e9 [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
19import owners
20import owners_finder
21
22import git_common as git
23
24
Stephen Martinisf53f82c2018-09-07 20:58:05 +000025# If a call to `git cl split` will generate more than this number of CLs, the
26# command will prompt the user to make sure they know what they're doing. Large
27# numbers of CLs generated by `git cl split` have caused infrastructure issues
28# in the past.
29CL_SPLIT_FORCE_LIMIT = 10
30
31
Francois Dorayd42c6812017-05-30 15:10:20 -040032def ReadFile(file_path):
33 """Returns the content of |file_path|."""
34 with open(file_path) as f:
35 content = f.read()
36 return content
37
38
39def EnsureInGitRepository():
40 """Throws an exception if the current directory is not a git repository."""
41 git.run('rev-parse')
42
43
Edward Lemurac5c55f2020-02-29 00:17:16 +000044def CreateBranchForDirectory(prefix, directory, upstream):
45 """Creates a branch named |prefix| + "_" + |directory| + "_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))
Edward Lemurac5c55f2020-02-29 00:17:16 +000051 branch_name = prefix + '_' + directory + '_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
Edward Lemurac5c55f2020-02-29 00:17:16 +000058def FormatDescriptionOrComment(txt, directory):
59 """Replaces $directory with |directory| in |txt|."""
60 return txt.replace('$directory', '/' + directory)
Francois Dorayd42c6812017-05-30 15:10:20 -040061
62
63def AddUploadedByGitClSplitToDescription(description):
64 """Adds a 'This CL was uploaded by git cl split.' line to |description|.
65
66 The line is added before footers, or at the end of |description| if it has no
67 footers.
68 """
69 split_footers = git_footers.split_footers(description)
70 lines = split_footers[0]
71 if not lines[-1] or lines[-1].isspace():
72 lines = lines + ['']
73 lines = lines + ['This CL was uploaded by git cl split.']
74 if split_footers[1]:
75 lines += [''] + split_footers[1]
76 return '\n'.join(lines)
77
78
Edward Lemurac5c55f2020-02-29 00:17:16 +000079def UploadCl(refactor_branch, refactor_branch_upstream, directory, files,
80 description, comment, reviewers, changelist, cmd_upload,
81 cq_dry_run, enable_auto_submit):
Francois Dorayd42c6812017-05-30 15:10:20 -040082 """Uploads a CL with all changes to |files| in |refactor_branch|.
83
84 Args:
85 refactor_branch: Name of the branch that contains the changes to upload.
86 refactor_branch_upstream: Name of the upstream of |refactor_branch|.
87 directory: Path to the directory that contains the OWNERS file for which
88 to upload a CL.
89 files: List of AffectedFile instances to include in the uploaded CL.
Francois Dorayd42c6812017-05-30 15:10:20 -040090 description: Description of the uploaded CL.
91 comment: Comment to post on the uploaded CL.
Edward Lemurac5c55f2020-02-29 00:17:16 +000092 reviewers: A set of reviewers for the CL.
Francois Dorayd42c6812017-05-30 15:10:20 -040093 changelist: The Changelist class.
94 cmd_upload: The function associated with the git cl upload command.
Stephen Martiniscb326682018-08-29 21:06:30 +000095 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +000096 enable_auto_submit: If CL uploads should also enable auto submit.
Francois Dorayd42c6812017-05-30 15:10:20 -040097 """
Francois Dorayd42c6812017-05-30 15:10:20 -040098 # Create a branch.
Edward Lemurac5c55f2020-02-29 00:17:16 +000099 if not CreateBranchForDirectory(
100 refactor_branch, directory, refactor_branch_upstream):
101 print('Skipping ' + directory + ' for which a branch already exists.')
Francois Dorayd42c6812017-05-30 15:10:20 -0400102 return
103
104 # Checkout all changes to files in |files|.
105 deleted_files = [f.AbsoluteLocalPath() for f in files if f.Action() == 'D']
106 if deleted_files:
107 git.run(*['rm'] + deleted_files)
108 modified_files = [f.AbsoluteLocalPath() for f in files if f.Action() != 'D']
109 if modified_files:
110 git.run(*['checkout', refactor_branch, '--'] + modified_files)
111
112 # Commit changes. The temporary file is created with delete=False so that it
113 # can be deleted manually after git has read it rather than automatically
114 # when it is closed.
Edward Lemur1773f372020-02-22 00:27:14 +0000115 with gclient_utils.temporary_file() as tmp_file:
116 gclient_utils.FileWrite(
Edward Lemurac5c55f2020-02-29 00:17:16 +0000117 tmp_file, FormatDescriptionOrComment(description, directory))
Edward Lemur1773f372020-02-22 00:27:14 +0000118 git.run('commit', '-F', tmp_file)
Francois Dorayd42c6812017-05-30 15:10:20 -0400119
120 # Upload a CL.
Edward Lemurac5c55f2020-02-29 00:17:16 +0000121 upload_args = ['-f', '-r', ','.join(reviewers)]
Stephen Martiniscb326682018-08-29 21:06:30 +0000122 if cq_dry_run:
123 upload_args.append('--cq-dry-run')
Francois Dorayd42c6812017-05-30 15:10:20 -0400124 if not comment:
Aaron Gablee5adf612017-07-14 10:43:58 -0700125 upload_args.append('--send-mail')
Takuto Ikuta51eca592019-02-14 19:40:52 +0000126 if enable_auto_submit:
127 upload_args.append('--enable-auto-submit')
Raul Tambre80ee78e2019-05-06 22:41:05 +0000128 print('Uploading CL for ' + directory + '.')
Francois Dorayd42c6812017-05-30 15:10:20 -0400129 cmd_upload(upload_args)
130 if comment:
Edward Lemurac5c55f2020-02-29 00:17:16 +0000131 changelist().AddComment(FormatDescriptionOrComment(comment, directory),
132 publish=True)
Francois Dorayd42c6812017-05-30 15:10:20 -0400133
134
Edward Lemurac5c55f2020-02-29 00:17:16 +0000135def GetFilesSplitByOwners(owners_database, files):
Francois Dorayd42c6812017-05-30 15:10:20 -0400136 """Returns a map of files split by OWNERS file.
137
138 Returns:
139 A map where keys are paths to directories containing an OWNERS file and
140 values are lists of files sharing an OWNERS file.
141 """
Edward Lemurac5c55f2020-02-29 00:17:16 +0000142 files_split_by_owners = collections.defaultdict(list)
Francois Dorayd42c6812017-05-30 15:10:20 -0400143 for f in files:
Edward Lemurac5c55f2020-02-29 00:17:16 +0000144 files_split_by_owners[owners_database.enclosing_dir_with_owners(
145 f.LocalPath())].append(f)
146 return files_split_by_owners
Francois Dorayd42c6812017-05-30 15:10:20 -0400147
148
Chris Watkinsba28e462017-12-13 11:22:17 +1100149def PrintClInfo(cl_index, num_cls, directory, file_paths, description,
Edward Lemurac5c55f2020-02-29 00:17:16 +0000150 reviewers):
Chris Watkinsba28e462017-12-13 11:22:17 +1100151 """Prints info about a CL.
152
153 Args:
154 cl_index: The index of this CL in the list of CLs to upload.
155 num_cls: The total number of CLs that will be uploaded.
156 directory: Path to the directory that contains the OWNERS file for which
157 to upload a CL.
158 file_paths: A list of files in this CL.
159 description: The CL description.
Edward Lemurac5c55f2020-02-29 00:17:16 +0000160 reviewers: A set of reviewers for this CL.
Chris Watkinsba28e462017-12-13 11:22:17 +1100161 """
Edward Lemurac5c55f2020-02-29 00:17:16 +0000162 description_lines = FormatDescriptionOrComment(description,
163 directory).splitlines()
Chris Watkinsba28e462017-12-13 11:22:17 +1100164 indented_description = '\n'.join([' ' + l for l in description_lines])
165
Raul Tambre80ee78e2019-05-06 22:41:05 +0000166 print('CL {}/{}'.format(cl_index, num_cls))
167 print('Path: {}'.format(directory))
Edward Lemurac5c55f2020-02-29 00:17:16 +0000168 print('Reviewers: {}'.format(', '.join(reviewers)))
Raul Tambre80ee78e2019-05-06 22:41:05 +0000169 print('\n' + indented_description + '\n')
170 print('\n'.join(file_paths))
171 print()
Chris Watkinsba28e462017-12-13 11:22:17 +1100172
173
Stephen Martiniscb326682018-08-29 21:06:30 +0000174def SplitCl(description_file, comment_file, changelist, cmd_upload, dry_run,
Takuto Ikuta51eca592019-02-14 19:40:52 +0000175 cq_dry_run, enable_auto_submit):
Francois Dorayd42c6812017-05-30 15:10:20 -0400176 """"Splits a branch into smaller branches and uploads CLs.
177
178 Args:
179 description_file: File containing the description of uploaded CLs.
180 comment_file: File containing the comment of uploaded CLs.
181 changelist: The Changelist class.
182 cmd_upload: The function associated with the git cl upload command.
Chris Watkinsba28e462017-12-13 11:22:17 +1100183 dry_run: Whether this is a dry run (no branches or CLs created).
Stephen Martiniscb326682018-08-29 21:06:30 +0000184 cq_dry_run: If CL uploads should also do a cq dry run.
Takuto Ikuta51eca592019-02-14 19:40:52 +0000185 enable_auto_submit: If CL uploads should also enable auto submit.
Francois Dorayd42c6812017-05-30 15:10:20 -0400186
187 Returns:
188 0 in case of success. 1 in case of error.
189 """
190 description = AddUploadedByGitClSplitToDescription(ReadFile(description_file))
191 comment = ReadFile(comment_file) if comment_file else None
192
193 try:
Chris Watkinsba28e462017-12-13 11:22:17 +1100194 EnsureInGitRepository()
Francois Dorayd42c6812017-05-30 15:10:20 -0400195
196 cl = changelist()
Edward Lesmes7c34a222020-02-21 21:11:24 +0000197 change = cl.GetChange(cl.GetCommonAncestorWithUpstream())
Francois Dorayd42c6812017-05-30 15:10:20 -0400198 files = change.AffectedFiles()
199
200 if not files:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000201 print('Cannot split an empty CL.')
Francois Dorayd42c6812017-05-30 15:10:20 -0400202 return 1
203
204 author = git.run('config', 'user.email').strip() or None
205 refactor_branch = git.current_branch()
Gabriel Charette09baacd2017-11-09 13:30:41 -0500206 assert refactor_branch, "Can't run from detached branch."
Francois Dorayd42c6812017-05-30 15:10:20 -0400207 refactor_branch_upstream = git.upstream(refactor_branch)
Gabriel Charette09baacd2017-11-09 13:30:41 -0500208 assert refactor_branch_upstream, \
209 "Branch %s must have an upstream." % refactor_branch
Francois Dorayd42c6812017-05-30 15:10:20 -0400210
Edward Lemurb7f759f2020-03-04 21:20:56 +0000211 owners_database = owners.Database(change.RepositoryRoot(), open, os.path)
Francois Dorayd42c6812017-05-30 15:10:20 -0400212 owners_database.load_data_needed_for([f.LocalPath() for f in files])
213
Edward Lemurac5c55f2020-02-29 00:17:16 +0000214 files_split_by_owners = GetFilesSplitByOwners(owners_database, files)
Francois Dorayd42c6812017-05-30 15:10:20 -0400215
Edward Lemurac5c55f2020-02-29 00:17:16 +0000216 num_cls = len(files_split_by_owners)
217 print('Will split current branch (' + refactor_branch + ') into ' +
218 str(num_cls) + ' CLs.\n')
Stephen Martinisf53f82c2018-09-07 20:58:05 +0000219 if cq_dry_run and num_cls > CL_SPLIT_FORCE_LIMIT:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000220 print(
Stephen Martiniscb326682018-08-29 21:06:30 +0000221 'This will generate "%r" CLs. This many CLs can potentially generate'
222 ' too much load on the build infrastructure. Please email'
223 ' infra-dev@chromium.org to ensure that this won\'t break anything.'
224 ' The infra team reserves the right to cancel your jobs if they are'
Raul Tambre80ee78e2019-05-06 22:41:05 +0000225 ' overloading the CQ.' % num_cls)
Stephen Martiniscb326682018-08-29 21:06:30 +0000226 answer = raw_input('Proceed? (y/n):')
227 if answer.lower() != 'y':
228 return 0
Francois Dorayd42c6812017-05-30 15:10:20 -0400229
Edward Lemurac5c55f2020-02-29 00:17:16 +0000230 for cl_index, (directory, files) in \
231 enumerate(files_split_by_owners.items(), 1):
Francois Dorayd42c6812017-05-30 15:10:20 -0400232 # Use '/' as a path separator in the branch name and the CL description
233 # and comment.
Edward Lemurac5c55f2020-02-29 00:17:16 +0000234 directory = directory.replace(os.path.sep, '/')
235 file_paths = [f.LocalPath() for f in files]
236 reviewers = owners_database.reviewers_for(file_paths, author)
Chris Watkinsba28e462017-12-13 11:22:17 +1100237
238 if dry_run:
239 PrintClInfo(cl_index, num_cls, directory, file_paths, description,
Edward Lemurac5c55f2020-02-29 00:17:16 +0000240 reviewers)
Chris Watkinsba28e462017-12-13 11:22:17 +1100241 else:
Edward Lemurac5c55f2020-02-29 00:17:16 +0000242 UploadCl(refactor_branch, refactor_branch_upstream, directory, files,
243 description, comment, reviewers, changelist, cmd_upload,
244 cq_dry_run, enable_auto_submit)
Francois Dorayd42c6812017-05-30 15:10:20 -0400245
246 # Go back to the original branch.
247 git.run('checkout', refactor_branch)
248
249 except subprocess2.CalledProcessError as cpe:
250 sys.stderr.write(cpe.stderr)
251 return 1
252 return 0