blob: 32203fc570e112f1624c903d960e981bb9926fdc [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
22def ReadFile(file_path):
23 """Returns the content of |file_path|."""
24 with open(file_path) as f:
25 content = f.read()
26 return content
27
28
29def EnsureInGitRepository():
30 """Throws an exception if the current directory is not a git repository."""
31 git.run('rev-parse')
32
33
34def CreateBranchForDirectory(prefix, directory, upstream):
35 """Creates a branch named |prefix| + "_" + |directory| + "_split".
36
37 Return false if the branch already exists. |upstream| is used as upstream for
38 the created branch.
39 """
40 existing_branches = set(git.branches(use_limit = False))
41 branch_name = prefix + '_' + directory + '_split'
42 if branch_name in existing_branches:
43 return False
44 git.run('checkout', '-t', upstream, '-b', branch_name)
45 return True
46
47
48def FormatDescriptionOrComment(txt, directory):
49 """Replaces $directory with |directory| in |txt|."""
50 return txt.replace('$directory', '/' + directory)
51
52
53def AddUploadedByGitClSplitToDescription(description):
54 """Adds a 'This CL was uploaded by git cl split.' line to |description|.
55
56 The line is added before footers, or at the end of |description| if it has no
57 footers.
58 """
59 split_footers = git_footers.split_footers(description)
60 lines = split_footers[0]
61 if not lines[-1] or lines[-1].isspace():
62 lines = lines + ['']
63 lines = lines + ['This CL was uploaded by git cl split.']
64 if split_footers[1]:
65 lines += [''] + split_footers[1]
66 return '\n'.join(lines)
67
68
69def UploadCl(refactor_branch, refactor_branch_upstream, directory, files,
Chris Watkinsba28e462017-12-13 11:22:17 +110070 description, comment, reviewers, changelist, cmd_upload):
Francois Dorayd42c6812017-05-30 15:10:20 -040071 """Uploads a CL with all changes to |files| in |refactor_branch|.
72
73 Args:
74 refactor_branch: Name of the branch that contains the changes to upload.
75 refactor_branch_upstream: Name of the upstream of |refactor_branch|.
76 directory: Path to the directory that contains the OWNERS file for which
77 to upload a CL.
78 files: List of AffectedFile instances to include in the uploaded CL.
Francois Dorayd42c6812017-05-30 15:10:20 -040079 description: Description of the uploaded CL.
80 comment: Comment to post on the uploaded CL.
Chris Watkinsba28e462017-12-13 11:22:17 +110081 reviewers: A set of reviewers for the CL.
Francois Dorayd42c6812017-05-30 15:10:20 -040082 changelist: The Changelist class.
83 cmd_upload: The function associated with the git cl upload command.
84 """
Francois Dorayd42c6812017-05-30 15:10:20 -040085 # Create a branch.
86 if not CreateBranchForDirectory(
87 refactor_branch, directory, refactor_branch_upstream):
88 print 'Skipping ' + directory + ' for which a branch already exists.'
89 return
90
91 # Checkout all changes to files in |files|.
92 deleted_files = [f.AbsoluteLocalPath() for f in files if f.Action() == 'D']
93 if deleted_files:
94 git.run(*['rm'] + deleted_files)
95 modified_files = [f.AbsoluteLocalPath() for f in files if f.Action() != 'D']
96 if modified_files:
97 git.run(*['checkout', refactor_branch, '--'] + modified_files)
98
99 # Commit changes. The temporary file is created with delete=False so that it
100 # can be deleted manually after git has read it rather than automatically
101 # when it is closed.
102 with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
103 tmp_file.write(FormatDescriptionOrComment(description, directory))
104 # Close the file to let git open it at the next line.
105 tmp_file.close()
106 git.run('commit', '-F', tmp_file.name)
107 os.remove(tmp_file.name)
108
109 # Upload a CL.
Francois Dorayd42c6812017-05-30 15:10:20 -0400110 upload_args = ['-f', '--cq-dry-run', '-r', ','.join(reviewers)]
111 if not comment:
Aaron Gablee5adf612017-07-14 10:43:58 -0700112 upload_args.append('--send-mail')
Francois Dorayd42c6812017-05-30 15:10:20 -0400113 print 'Uploading CL for ' + directory + '.'
114 cmd_upload(upload_args)
115 if comment:
Aaron Gablee5adf612017-07-14 10:43:58 -0700116 changelist().AddComment(FormatDescriptionOrComment(comment, directory),
117 publish=True)
Francois Dorayd42c6812017-05-30 15:10:20 -0400118
119
120def GetFilesSplitByOwners(owners_database, files):
121 """Returns a map of files split by OWNERS file.
122
123 Returns:
124 A map where keys are paths to directories containing an OWNERS file and
125 values are lists of files sharing an OWNERS file.
126 """
127 files_split_by_owners = collections.defaultdict(list)
128 for f in files:
129 files_split_by_owners[owners_database.enclosing_dir_with_owners(
130 f.LocalPath())].append(f)
131 return files_split_by_owners
132
133
Chris Watkinsba28e462017-12-13 11:22:17 +1100134def PrintClInfo(cl_index, num_cls, directory, file_paths, description,
135 reviewers):
136 """Prints info about a CL.
137
138 Args:
139 cl_index: The index of this CL in the list of CLs to upload.
140 num_cls: The total number of CLs that will be uploaded.
141 directory: Path to the directory that contains the OWNERS file for which
142 to upload a CL.
143 file_paths: A list of files in this CL.
144 description: The CL description.
145 reviewers: A set of reviewers for this CL.
146 """
147 description_lines = FormatDescriptionOrComment(description,
148 directory).splitlines()
149 indented_description = '\n'.join([' ' + l for l in description_lines])
150
151 print 'CL {}/{}'.format(cl_index, num_cls)
152 print 'Path: {}'.format(directory)
153 print 'Reviewers: {}'.format(', '.join(reviewers))
154 print '\n' + indented_description + '\n'
155 print '\n'.join(file_paths)
156 print
157
158
159def SplitCl(description_file, comment_file, changelist, cmd_upload, dry_run):
Francois Dorayd42c6812017-05-30 15:10:20 -0400160 """"Splits a branch into smaller branches and uploads CLs.
161
162 Args:
163 description_file: File containing the description of uploaded CLs.
164 comment_file: File containing the comment of uploaded CLs.
165 changelist: The Changelist class.
166 cmd_upload: The function associated with the git cl upload command.
Chris Watkinsba28e462017-12-13 11:22:17 +1100167 dry_run: Whether this is a dry run (no branches or CLs created).
Francois Dorayd42c6812017-05-30 15:10:20 -0400168
169 Returns:
170 0 in case of success. 1 in case of error.
171 """
172 description = AddUploadedByGitClSplitToDescription(ReadFile(description_file))
173 comment = ReadFile(comment_file) if comment_file else None
174
175 try:
Chris Watkinsba28e462017-12-13 11:22:17 +1100176 EnsureInGitRepository()
Francois Dorayd42c6812017-05-30 15:10:20 -0400177
178 cl = changelist()
179 change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
180 files = change.AffectedFiles()
181
182 if not files:
183 print 'Cannot split an empty CL.'
184 return 1
185
186 author = git.run('config', 'user.email').strip() or None
187 refactor_branch = git.current_branch()
Gabriel Charette09baacd2017-11-09 13:30:41 -0500188 assert refactor_branch, "Can't run from detached branch."
Francois Dorayd42c6812017-05-30 15:10:20 -0400189 refactor_branch_upstream = git.upstream(refactor_branch)
Gabriel Charette09baacd2017-11-09 13:30:41 -0500190 assert refactor_branch_upstream, \
191 "Branch %s must have an upstream." % refactor_branch
Francois Dorayd42c6812017-05-30 15:10:20 -0400192
193 owners_database = owners.Database(change.RepositoryRoot(), file, os.path)
194 owners_database.load_data_needed_for([f.LocalPath() for f in files])
195
Chris Watkinsba28e462017-12-13 11:22:17 +1100196 files_split_by_owners = GetFilesSplitByOwners(owners_database, files)
Francois Dorayd42c6812017-05-30 15:10:20 -0400197
Chris Watkinsba28e462017-12-13 11:22:17 +1100198 num_cls = len(files_split_by_owners)
199 print('Will split current branch (' + refactor_branch + ') into ' +
200 str(num_cls) + ' CLs.\n')
Francois Dorayd42c6812017-05-30 15:10:20 -0400201
Chris Watkinsba28e462017-12-13 11:22:17 +1100202 for cl_index, (directory, files) in \
203 enumerate(files_split_by_owners.iteritems(), 1):
Francois Dorayd42c6812017-05-30 15:10:20 -0400204 # Use '/' as a path separator in the branch name and the CL description
205 # and comment.
206 directory = directory.replace(os.path.sep, '/')
Chris Watkinsba28e462017-12-13 11:22:17 +1100207 file_paths = [f.LocalPath() for f in files]
208 reviewers = owners_database.reviewers_for(file_paths, author)
209
210 if dry_run:
211 PrintClInfo(cl_index, num_cls, directory, file_paths, description,
212 reviewers)
213 else:
214 UploadCl(refactor_branch, refactor_branch_upstream, directory, files,
215 description, comment, reviewers, changelist, cmd_upload)
Francois Dorayd42c6812017-05-30 15:10:20 -0400216
217 # Go back to the original branch.
218 git.run('checkout', refactor_branch)
219
220 except subprocess2.CalledProcessError as cpe:
221 sys.stderr.write(cpe.stderr)
222 return 1
223 return 0