blob: c5faed7df2a86ff70fb7ade74c4082bafa62b0fe [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
39import shutil
40import sys
41import tempfile
42
43from chromite.buildbot import constants
Chris Sosaefc35722012-09-11 18:55:37 -070044from chromite.buildbot import repository
45from chromite.lib import commandline
46from chromite.lib import cros_build_lib
Brian Harring511055e2012-10-10 02:58:59 -070047from chromite.lib import gerrit
David James97d95872012-11-16 15:09:56 -080048from chromite.lib import git
Brian Harring511055e2012-10-10 02:58:59 -070049from chromite.lib import patch as cros_patch
Chris Sosaefc35722012-09-11 18:55:37 -070050
51
52_USAGE = """
53cros_merge_to_branch [*]change_number1 [[*]change_number2 ...] branch\n\n %s
54""" % __doc__
55
56
57def _GetParser():
58 """Returns the parser to use for this module."""
59 parser = commandline.OptionParser(usage=_USAGE)
60 parser.add_option('-d', '--draft', default=False, action='store_true',
61 help='Upload a draft to Gerrit rather than a change.')
62 parser.add_option('--dryrun', default=False, action='store_true',
63 help='Apply changes locally but do not upload them.')
64 parser.add_option('-e', '--email',
65 help='If specified, use this email instead of '
66 'the email you would upload changes as. Must be set if '
67 'nomirror is set.')
68 parser.add_option('--nomirror', default=True, dest='mirror',
69 action='store_false', help='Disable mirroring -- requires '
70 'email to be set.')
71 parser.add_option('--nowipe', default=True, dest='wipe', action='store_false',
72 help='Do not wipe the work directory after finishing.')
73 return parser
74
75
76def _UploadChangeToBranch(work_dir, patch, branch, draft, dryrun):
77 """Creates a new change from GerritPatch |patch| to |branch| from |work_dir|.
78
79 Args:
80 patch: Instance of GerritPatch to upload.
81 branch: Branch to upload to.
82 work_dir: Local directory where repository is checked out in.
83 draft: If True, upload to refs/draft/|branch| rather than refs/for/|branch|.
84 dryrun: Don't actually upload a change but go through all the steps up to
85 and including git push --dryrun.
86 """
87 upload_type = 'drafts' if draft else 'for'
88 # Apply the actual change.
89 patch.CherryPick(work_dir, inflight=True, leave_dirty=True)
90
91 # Get the new sha1 after apply.
David James97d95872012-11-16 15:09:56 -080092 new_sha1 = git.GetGitRepoRevision(work_dir)
Chris Sosaefc35722012-09-11 18:55:37 -070093
94 # Create and use a LocalPatch to Upload the change to Gerrit.
95 local_patch = cros_patch.LocalPatch(
96 work_dir, patch.project_url, constants.PATCH_BRANCH,
97 patch.tracking_branch, patch.remote, new_sha1)
Mike Frysinger075e6592012-10-27 04:41:09 -040098 return local_patch.Upload(
Chris Sosaefc35722012-09-11 18:55:37 -070099 patch.project_url, 'refs/%s/%s' % (upload_type, branch),
100 carbon_copy=False, dryrun=dryrun)
101
102
103def _SetupWorkDirectoryForPatch(work_dir, patch, branch, manifest, email):
104 """Set up local dir for uploading changes to the given patch's project."""
105 logging.info('Setting up dir %s for uploading changes to %s', work_dir,
106 patch.project_url)
107
108 # Clone the git repo from reference if we have a pointer to a
109 # ManifestCheckout object.
110 reference = None
111 if manifest:
112 reference = os.path.join(constants.SOURCE_ROOT,
113 manifest.GetProjectPath(patch.project))
114 # Use the email if email wasn't specified.
115 if not email:
David James97d95872012-11-16 15:09:56 -0800116 email = git.GetProjectUserEmail(reference)
Chris Sosaefc35722012-09-11 18:55:37 -0700117
118 repository.CloneGitRepo(work_dir, patch.project_url, reference=reference)
119
120 # Set the git committer.
David James97d95872012-11-16 15:09:56 -0800121 git.RunGit(work_dir, ['config', '--replace-all', 'user.email', email])
Chris Sosaefc35722012-09-11 18:55:37 -0700122
David James97d95872012-11-16 15:09:56 -0800123 mbranch = git.MatchSingleBranchName(
Mike Frysinger94f91be2012-10-19 16:09:06 -0400124 work_dir, branch, namespace='refs/remotes/origin/')
125 logging.info('Auto resolved branch name "%s" to "%s"' % (branch, mbranch))
126 branch = mbranch
127
Chris Sosaefc35722012-09-11 18:55:37 -0700128 # Finally, create a local branch for uploading changes to the given remote
129 # branch.
David James97d95872012-11-16 15:09:56 -0800130 git.CreatePushBranch(
Chris Sosaefc35722012-09-11 18:55:37 -0700131 constants.PATCH_BRANCH, work_dir, sync=False,
132 remote_push_branch=('ignore', 'origin/%s' % branch))
133
Mike Frysinger94f91be2012-10-19 16:09:06 -0400134 return branch
135
Chris Sosaefc35722012-09-11 18:55:37 -0700136
137def _ManifestContainsAllPatches(manifest, patches):
138 """Returns true if the given manifest contains all the patches.
139
140 Args:
David James97d95872012-11-16 15:09:56 -0800141 manifest - an instance of git.Manifest
Chris Sosaefc35722012-09-11 18:55:37 -0700142 patches - a collection GerritPatch objects.
143 """
144 for patch in patches:
145 project_path = None
146 if manifest.ProjectExists(patch.project):
147 project_path = manifest.GetProjectPath(patch.project)
148
149 if not project_path:
150 logging.error('Your manifest does not have the repository %s for '
151 'change %s. Please re-run with --nomirror and '
152 '--email set', patch.project, patch.gerrit_number)
153 return False
154
155 return True
156
157
158def main(argv):
159 parser = _GetParser()
160 options, args = parser.parse_args(argv)
161
162 if len(args) < 2:
163 parser.error('Not enough arguments specified')
164
165 changes = args[0:-1]
Brian Harring511055e2012-10-10 02:58:59 -0700166 patches = gerrit.GetGerritPatchInfo(changes)
Chris Sosaefc35722012-09-11 18:55:37 -0700167 branch = args[-1]
168
169 # Suppress all cros_build_lib info output unless we're running debug.
170 if not options.debug:
171 cros_build_lib.logger.setLevel(logging.ERROR)
172
173 # Get a pointer to your repo checkout to look up the local project paths for
174 # both email addresses and for using your checkout as a git mirror.
175 manifest = None
176 if options.mirror:
David James97d95872012-11-16 15:09:56 -0800177 manifest = git.ManifestCheckout.Cached(constants.SOURCE_ROOT)
Chris Sosaefc35722012-09-11 18:55:37 -0700178 if not _ManifestContainsAllPatches(manifest, patches):
179 return 1
180 else:
181 if not options.email:
182 chromium_email = '%s@chromium.org' % os.environ['USER']
183 logging.info('--nomirror set without email, using %s', chromium_email)
184 options.email = chromium_email
185
186 index = 0
187 work_dir = None
188 root_work_dir = tempfile.mkdtemp(prefix='cros_merge_to_branch')
189 try:
190 for index, (change, patch) in enumerate(zip(changes, patches)):
191 # We only clone the project and set the committer the first time.
192 work_dir = os.path.join(root_work_dir, patch.project)
193 if not os.path.isdir(work_dir):
Mike Frysinger94f91be2012-10-19 16:09:06 -0400194 branch = _SetupWorkDirectoryForPatch(work_dir, patch, branch, manifest,
195 options.email)
Chris Sosaefc35722012-09-11 18:55:37 -0700196
197 # Now that we have the project checked out, let's apply our change and
198 # create a new change on Gerrit.
199 logging.info('Uploading change %s to branch %s', change, branch)
Mike Frysinger075e6592012-10-27 04:41:09 -0400200 url = _UploadChangeToBranch(work_dir, patch, branch, options.draft,
201 options.dryrun)
Chris Sosaefc35722012-09-11 18:55:37 -0700202 logging.info('Successfully uploaded %s to %s', change, branch)
Mike Frysinger075e6592012-10-27 04:41:09 -0400203 if url:
204 logging.info(' URL: %s', url)
Chris Sosaefc35722012-09-11 18:55:37 -0700205
Mike Frysinger94f91be2012-10-19 16:09:06 -0400206 except (cros_build_lib.RunCommandError, cros_patch.ApplyPatchException,
David James97d95872012-11-16 15:09:56 -0800207 git.AmbiguousBranchName) as e:
Chris Sosaefc35722012-09-11 18:55:37 -0700208 # Tell the user how far we got.
209 good_changes = changes[:index]
210 bad_changes = changes[index:]
211
212 logging.warning('############## SOME CHANGES FAILED TO UPLOAD ############')
213
214 if good_changes:
215 logging.info('Successfully uploaded change(s) %s', ' '.join(good_changes))
216
217 # Printing out the error here so that we can see exactly what failed. This
218 # is especially useful to debug without using --debug.
219 logging.error('Upload failed with %s', str(e).strip())
220 if not options.wipe:
221 logging.info('Not wiping the directory. You can inspect the failed '
Mike Frysinger9f606d72012-10-12 00:55:57 -0400222 'change at %s; After fixing the change (if trivial) you can '
Chris Sosaefc35722012-09-11 18:55:37 -0700223 'try to upload the change by running:\n'
224 'git push %s HEAD:refs/for/%s', work_dir, patch.project_url,
225 branch)
226 else:
227 logging.error('--nowipe not set thus deleting the work directory. If you '
228 'wish to debug this, re-run the script with change(s) '
Mike Frysinger1244fb22012-10-19 14:14:10 -0400229 '%s and --nowipe by running:\n %s %s %s --nowipe',
230 ' '.join(bad_changes), sys.argv[0], ' '.join(bad_changes),
231 branch)
Chris Sosaefc35722012-09-11 18:55:37 -0700232
233 # Suppress the stack trace if we're not debugging.
234 if options.debug:
235 raise
236 else:
237 return 1
238
239 finally:
240 if options.wipe:
241 shutil.rmtree(root_work_dir)
242
243 if options.dryrun:
244 logging.info('Success! To actually upload changes re-run without --dryrun.')
245 else:
246 logging.info('Successfully uploaded all changes requested.')
247
248 return 0