blob: 577de227c081de87e8093c8a00121d97ece26a2c [file] [log] [blame]
Chris Sosadad0d322011-01-31 16:37:33 -08001#!/usr/bin/python
2
Mike Frysinger110750a2012-03-26 14:19:20 -04003# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Chris Sosadad0d322011-01-31 16:37:33 -08004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""This module uprevs a given package's ebuild to the next revision."""
8
Chris Sosa62ad8522011-03-08 17:46:17 -08009import optparse
Chris Sosadad0d322011-01-31 16:37:33 -080010import os
Chris Sosadad0d322011-01-31 16:37:33 -080011import sys
12
Mike Frysinger6cb624a2012-05-24 18:17:38 -040013from chromite.buildbot import constants
David James66009462012-03-25 10:08:38 -070014from chromite.buildbot import portage_utilities
Chris Sosac13bba52011-05-24 15:14:09 -070015from chromite.lib import cros_build_lib
David James97d95872012-11-16 15:09:56 -080016from chromite.lib import git
Mike Frysingerfddaeb52012-11-20 11:17:31 -050017from chromite.lib import osutils
David James6450a0a2012-12-04 07:59:53 -080018from chromite.lib import parallel
Chris Sosac13bba52011-05-24 15:14:09 -070019
David James15ed1302013-04-25 09:21:19 -070020
David James29e86d52013-04-19 09:41:29 -070021# Commit message for uprevving Portage packages.
22_GIT_COMMIT_MESSAGE = 'Marking 9999 ebuild for %s as stable.'
23
Chris Sosadad0d322011-01-31 16:37:33 -080024# Dictionary of valid commands with usage information.
25COMMAND_DICTIONARY = {
Chris Sosadad0d322011-01-31 16:37:33 -080026 'commit':
27 'Marks given ebuilds as stable locally',
28 'push':
29 'Pushes previous marking of ebuilds to remote repo',
30 }
31
Chris Sosadad0d322011-01-31 16:37:33 -080032
Chris Sosadad0d322011-01-31 16:37:33 -080033# ======================= Global Helper Functions ========================
34
35
David Jamescc09c9b2012-01-26 22:10:13 -080036def CleanStalePackages(boards, package_atoms):
Chris Sosabf153872011-04-28 14:21:09 -070037 """Cleans up stale package info from a previous build.
38 Args:
David Jamescc09c9b2012-01-26 22:10:13 -080039 boards: Boards to clean the packages from.
Mike Frysingerde5ab0e2013-03-21 20:48:36 -040040 package_atoms: A list of package atoms to unmerge.
Chris Sosabf153872011-04-28 14:21:09 -070041 """
David James15ed1302013-04-25 09:21:19 -070042 if package_atoms:
43 cros_build_lib.Info('Cleaning up stale packages %s.' % package_atoms)
44
Mike Frysingerb7ab9b82012-04-04 16:22:43 -040045 # First unmerge all the packages for a board, then eclean it.
46 # We need these two steps to run in order (unmerge/eclean),
47 # but we can let all the boards run in parallel.
48 def _CleanStalePackages(board):
49 if board:
50 suffix = '-' + board
51 runcmd = cros_build_lib.RunCommand
52 else:
53 suffix = ''
54 runcmd = cros_build_lib.SudoRunCommand
Chris Sosadad0d322011-01-31 16:37:33 -080055
David James59a0a2b2013-03-22 14:04:44 -070056 emerge, eclean = 'emerge' + suffix, 'eclean' + suffix
57 if not osutils.FindMissingBinaries([emerge, eclean]):
Mike Frysingerde5ab0e2013-03-21 20:48:36 -040058 # If nothing was found to be unmerged, emerge will exit(1).
David James59a0a2b2013-03-22 14:04:44 -070059 result = runcmd([emerge, '-q', '--unmerge'] + package_atoms,
Mike Frysingerde5ab0e2013-03-21 20:48:36 -040060 extra_env={'CLEAN_DELAY': '0'}, error_code_ok=True)
61 if not result.returncode in (0, 1):
62 raise cros_build_lib.RunCommandError('unexpected error', result)
David James59a0a2b2013-03-22 14:04:44 -070063 runcmd([eclean, '-d', 'packages'],
64 redirect_stdout=True, redirect_stderr=True)
Mike Frysingerb7ab9b82012-04-04 16:22:43 -040065
66 tasks = []
David Jamescc09c9b2012-01-26 22:10:13 -080067 for board in boards:
Mike Frysingerb7ab9b82012-04-04 16:22:43 -040068 tasks.append([board])
69 tasks.append([None])
70
David James6450a0a2012-12-04 07:59:53 -080071 parallel.RunTasksInProcessPool(_CleanStalePackages, tasks)
Chris Sosadad0d322011-01-31 16:37:33 -080072
73
Mike Frysinger2ebe3732012-05-08 17:04:12 -040074# TODO(build): This code needs to be gutted and rebased to cros_build_lib.
75def _DoWeHaveLocalCommits(stable_branch, tracking_branch, cwd):
Chris Sosadad0d322011-01-31 16:37:33 -080076 """Returns true if there are local commits."""
David James97d95872012-11-16 15:09:56 -080077 current_branch = git.GetCurrentBranch(cwd)
Brian Harring609dc4e2012-05-07 02:17:44 -070078
79 if current_branch != stable_branch:
Chris Sosadad0d322011-01-31 16:37:33 -080080 return False
David James97d95872012-11-16 15:09:56 -080081 output = git.RunGit(
Brian Harring609dc4e2012-05-07 02:17:44 -070082 cwd, ['rev-parse', 'HEAD', tracking_branch]).output.split()
Brian Harring5b86b5e2012-05-25 18:27:40 -070083 return output[0] != output[1]
Chris Sosadad0d322011-01-31 16:37:33 -080084
85
David James1b363582012-12-17 11:53:11 -080086def _CheckSaneArguments(command, options):
Chris Sosadad0d322011-01-31 16:37:33 -080087 """Checks to make sure the flags are sane. Dies if arguments are not sane."""
88 if not command in COMMAND_DICTIONARY.keys():
89 _PrintUsageAndDie('%s is not a valid command' % command)
Chris Sosa62ad8522011-03-08 17:46:17 -080090 if not options.packages and command == 'commit' and not options.all:
Chris Sosadad0d322011-01-31 16:37:33 -080091 _PrintUsageAndDie('Please specify at least one package')
Mike Frysinger8fd67dc2012-12-03 23:51:18 -050092 if options.boards:
93 cros_build_lib.AssertInsideChroot()
Chris Sosa62ad8522011-03-08 17:46:17 -080094 if not os.path.isdir(options.srcroot):
Chris Sosadad0d322011-01-31 16:37:33 -080095 _PrintUsageAndDie('srcroot is not a valid path')
Chris Sosa62ad8522011-03-08 17:46:17 -080096 options.srcroot = os.path.abspath(options.srcroot)
Chris Sosadad0d322011-01-31 16:37:33 -080097
98
99def _PrintUsageAndDie(error_message=''):
100 """Prints optional error_message the usage and returns an error exit code."""
101 command_usage = 'Commands: \n'
102 # Add keys and usage information from dictionary.
103 commands = sorted(COMMAND_DICTIONARY.keys())
104 for command in commands:
105 command_usage += ' %s: %s\n' % (command, COMMAND_DICTIONARY[command])
106 commands_str = '|'.join(commands)
Chris Sosac13bba52011-05-24 15:14:09 -0700107 cros_build_lib.Warning('Usage: %s FLAGS [%s]\n\n%s' % (
108 sys.argv[0], commands_str, command_usage))
Chris Sosadad0d322011-01-31 16:37:33 -0800109 if error_message:
Chris Sosac13bba52011-05-24 15:14:09 -0700110 cros_build_lib.Die(error_message)
Chris Sosadad0d322011-01-31 16:37:33 -0800111 else:
112 sys.exit(1)
113
114
Chris Sosadad0d322011-01-31 16:37:33 -0800115# ======================= End Global Helper Functions ========================
116
117
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400118def PushChange(stable_branch, tracking_branch, dryrun, cwd):
Chris Sosadad0d322011-01-31 16:37:33 -0800119 """Pushes commits in the stable_branch to the remote git repository.
120
David Jamesee2da622012-02-23 09:32:16 -0800121 Pushes local commits from calls to CommitChange to the remote git
David James66009462012-03-25 10:08:38 -0700122 repository specified by current working directory. If changes are
123 found to commit, they will be merged to the merge branch and pushed.
124 In that case, the local repository will be left on the merge branch.
Chris Sosadad0d322011-01-31 16:37:33 -0800125
126 Args:
127 stable_branch: The local branch with commits we want to push.
128 tracking_branch: The tracking branch of the local branch.
Chris Sosa62ad8522011-03-08 17:46:17 -0800129 dryrun: Use git push --dryrun to emulate a push.
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400130 cwd: The directory to run commands in.
Chris Sosadad0d322011-01-31 16:37:33 -0800131 Raises:
132 OSError: Error occurred while pushing.
133 """
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400134 if not _DoWeHaveLocalCommits(stable_branch, tracking_branch, cwd):
Brian Harring609dc4e2012-05-07 02:17:44 -0700135 cros_build_lib.Info('No work found to push in %s. Exiting', cwd)
Chris Sosadad0d322011-01-31 16:37:33 -0800136 return
137
David James66009462012-03-25 10:08:38 -0700138 # For the commit queue, our local branch may contain commits that were
139 # just tested and pushed during the CommitQueueCompletion stage. Sync
140 # and rebase our local branch on top of the remote commits.
David James97d95872012-11-16 15:09:56 -0800141 remote, push_branch = git.GetTrackingBranch(cwd, for_push=True)
142 git.SyncPushBranch(cwd, remote, push_branch)
David James66009462012-03-25 10:08:38 -0700143
144 # Check whether any local changes remain after the sync.
Brian Harring609dc4e2012-05-07 02:17:44 -0700145 if not _DoWeHaveLocalCommits(stable_branch, push_branch, cwd):
146 cros_build_lib.Info('All changes already pushed for %s. Exiting', cwd)
David James66009462012-03-25 10:08:38 -0700147 return
148
David James67d73252013-09-19 17:33:12 -0700149 description = git.RunGit(cwd,
150 ['log', '--format=format:%s%n%n%b', '%s..%s' % (
151 push_branch, stable_branch)]).output
Chris Sosadad0d322011-01-31 16:37:33 -0800152 description = 'Marking set of ebuilds as stable\n\n%s' % description
Brian Harring609dc4e2012-05-07 02:17:44 -0700153 cros_build_lib.Info('For %s, using description %s', cwd, description)
David James97d95872012-11-16 15:09:56 -0800154 git.CreatePushBranch(constants.MERGE_BRANCH, cwd)
155 git.RunGit(cwd, ['merge', '--squash', stable_branch])
156 git.RunGit(cwd, ['commit', '-m', description])
157 git.RunGit(cwd, ['config', 'push.default', 'tracking'])
158 git.PushWithRetry(constants.MERGE_BRANCH, cwd, dryrun=dryrun)
Chris Sosadad0d322011-01-31 16:37:33 -0800159
160
161class GitBranch(object):
162 """Wrapper class for a git branch."""
163
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400164 def __init__(self, branch_name, tracking_branch, cwd):
David Jamesc7c4ff52013-09-18 17:57:13 -0700165 """Sets up variables but does not create the branch.
166
167 Arguments:
168 branch_name: The name of the branch.
169 tracking_branch: The associated tracking branch.
170 cwd: The git repository to work in.
171 """
Chris Sosadad0d322011-01-31 16:37:33 -0800172 self.branch_name = branch_name
173 self.tracking_branch = tracking_branch
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400174 self.cwd = cwd
Chris Sosadad0d322011-01-31 16:37:33 -0800175
176 def CreateBranch(self):
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400177 self.Checkout()
Chris Sosadad0d322011-01-31 16:37:33 -0800178
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400179 def Checkout(self, branch=None):
Chris Sosadad0d322011-01-31 16:37:33 -0800180 """Function used to check out to another GitBranch."""
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400181 if not branch:
182 branch = self.branch_name
183 if branch == self.tracking_branch or self.Exists(branch):
184 git_cmd = ['git', 'checkout', '-f', branch]
Chris Sosadad0d322011-01-31 16:37:33 -0800185 else:
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400186 git_cmd = ['repo', 'start', branch, '.']
187 cros_build_lib.RunCommandCaptureOutput(git_cmd, print_cmd=False,
188 cwd=self.cwd)
Chris Sosadad0d322011-01-31 16:37:33 -0800189
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400190 def Exists(self, branch=None):
Chris Sosadad0d322011-01-31 16:37:33 -0800191 """Returns True if the branch exists."""
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400192 if not branch:
193 branch = self.branch_name
David James67d73252013-09-19 17:33:12 -0700194 branches = git.RunGit(self.cwd, ['branch']).output
Mike Frysinger2ebe3732012-05-08 17:04:12 -0400195 return branch in branches.split()
Chris Sosadad0d322011-01-31 16:37:33 -0800196
197
David James1b363582012-12-17 11:53:11 -0800198def main(_argv):
Chris Sosa62ad8522011-03-08 17:46:17 -0800199 parser = optparse.OptionParser('cros_mark_as_stable OPTIONS packages')
200 parser.add_option('--all', action='store_true',
201 help='Mark all packages as stable.')
Mike Frysinger587bd562012-11-19 16:41:39 -0500202 parser.add_option('-b', '--boards', default='',
David Jamescc09c9b2012-01-26 22:10:13 -0800203 help='Colon-separated list of boards')
Chris Sosa62ad8522011-03-08 17:46:17 -0800204 parser.add_option('--drop_file',
205 help='File to list packages that were revved.')
206 parser.add_option('--dryrun', action='store_true',
207 help='Passes dry-run to git push if pushing a change.')
208 parser.add_option('-o', '--overlays',
209 help='Colon-separated list of overlays to modify.')
210 parser.add_option('-p', '--packages',
211 help='Colon separated list of packages to rev.')
212 parser.add_option('-r', '--srcroot',
Mike Frysingerfddaeb52012-11-20 11:17:31 -0500213 default=os.path.join(constants.SOURCE_ROOT, 'src'),
Chris Sosa62ad8522011-03-08 17:46:17 -0800214 help='Path to root src directory.')
Chris Sosa62ad8522011-03-08 17:46:17 -0800215 parser.add_option('--verbose', action='store_true',
216 help='Prints out debug info.')
217 (options, args) = parser.parse_args()
Chris Sosadad0d322011-01-31 16:37:33 -0800218
J. Richard Barnette2fa9fd62011-12-02 17:10:10 -0800219 portage_utilities.EBuild.VERBOSE = options.verbose
Chris Sosa62ad8522011-03-08 17:46:17 -0800220
221 if len(args) != 1:
Ryan Cui05a31ba2011-05-31 17:47:37 -0700222 _PrintUsageAndDie('Must specify a valid command [commit, push]')
Chris Sosa62ad8522011-03-08 17:46:17 -0800223
224 command = args[0]
225 package_list = None
226 if options.packages:
227 package_list = options.packages.split(':')
228
David James1b363582012-12-17 11:53:11 -0800229 _CheckSaneArguments(command, options)
Chris Sosa62ad8522011-03-08 17:46:17 -0800230 if options.overlays:
Chris Sosadad0d322011-01-31 16:37:33 -0800231 overlays = {}
Chris Sosa62ad8522011-03-08 17:46:17 -0800232 for path in options.overlays.split(':'):
Ryan Cui05a31ba2011-05-31 17:47:37 -0700233 if not os.path.isdir(path):
Chris Sosac13bba52011-05-24 15:14:09 -0700234 cros_build_lib.Die('Cannot find overlay: %s' % path)
Chris Sosadad0d322011-01-31 16:37:33 -0800235 overlays[path] = []
236 else:
Chris Sosac13bba52011-05-24 15:14:09 -0700237 cros_build_lib.Warning('Missing --overlays argument')
Chris Sosadad0d322011-01-31 16:37:33 -0800238 overlays = {
Chris Sosa62ad8522011-03-08 17:46:17 -0800239 '%s/private-overlays/chromeos-overlay' % options.srcroot: [],
240 '%s/third_party/chromiumos-overlay' % options.srcroot: []
Chris Sosadad0d322011-01-31 16:37:33 -0800241 }
242
David James97d95872012-11-16 15:09:56 -0800243 manifest = git.ManifestCheckout.Cached(options.srcroot)
Ryan Cui4656a3c2011-05-24 12:30:30 -0700244
David James84e953c2013-04-23 18:44:06 -0700245 if command == 'commit':
246 portage_utilities.BuildEBuildDictionary(overlays, options.all, package_list)
247
David James15ed1302013-04-25 09:21:19 -0700248 # Contains the array of packages we actually revved.
249 revved_packages = []
250 new_package_atoms = []
David Jamesa8457b52011-05-28 00:03:20 -0700251
David James15ed1302013-04-25 09:21:19 -0700252 # Slight optimization hack: process the chromiumos overlay before any other
253 # cros-workon overlay first so we can do background cache generation in it.
254 # A perfect solution would walk all the overlays, figure out any dependencies
255 # between them (with layout.conf), and then process them in dependency order.
256 # However, this operation isn't slow enough to warrant that level of
257 # complexity, so we'll just special case the main overlay.
258 #
259 # Similarly, generate the cache in the portage-stable tree asap. We know
260 # we won't have any cros-workon packages in there, so generating the cache
261 # is the only thing it'll be doing. The chromiumos overlay instead might
262 # have revbumping to do before it can generate the cache.
263 keys = overlays.keys()
264 for overlay in ('/third_party/chromiumos-overlay',
265 '/third_party/portage-stable'):
266 for k in keys:
267 if k.endswith(overlay):
268 keys.remove(k)
269 keys.insert(0, k)
270 break
Chris Sosadad0d322011-01-31 16:37:33 -0800271
David James15ed1302013-04-25 09:21:19 -0700272 with parallel.BackgroundTaskRunner(portage_utilities.RegenCache) as queue:
273 for overlay in keys:
274 ebuilds = overlays[overlay]
275 if not os.path.isdir(overlay):
276 cros_build_lib.Warning("Skipping %s" % overlay)
277 continue
Chris Sosadad0d322011-01-31 16:37:33 -0800278
David James15ed1302013-04-25 09:21:19 -0700279 # Note we intentionally work from the non push tracking branch;
280 # everything built thus far has been against it (meaning, http mirrors),
281 # thus we should honor that. During the actual push, the code switches
282 # to the correct urls, and does an appropriate rebasing.
283 tracking_branch = git.GetTrackingBranchViaManifest(
284 overlay, manifest=manifest)[1]
Brian Harring609dc4e2012-05-07 02:17:44 -0700285
David James15ed1302013-04-25 09:21:19 -0700286 if command == 'push':
287 PushChange(constants.STABLE_EBUILD_BRANCH, tracking_branch,
288 options.dryrun, cwd=overlay)
289 elif command == 'commit':
290 existing_branch = git.GetCurrentBranch(overlay)
291 work_branch = GitBranch(constants.STABLE_EBUILD_BRANCH, tracking_branch,
292 cwd=overlay)
293 work_branch.CreateBranch()
294 if not work_branch.Exists():
295 cros_build_lib.Die('Unable to create stabilizing branch in %s' %
296 overlay)
297
298 # In the case of uprevving overlays that have patches applied to them,
299 # include the patched changes in the stabilizing branch.
300 if existing_branch:
David James67d73252013-09-19 17:33:12 -0700301 git.RunGit(overlay, ['rebase', existing_branch])
David James15ed1302013-04-25 09:21:19 -0700302
303 messages = []
304 for ebuild in ebuilds:
305 if options.verbose:
306 cros_build_lib.Info('Working on %s', ebuild.package)
307 try:
308 new_package = ebuild.RevWorkOnEBuild(options.srcroot, manifest)
309 if new_package:
310 revved_packages.append(ebuild.package)
311 new_package_atoms.append('=%s' % new_package)
312 messages.append(_GIT_COMMIT_MESSAGE % ebuild.package)
313 except (OSError, IOError):
314 cros_build_lib.Warning('Cannot rev %s\n' % ebuild.package +
315 'Note you will have to go into %s '
316 'and reset the git repo yourself.' % overlay)
317 raise
318
319 if messages:
320 portage_utilities.EBuild.CommitChange('\n\n'.join(messages), overlay)
321
322 if cros_build_lib.IsInsideChroot():
323 # Regenerate caches if need be. We do this all the time to
324 # catch when users make changes without updating cache files.
325 queue.put([overlay])
326
327 if command == 'commit':
328 if cros_build_lib.IsInsideChroot():
329 CleanStalePackages(options.boards.split(':'), new_package_atoms)
330 if options.drop_file:
331 osutils.WriteFile(options.drop_file, ' '.join(revved_packages))