blob: d974eb71558252841f2de4acfcf5d9bfd912abfe [file] [log] [blame]
Chris Sosaefc35722012-09-11 18:55:37 -07001#!/usr/bin/python
2
3# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7""" This simple program takes changes from gerrit/gerrit-int and creates new
8changes for them on the desired branch using your gerrit/ssh credentials. To
9specify a change on gerrit-int, you must prefix the change with a *.
10
11Note that this script is best used from within an existing checkout of
12Chromium OS that already has the changes you want merged to the branch in it
13i.e. if you want to push changes to crosutils.git, you must have src/scripts
14checked out. If this isn't true e.g. you are running this script from a
15minilayout or trying to upload an internal change from a non internal checkout,
16you must specify some extra options: use the --nomirror option and use -e to
17specify your email address. This tool will then checkout the git repo fresh
18using the credentials for the -e/email you specified and upload the change. Note
19you can always use this method but it's slower than the "mirrored" method and
20requires more typing :(.
21
22Examples:
23 cros_merge_to_branch 32027 32030 32031 release-R22.2723.B
24
25This will create changes for 32027, 32030 and 32031 on the R22 branch. To look
26up the name of a branch, go into a git sub-dir and type 'git branch -a' and the
27find the branch you want to merge to. If you want to upload internal changes
28from gerrit-int, you must prefix the gerrit change number with a * e.g.
29
30 cros_merge_to_branch *26108 release-R22.2723.B
31
32For more information on how to do this yourself you can go here:
33http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/working-on-a-br\
34anch
35"""
36
37import logging
38import os
Mike Frysinger187af412012-10-27 04:27:04 -040039import re
Chris Sosaefc35722012-09-11 18:55:37 -070040import shutil
41import sys
42import tempfile
43
44from chromite.buildbot import constants
Chris Sosaefc35722012-09-11 18:55:37 -070045from chromite.buildbot import repository
46from chromite.lib import commandline
47from chromite.lib import cros_build_lib
Brian Harring511055e2012-10-10 02:58:59 -070048from chromite.lib import gerrit
David James97d95872012-11-16 15:09:56 -080049from chromite.lib import git
Brian Harring511055e2012-10-10 02:58:59 -070050from chromite.lib import patch as cros_patch
Chris Sosaefc35722012-09-11 18:55:37 -070051
52
53_USAGE = """
54cros_merge_to_branch [*]change_number1 [[*]change_number2 ...] branch\n\n %s
55""" % __doc__
56
57
58def _GetParser():
59 """Returns the parser to use for this module."""
60 parser = commandline.OptionParser(usage=_USAGE)
61 parser.add_option('-d', '--draft', default=False, action='store_true',
62 help='Upload a draft to Gerrit rather than a change.')
Mike Frysingerb6c6fab2012-12-06 00:00:24 -050063 parser.add_option('-n', '--dry-run', default=False, action='store_true',
64 dest='dryrun',
Chris Sosaefc35722012-09-11 18:55:37 -070065 help='Apply changes locally but do not upload them.')
66 parser.add_option('-e', '--email',
67 help='If specified, use this email instead of '
68 'the email you would upload changes as. Must be set if '
69 'nomirror is set.')
70 parser.add_option('--nomirror', default=True, dest='mirror',
71 action='store_false', help='Disable mirroring -- requires '
72 'email to be set.')
73 parser.add_option('--nowipe', default=True, dest='wipe', action='store_false',
74 help='Do not wipe the work directory after finishing.')
75 return parser
76
77
78def _UploadChangeToBranch(work_dir, patch, branch, draft, dryrun):
79 """Creates a new change from GerritPatch |patch| to |branch| from |work_dir|.
80
81 Args:
82 patch: Instance of GerritPatch to upload.
83 branch: Branch to upload to.
84 work_dir: Local directory where repository is checked out in.
85 draft: If True, upload to refs/draft/|branch| rather than refs/for/|branch|.
86 dryrun: Don't actually upload a change but go through all the steps up to
Mike Frysingerb6c6fab2012-12-06 00:00:24 -050087 and including git push --dry-run.
Chris Sosaefc35722012-09-11 18:55:37 -070088 """
89 upload_type = 'drafts' if draft else 'for'
Mike Frysinger187af412012-10-27 04:27:04 -040090 # Download & setup the patch if need be.
91 patch.Fetch(work_dir)
Chris Sosaefc35722012-09-11 18:55:37 -070092 # Apply the actual change.
93 patch.CherryPick(work_dir, inflight=True, leave_dirty=True)
94
95 # Get the new sha1 after apply.
David James97d95872012-11-16 15:09:56 -080096 new_sha1 = git.GetGitRepoRevision(work_dir)
Chris Sosaefc35722012-09-11 18:55:37 -070097
Mike Frysinger187af412012-10-27 04:27:04 -040098 # If the sha1 has changed, then rewrite the commit message.
99 if patch.sha1 != new_sha1:
100 msg = []
101 reviewers = set()
102 for line in patch.commit_message.splitlines():
103 if line.startswith('Reviewed-on: '):
104 line = 'Previous-' + line
105 elif line.startswith('Commit-Ready: ') or \
106 line.startswith('Reviewed-by: ') or \
107 line.startswith('Tested-by: '):
108 # If the tag is malformed, or the person lacks a name,
109 # then that's just too bad -- throw it away.
110 ele = re.split('[<>@]+', line)
111 if len(ele) == 4:
112 reviewers.add('@'.join(ele[-3:-1]))
113 continue
114 msg.append(line)
115 msg += [
116 '(cherry picked from commit %s)' % patch.sha1,
117 ]
118 git.RunGit(work_dir, ['commit', '--amend', '-F', '-'],
119 input='\n'.join(msg).encode('utf8'))
120
121 # Get the new sha1 after rewriting the commit message.
122 new_sha1 = git.GetGitRepoRevision(work_dir)
123
Chris Sosaefc35722012-09-11 18:55:37 -0700124 # Create and use a LocalPatch to Upload the change to Gerrit.
125 local_patch = cros_patch.LocalPatch(
126 work_dir, patch.project_url, constants.PATCH_BRANCH,
127 patch.tracking_branch, patch.remote, new_sha1)
Mike Frysinger075e6592012-10-27 04:41:09 -0400128 return local_patch.Upload(
Chris Sosaefc35722012-09-11 18:55:37 -0700129 patch.project_url, 'refs/%s/%s' % (upload_type, branch),
Mike Frysinger187af412012-10-27 04:27:04 -0400130 carbon_copy=False, dryrun=dryrun, reviewers=reviewers)
Chris Sosaefc35722012-09-11 18:55:37 -0700131
132
133def _SetupWorkDirectoryForPatch(work_dir, patch, branch, manifest, email):
134 """Set up local dir for uploading changes to the given patch's project."""
135 logging.info('Setting up dir %s for uploading changes to %s', work_dir,
136 patch.project_url)
137
138 # Clone the git repo from reference if we have a pointer to a
139 # ManifestCheckout object.
140 reference = None
141 if manifest:
142 reference = os.path.join(constants.SOURCE_ROOT,
143 manifest.GetProjectPath(patch.project))
144 # Use the email if email wasn't specified.
145 if not email:
David James97d95872012-11-16 15:09:56 -0800146 email = git.GetProjectUserEmail(reference)
Chris Sosaefc35722012-09-11 18:55:37 -0700147
148 repository.CloneGitRepo(work_dir, patch.project_url, reference=reference)
149
150 # Set the git committer.
David James97d95872012-11-16 15:09:56 -0800151 git.RunGit(work_dir, ['config', '--replace-all', 'user.email', email])
Chris Sosaefc35722012-09-11 18:55:37 -0700152
David James97d95872012-11-16 15:09:56 -0800153 mbranch = git.MatchSingleBranchName(
Mike Frysinger94f91be2012-10-19 16:09:06 -0400154 work_dir, branch, namespace='refs/remotes/origin/')
Mike Frysinger35887c62012-12-12 23:29:20 -0500155 if branch != mbranch:
156 logging.info('Auto resolved branch name "%s" to "%s"', branch, mbranch)
Mike Frysinger94f91be2012-10-19 16:09:06 -0400157 branch = mbranch
158
Chris Sosaefc35722012-09-11 18:55:37 -0700159 # Finally, create a local branch for uploading changes to the given remote
160 # branch.
David James97d95872012-11-16 15:09:56 -0800161 git.CreatePushBranch(
Chris Sosaefc35722012-09-11 18:55:37 -0700162 constants.PATCH_BRANCH, work_dir, sync=False,
163 remote_push_branch=('ignore', 'origin/%s' % branch))
164
Mike Frysinger94f91be2012-10-19 16:09:06 -0400165 return branch
166
Chris Sosaefc35722012-09-11 18:55:37 -0700167
168def _ManifestContainsAllPatches(manifest, patches):
169 """Returns true if the given manifest contains all the patches.
170
171 Args:
David James97d95872012-11-16 15:09:56 -0800172 manifest - an instance of git.Manifest
Chris Sosaefc35722012-09-11 18:55:37 -0700173 patches - a collection GerritPatch objects.
174 """
175 for patch in patches:
176 project_path = None
177 if manifest.ProjectExists(patch.project):
178 project_path = manifest.GetProjectPath(patch.project)
179
180 if not project_path:
181 logging.error('Your manifest does not have the repository %s for '
182 'change %s. Please re-run with --nomirror and '
183 '--email set', patch.project, patch.gerrit_number)
184 return False
185
186 return True
187
188
189def main(argv):
190 parser = _GetParser()
191 options, args = parser.parse_args(argv)
192
193 if len(args) < 2:
194 parser.error('Not enough arguments specified')
195
196 changes = args[0:-1]
Brian Harring511055e2012-10-10 02:58:59 -0700197 patches = gerrit.GetGerritPatchInfo(changes)
Chris Sosaefc35722012-09-11 18:55:37 -0700198 branch = args[-1]
199
200 # Suppress all cros_build_lib info output unless we're running debug.
201 if not options.debug:
202 cros_build_lib.logger.setLevel(logging.ERROR)
203
204 # Get a pointer to your repo checkout to look up the local project paths for
205 # both email addresses and for using your checkout as a git mirror.
206 manifest = None
207 if options.mirror:
David James97d95872012-11-16 15:09:56 -0800208 manifest = git.ManifestCheckout.Cached(constants.SOURCE_ROOT)
Chris Sosaefc35722012-09-11 18:55:37 -0700209 if not _ManifestContainsAllPatches(manifest, patches):
210 return 1
211 else:
212 if not options.email:
213 chromium_email = '%s@chromium.org' % os.environ['USER']
214 logging.info('--nomirror set without email, using %s', chromium_email)
215 options.email = chromium_email
216
217 index = 0
218 work_dir = None
219 root_work_dir = tempfile.mkdtemp(prefix='cros_merge_to_branch')
220 try:
221 for index, (change, patch) in enumerate(zip(changes, patches)):
222 # We only clone the project and set the committer the first time.
223 work_dir = os.path.join(root_work_dir, patch.project)
224 if not os.path.isdir(work_dir):
Mike Frysinger94f91be2012-10-19 16:09:06 -0400225 branch = _SetupWorkDirectoryForPatch(work_dir, patch, branch, manifest,
226 options.email)
Chris Sosaefc35722012-09-11 18:55:37 -0700227
228 # Now that we have the project checked out, let's apply our change and
229 # create a new change on Gerrit.
230 logging.info('Uploading change %s to branch %s', change, branch)
Mike Frysinger075e6592012-10-27 04:41:09 -0400231 url = _UploadChangeToBranch(work_dir, patch, branch, options.draft,
232 options.dryrun)
Chris Sosaefc35722012-09-11 18:55:37 -0700233 logging.info('Successfully uploaded %s to %s', change, branch)
Mike Frysinger075e6592012-10-27 04:41:09 -0400234 if url:
235 logging.info(' URL: %s', url)
Chris Sosaefc35722012-09-11 18:55:37 -0700236
Mike Frysinger94f91be2012-10-19 16:09:06 -0400237 except (cros_build_lib.RunCommandError, cros_patch.ApplyPatchException,
David James97d95872012-11-16 15:09:56 -0800238 git.AmbiguousBranchName) as e:
Chris Sosaefc35722012-09-11 18:55:37 -0700239 # Tell the user how far we got.
240 good_changes = changes[:index]
241 bad_changes = changes[index:]
242
243 logging.warning('############## SOME CHANGES FAILED TO UPLOAD ############')
244
245 if good_changes:
246 logging.info('Successfully uploaded change(s) %s', ' '.join(good_changes))
247
248 # Printing out the error here so that we can see exactly what failed. This
249 # is especially useful to debug without using --debug.
250 logging.error('Upload failed with %s', str(e).strip())
251 if not options.wipe:
252 logging.info('Not wiping the directory. You can inspect the failed '
Mike Frysinger9f606d72012-10-12 00:55:57 -0400253 'change at %s; After fixing the change (if trivial) you can '
Chris Sosaefc35722012-09-11 18:55:37 -0700254 'try to upload the change by running:\n'
255 'git push %s HEAD:refs/for/%s', work_dir, patch.project_url,
256 branch)
257 else:
258 logging.error('--nowipe not set thus deleting the work directory. If you '
259 'wish to debug this, re-run the script with change(s) '
Mike Frysinger1244fb22012-10-19 14:14:10 -0400260 '%s and --nowipe by running:\n %s %s %s --nowipe',
261 ' '.join(bad_changes), sys.argv[0], ' '.join(bad_changes),
262 branch)
Chris Sosaefc35722012-09-11 18:55:37 -0700263
264 # Suppress the stack trace if we're not debugging.
265 if options.debug:
266 raise
267 else:
268 return 1
269
270 finally:
271 if options.wipe:
272 shutil.rmtree(root_work_dir)
273
274 if options.dryrun:
Mike Frysingerb6c6fab2012-12-06 00:00:24 -0500275 logging.info('Success! To actually upload changes, re-run without '
276 '--dry-run.')
Chris Sosaefc35722012-09-11 18:55:37 -0700277 else:
278 logging.info('Successfully uploaded all changes requested.')
279
280 return 0