Revert "The major change is refactoring to make functions more accessible for other modules."

This reverts commit 118629dae8f744f20f0bcd6a2b341c22a2958bca.

Revert "Remove _ to fix tree."

This reverts commit a74ee710488e44f81980b9fb4dbd44d70c49c4a2.

Revert "Missed tracking branch to re-open tree."

This reverts commit 0b9f24e9be3f49f0945bd01c2292b381b2d1e87c.

TBR=davidjames

Change-Id: Ic7057cd2a01e192ec78dd729a1f3eac7835b96c7
This commit is contained in:
Chris Sosa 2010-11-18 15:57:20 -08:00
parent 0b9f24e9be
commit 9b054f0f88
2 changed files with 192 additions and 186 deletions

View File

@ -18,8 +18,7 @@ import sys
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
from cros_build_lib import Info, RunCommand, Warning, Die from cros_build_lib import Info, RunCommand, Warning, Die
gflags.DEFINE_boolean('all', False,
'Mark all packages as stable.')
gflags.DEFINE_string('board', '', gflags.DEFINE_string('board', '',
'Board for which the package belongs.', short_name='b') 'Board for which the package belongs.', short_name='b')
gflags.DEFINE_string('overlays', '', gflags.DEFINE_string('overlays', '',
@ -36,16 +35,19 @@ gflags.DEFINE_string('srcroot', '%s/trunk/src' % os.environ['HOME'],
gflags.DEFINE_string('tracking_branch', 'cros/master', gflags.DEFINE_string('tracking_branch', 'cros/master',
'Used with commit to specify branch to track against.', 'Used with commit to specify branch to track against.',
short_name='t') short_name='t')
gflags.DEFINE_boolean('all', False,
'Mark all packages as stable.')
gflags.DEFINE_boolean('verbose', False, gflags.DEFINE_boolean('verbose', False,
'Prints out verbose information about what is going on.', 'Prints out verbose information about what is going on.',
short_name='v') short_name='v')
# Takes two strings, package_name and commit_id. # Takes two strings, package_name and commit_id.
_GIT_COMMIT_MESSAGE = 'Marking 9999 ebuild for %s with commit %s as stable.' _GIT_COMMIT_MESSAGE = \
'Marking 9999 ebuild for %s with commit %s as stable.'
# Dictionary of valid commands with usage information. # Dictionary of valid commands with usage information.
COMMAND_DICTIONARY = { _COMMAND_DICTIONARY = {
'clean': 'clean':
'Cleans up previous calls to either commit or push', 'Cleans up previous calls to either commit or push',
'commit': 'commit':
@ -57,16 +59,6 @@ COMMAND_DICTIONARY = {
# Name used for stabilizing branch. # Name used for stabilizing branch.
_STABLE_BRANCH_NAME = 'stabilizing_branch' _STABLE_BRANCH_NAME = 'stabilizing_branch'
def BestEBuild(ebuilds):
"""Returns the newest EBuild from a list of EBuild objects."""
from portage.versions import vercmp
winner = ebuilds[0]
for ebuild in ebuilds[1:]:
if vercmp(winner.version, ebuild.version) < 0:
winner = ebuild
return winner
# ======================= Global Helper Functions ======================== # ======================= Global Helper Functions ========================
@ -91,6 +83,16 @@ def _CleanStalePackages(board, package_array):
RunCommand(['sudo', 'eclean', '-d', 'packages'], redirect_stderr=True) RunCommand(['sudo', 'eclean', '-d', 'packages'], redirect_stderr=True)
def _BestEBuild(ebuilds):
"""Returns the newest EBuild from a list of EBuild objects."""
from portage.versions import vercmp
winner = ebuilds[0]
for ebuild in ebuilds[1:]:
if vercmp(winner.version, ebuild.version) < 0:
winner = ebuild
return winner
def _FindUprevCandidates(files): def _FindUprevCandidates(files):
"""Return a list of uprev candidates from specified list of files. """Return a list of uprev candidates from specified list of files.
@ -106,7 +108,7 @@ def _FindUprevCandidates(files):
unstable_ebuilds = [] unstable_ebuilds = []
for path in files: for path in files:
if path.endswith('.ebuild') and not os.path.islink(path): if path.endswith('.ebuild') and not os.path.islink(path):
ebuild = EBuild(path) ebuild = _EBuild(path)
if ebuild.is_workon: if ebuild.is_workon:
workon_dir = True workon_dir = True
if ebuild.is_stable: if ebuild.is_stable:
@ -119,7 +121,7 @@ def _FindUprevCandidates(files):
if len(unstable_ebuilds) > 1: if len(unstable_ebuilds) > 1:
Die('Found multiple unstable ebuilds in %s' % os.path.dirname(path)) Die('Found multiple unstable ebuilds in %s' % os.path.dirname(path))
if len(stable_ebuilds) > 1: if len(stable_ebuilds) > 1:
stable_ebuilds = [BestEBuild(stable_ebuilds)] stable_ebuilds = [_BestEBuild(stable_ebuilds)]
# Print a warning if multiple stable ebuilds are found in the same # Print a warning if multiple stable ebuilds are found in the same
# directory. Storing multiple stable ebuilds is error-prone because # directory. Storing multiple stable ebuilds is error-prone because
@ -164,15 +166,15 @@ def _BuildEBuildDictionary(overlays, all, packages):
overlays[overlay].append(ebuild) overlays[overlay].append(ebuild)
def _CheckOnStabilizingBranch(stable_branch): def _CheckOnStabilizingBranch():
"""Returns true if the git branch is on the stabilizing branch.""" """Returns true if the git branch is on the stabilizing branch."""
current_branch = _SimpleRunCommand('git branch | grep \*').split()[1] current_branch = _SimpleRunCommand('git branch | grep \*').split()[1]
return current_branch == stable_branch return current_branch == _STABLE_BRANCH_NAME
def _CheckSaneArguments(package_list, command): def _CheckSaneArguments(package_list, command):
"""Checks to make sure the flags are sane. Dies if arguments are not sane.""" """Checks to make sure the flags are sane. Dies if arguments are not sane."""
if not command in COMMAND_DICTIONARY.keys(): if not command in _COMMAND_DICTIONARY.keys():
_PrintUsageAndDie('%s is not a valid command' % command) _PrintUsageAndDie('%s is not a valid command' % command)
if not gflags.FLAGS.packages and command == 'commit' and not gflags.FLAGS.all: if not gflags.FLAGS.packages and command == 'commit' and not gflags.FLAGS.all:
_PrintUsageAndDie('Please specify at least one package') _PrintUsageAndDie('Please specify at least one package')
@ -183,13 +185,19 @@ def _CheckSaneArguments(package_list, command):
gflags.FLAGS.srcroot = os.path.abspath(gflags.FLAGS.srcroot) gflags.FLAGS.srcroot = os.path.abspath(gflags.FLAGS.srcroot)
def _Clean():
"""Cleans up uncommitted changes on either stabilizing branch or master."""
_SimpleRunCommand('git reset HEAD --hard')
_SimpleRunCommand('git checkout %s' % gflags.FLAGS.tracking_branch)
def _PrintUsageAndDie(error_message=''): def _PrintUsageAndDie(error_message=''):
"""Prints optional error_message the usage and returns an error exit code.""" """Prints optional error_message the usage and returns an error exit code."""
command_usage = 'Commands: \n' command_usage = 'Commands: \n'
# Add keys and usage information from dictionary. # Add keys and usage information from dictionary.
commands = sorted(COMMAND_DICTIONARY.keys()) commands = sorted(_COMMAND_DICTIONARY.keys())
for command in commands: for command in commands:
command_usage += ' %s: %s\n' % (command, COMMAND_DICTIONARY[command]) command_usage += ' %s: %s\n' % (command, _COMMAND_DICTIONARY[command])
commands_str = '|'.join(commands) commands_str = '|'.join(commands)
Warning('Usage: %s FLAGS [%s]\n\n%s\nFlags:%s' % (sys.argv[0], commands_str, Warning('Usage: %s FLAGS [%s]\n\n%s\nFlags:%s' % (sys.argv[0], commands_str,
command_usage, gflags.FLAGS)) command_usage, gflags.FLAGS))
@ -198,59 +206,34 @@ def _PrintUsageAndDie(error_message=''):
else: else:
sys.exit(1) sys.exit(1)
def _PushChange():
def _SimpleRunCommand(command): """Pushes changes to the git repository.
"""Runs a shell command and returns stdout back to caller."""
_Print(' + %s' % command)
proc_handle = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
stdout = proc_handle.communicate()[0]
retcode = proc_handle.wait()
if retcode != 0:
_Print(stdout)
raise subprocess.CalledProcessError(retcode, command)
return stdout
# ======================= End Global Helper Functions ========================
def Clean(tracking_branch):
"""Cleans up uncommitted changes.
Args:
tracking_branch: The tracking branch we want to return to after the call.
"""
_SimpleRunCommand('git reset HEAD --hard')
_SimpleRunCommand('git checkout %s' % tracking_branch)
def PushChange(stable_branch, tracking_branch):
"""Pushes commits in the stable_branch to the remote git repository.
Pushes locals commits from calls to CommitChange to the remote git Pushes locals commits from calls to CommitChange to the remote git
repository specified by current working directory. repository specified by os.pwd.
Args:
stable_branch: The local branch with commits we want to push.
tracking_branch: The tracking branch of the local branch.
Raises: Raises:
OSError: Error occurred while pushing. OSError: Error occurred while pushing.
""" """
num_retries = 5 num_retries = 5
# TODO(sosa) - Add logic for buildbot to check whether other slaves have
# completed and push this change only if they have.
# Sanity check to make sure we're on a stabilizing branch before pushing. # Sanity check to make sure we're on a stabilizing branch before pushing.
if not _CheckOnStabilizingBranch(stable_branch): if not _CheckOnStabilizingBranch():
Info('Not on branch %s so no work found to push. Exiting' % stable_branch) Info('Not on branch %s so no work found to push. Exiting' % \
_STABLE_BRANCH_NAME)
return return
description = _SimpleRunCommand('git log --format=format:%s%n%n%b ' + description = _SimpleRunCommand('git log --format=format:%s%n%n%b ' +
tracking_branch) gflags.FLAGS.tracking_branch + '..')
description = 'Marking set of ebuilds as stable\n\n%s' % description description = 'Marking set of ebuilds as stable\n\n%s' % description
merge_branch_name = 'merge_branch' merge_branch_name = 'merge_branch'
for push_try in range(num_retries + 1): for push_try in range(num_retries + 1):
try: try:
_SimpleRunCommand('git remote update') _SimpleRunCommand('git remote update')
merge_branch = GitBranch(merge_branch_name, gflags.FLAGS.tracking_branch) merge_branch = _GitBranch(merge_branch_name)
merge_branch.CreateBranch() merge_branch.CreateBranch()
if not merge_branch.Exists(): if not merge_branch.Exists():
Die('Unable to create merge branch.') Die('Unable to create merge branch.')
@ -268,13 +251,27 @@ def PushChange(stable_branch, tracking_branch):
raise raise
class GitBranch(object): def _SimpleRunCommand(command):
"""Runs a shell command and returns stdout back to caller."""
_Print(' + %s' % command)
proc_handle = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
stdout = proc_handle.communicate()[0]
retcode = proc_handle.wait()
if retcode != 0:
_Print(stdout)
raise subprocess.CalledProcessError(retcode, command)
return stdout
# ======================= End Global Helper Functions ========================
class _GitBranch(object):
"""Wrapper class for a git branch.""" """Wrapper class for a git branch."""
def __init__(self, branch_name, tracking_branch): def __init__(self, branch_name):
"""Sets up variables but does not create the branch.""" """Sets up variables but does not create the branch."""
self.branch_name = branch_name self.branch_name = branch_name
self.tracking_branch = tracking_branch
def CreateBranch(self): def CreateBranch(self):
"""Creates a new git branch or replaces an existing one.""" """Creates a new git branch or replaces an existing one."""
@ -285,7 +282,7 @@ class GitBranch(object):
def _Checkout(self, target, create=True): def _Checkout(self, target, create=True):
"""Function used internally to create and move between branches.""" """Function used internally to create and move between branches."""
if create: if create:
git_cmd = 'git checkout -b %s %s' % (target, self.tracking_branch) git_cmd = 'git checkout -b %s %s' % (target, gflags.FLAGS.tracking_branch)
else: else:
git_cmd = 'git checkout %s' % target git_cmd = 'git checkout %s' % target
_SimpleRunCommand(git_cmd) _SimpleRunCommand(git_cmd)
@ -301,30 +298,30 @@ class GitBranch(object):
Returns True on success. Returns True on success.
""" """
self._Checkout(self.tracking_branch, create=False) self._Checkout(gflags.FLAGS.tracking_branch, create=False)
delete_cmd = 'git branch -D %s' % self.branch_name delete_cmd = 'git branch -D %s' % self.branch_name
_SimpleRunCommand(delete_cmd) _SimpleRunCommand(delete_cmd)
class EBuild(object): class _EBuild(object):
"""Wrapper class for information about an ebuild.""" """Wrapper class for an ebuild."""
def __init__(self, path): def __init__(self, path):
"""Sets up data about an ebuild from its path.""" """Initializes all data about an ebuild.
from portage.versions import pkgsplit
unused_path, self.category, self.pkgname, filename = path.rsplit('/', 3)
unused_pkgname, version_no_rev, rev = pkgsplit(
filename.replace('.ebuild', ''))
self.ebuild_path_no_version = os.path.join( Uses equery to find the ebuild path and sets data about an ebuild for
os.path.dirname(path), self.pkgname) easy reference.
self.ebuild_path_no_revision = '%s-%s' % (self.ebuild_path_no_version, """
version_no_rev) from portage.versions import pkgsplit
self.current_revision = int(rev.replace('r', '')) self.ebuild_path = path
(self.ebuild_path_no_revision,
self.ebuild_path_no_version,
self.current_revision) = self._ParseEBuildPath(self.ebuild_path)
_, self.category, pkgpath, filename = path.rsplit('/', 3)
filename_no_suffix = os.path.join(filename.replace('.ebuild', ''))
self.pkgname, version_no_rev, rev = pkgsplit(filename_no_suffix)
self.version = '%s-%s' % (version_no_rev, rev) self.version = '%s-%s' % (version_no_rev, rev)
self.package = '%s/%s' % (self.category, self.pkgname) self.package = '%s/%s' % (self.category, self.pkgname)
self.ebuild_path = path
self.is_workon = False self.is_workon = False
self.is_stable = False self.is_stable = False
@ -338,6 +335,7 @@ class EBuild(object):
def GetCommitId(self): def GetCommitId(self):
"""Get the commit id for this ebuild.""" """Get the commit id for this ebuild."""
# Grab and evaluate CROS_WORKON variables from this ebuild. # Grab and evaluate CROS_WORKON variables from this ebuild.
unstable_ebuild = '%s-9999.ebuild' % self.ebuild_path_no_version unstable_ebuild = '%s-9999.ebuild' % self.ebuild_path_no_version
cmd = ('export CROS_WORKON_LOCALNAME="%s" CROS_WORKON_PROJECT="%s"; ' cmd = ('export CROS_WORKON_LOCALNAME="%s" CROS_WORKON_PROJECT="%s"; '
@ -380,53 +378,39 @@ class EBuild(object):
Die('Missing commit id for %s' % self.ebuild_path) Die('Missing commit id for %s' % self.ebuild_path)
return output.rstrip() return output.rstrip()
@classmethod
def _ParseEBuildPath(cls, ebuild_path):
"""Static method that parses the path of an ebuild
Returns a tuple containing the (ebuild path without the revision
string, without the version string, and the current revision number for
the ebuild).
"""
# Get the ebuild name without the revision string.
(ebuild_no_rev, _, rev_string) = ebuild_path.rpartition('-')
# Verify the revision string starts with the revision character.
if rev_string.startswith('r'):
# Get the ebuild name without the revision and version strings.
ebuild_no_version = ebuild_no_rev.rpartition('-')[0]
rev_string = rev_string[1:].rpartition('.ebuild')[0]
else:
# Has no revision so we stripped the version number instead.
ebuild_no_version = ebuild_no_rev
ebuild_no_rev = ebuild_path.rpartition('9999.ebuild')[0] + '0.0.1'
rev_string = '0'
revision = int(rev_string)
return (ebuild_no_rev, ebuild_no_version, revision)
class EBuildStableMarker(object): class EBuildStableMarker(object):
"""Class that revs the ebuild and commits locally or pushes the change.""" """Class that revs the ebuild and commits locally or pushes the change."""
def __init__(self, ebuild): def __init__(self, ebuild):
assert ebuild
self._ebuild = ebuild self._ebuild = ebuild
@classmethod def RevEBuild(self, commit_id='', redirect_file=None):
def MarkAsStable(cls, unstable_ebuild_path, new_stable_ebuild_path, """Revs an ebuild given the git commit id.
commit_keyword, commit_value, redirect_file=None):
"""Static function that creates a revved stable ebuild.
This function assumes you have already figured out the name of the new
stable ebuild path and then creates that file from the given unstable
ebuild and marks it as stable. If the commit_value is set, it also
set the commit_keyword=commit_value pair in the ebuild.
Args:
unstable_ebuild_path: The path to the unstable ebuild.
new_stable_ebuild_path: The path you want to use for the new stable
ebuild.
commit_keyword: Optional keyword to set in the ebuild to mark it as
stable.
commit_value: Value to set the above keyword to.
redirect_file: Optionally redirect output of new ebuild somewhere else.
"""
shutil.copyfile(unstable_ebuild_path, new_stable_ebuild_path)
for line in fileinput.input(new_stable_ebuild_path, inplace=1):
# Has to be done here to get changes to sys.stdout from fileinput.input.
if not redirect_file:
redirect_file = sys.stdout
if line.startswith('KEYWORDS'):
# Actually mark this file as stable by removing ~'s.
redirect_file.write(line.replace('~', ''))
elif line.startswith('EAPI'):
# Always add new commit_id after EAPI definition.
redirect_file.write(line)
if commit_keyword and commit_value:
redirect_file.write('%s="%s"\n' % (commit_keyword, commit_value))
elif not line.startswith(commit_keyword):
# Skip old commit_keyword definition.
redirect_file.write(line)
fileinput.close()
def RevWorkOnEBuild(self, commit_id, redirect_file=None):
"""Revs a workon ebuild given the git commit hash.
By default this class overwrites a new ebuild given the normal By default this class overwrites a new ebuild given the normal
ebuild rev'ing logic. However, a user can specify a redirect_file ebuild rev'ing logic. However, a user can specify a redirect_file
@ -445,34 +429,44 @@ class EBuildStableMarker(object):
Returns: Returns:
True if the revved package is different than the old ebuild. True if the revved package is different than the old ebuild.
""" """
if self._ebuild.is_stable: # TODO(sosa): Change to a check.
new_stable_ebuild_path = '%s-r%d.ebuild' % ( if not self._ebuild:
self._ebuild.ebuild_path_no_revision, Die('Invalid ebuild given to EBuildStableMarker')
self._ebuild.current_revision + 1)
else: new_ebuild_path = '%s-r%d.ebuild' % (self._ebuild.ebuild_path_no_revision,
# If given unstable ebuild, use 0.0.1 rather than 9999.
new_stable_ebuild_path = '%s-0.0.1-r%d.ebuild' % (
self._ebuild.ebuild_path_no_version,
self._ebuild.current_revision + 1) self._ebuild.current_revision + 1)
_Print('Creating new stable ebuild %s' % new_stable_ebuild_path) _Print('Creating new stable ebuild %s' % new_ebuild_path)
unstable_ebuild_path = ('%s-9999.ebuild' % workon_ebuild = '%s-9999.ebuild' % self._ebuild.ebuild_path_no_version
self._ebuild.ebuild_path_no_version) if not os.path.exists(workon_ebuild):
if not os.path.exists(unstable_ebuild_path): Die('Missing 9999 ebuild: %s' % workon_ebuild)
Die('Missing unstable ebuild: %s' % unstable_ebuild_path) shutil.copyfile(workon_ebuild, new_ebuild_path)
self.MarkAsStable(unstable_ebuild_path, new_stable_ebuild_path, for line in fileinput.input(new_ebuild_path, inplace=1):
'CROS_WORKON_COMMIT', commit_id, redirect_file) # Has to be done here to get changes to sys.stdout from fileinput.input.
if not redirect_file:
redirect_file = sys.stdout
if line.startswith('KEYWORDS'):
# Actually mark this file as stable by removing ~'s.
redirect_file.write(line.replace('~', ''))
elif line.startswith('EAPI'):
# Always add new commit_id after EAPI definition.
redirect_file.write(line)
redirect_file.write('CROS_WORKON_COMMIT="%s"\n' % commit_id)
elif not line.startswith('CROS_WORKON_COMMIT'):
# Skip old CROS_WORKON_COMMIT definition.
redirect_file.write(line)
fileinput.close()
old_ebuild_path = self._ebuild.ebuild_path old_ebuild_path = self._ebuild.ebuild_path
diff_cmd = ['diff', '-Bu', old_ebuild_path, new_stable_ebuild_path] diff_cmd = ['diff', '-Bu', old_ebuild_path, new_ebuild_path]
if 0 == RunCommand(diff_cmd, exit_code=True, redirect_stdout=True, if 0 == RunCommand(diff_cmd, exit_code=True, redirect_stdout=True,
redirect_stderr=True, print_cmd=gflags.FLAGS.verbose): redirect_stderr=True, print_cmd=gflags.FLAGS.verbose):
os.unlink(new_stable_ebuild_path) os.unlink(new_ebuild_path)
return False return False
else: else:
_Print('Adding new stable ebuild to git') _Print('Adding new stable ebuild to git')
_SimpleRunCommand('git add %s' % new_stable_ebuild_path) _SimpleRunCommand('git add %s' % new_ebuild_path)
if self._ebuild.is_stable: if self._ebuild.is_stable:
_Print('Removing old ebuild from git') _Print('Removing old ebuild from git')
@ -480,9 +474,11 @@ class EBuildStableMarker(object):
return True return True
@classmethod def CommitChange(self, message):
def CommitChange(cls, message): """Commits current changes in git locally.
"""Commits current changes in git locally with given commit message.
This method will take any changes from invocations to RevEBuild
and commits them locally in the git repository that contains os.pwd.
Args: Args:
message: the commit string to write when committing to git. message: the commit string to write when committing to git.
@ -490,7 +486,8 @@ class EBuildStableMarker(object):
Raises: Raises:
OSError: Error occurred while committing. OSError: Error occurred while committing.
""" """
Info('Committing changes with commit message: %s' % message) _Print('Committing changes for %s with commit message %s' % \
(self._ebuild.package, message))
git_commit_cmd = 'git commit -am "%s"' % message git_commit_cmd = 'git commit -am "%s"' % message
_SimpleRunCommand(git_commit_cmd) _SimpleRunCommand(git_commit_cmd)
@ -534,11 +531,11 @@ def main(argv):
os.chdir(overlay) os.chdir(overlay)
if command == 'clean': if command == 'clean':
Clean(gflags.FLAGS.tracking_branch) _Clean()
elif command == 'push': elif command == 'push':
PushChange(_STABLE_BRANCH_NAME, gflags.FLAGS.tracking_branch) _PushChange()
elif command == 'commit' and ebuilds: elif command == 'commit' and ebuilds:
work_branch = GitBranch(_STABLE_BRANCH_NAME, gflags.FLAGS.tracking_branch) work_branch = _GitBranch(_STABLE_BRANCH_NAME)
work_branch.CreateBranch() work_branch.CreateBranch()
if not work_branch.Exists(): if not work_branch.Exists():
Die('Unable to create stabilizing branch in %s' % overlay) Die('Unable to create stabilizing branch in %s' % overlay)
@ -550,7 +547,7 @@ def main(argv):
_Print('Working on %s' % ebuild.package) _Print('Working on %s' % ebuild.package)
worker = EBuildStableMarker(ebuild) worker = EBuildStableMarker(ebuild)
commit_id = ebuild.GetCommitId() commit_id = ebuild.GetCommitId()
if worker.RevWorkOnEBuild(commit_id): if worker.RevEBuild(commit_id):
message = _GIT_COMMIT_MESSAGE % (ebuild.package, commit_id) message = _GIT_COMMIT_MESSAGE % (ebuild.package, commit_id)
worker.CommitChange(message) worker.CommitChange(message)
revved_packages.append(ebuild.package) revved_packages.append(ebuild.package)

View File

@ -6,7 +6,7 @@
"""Unit tests for cros_mark_as_stable.py.""" """Unit tests for cros_mark_as_stable.py."""
import fileinput
import mox import mox
import os import os
import sys import sys
@ -23,11 +23,10 @@ class GitBranchTest(mox.MoxTestBase):
# Always stub RunCommmand out as we use it in every method. # Always stub RunCommmand out as we use it in every method.
self.mox.StubOutWithMock(cros_mark_as_stable, '_SimpleRunCommand') self.mox.StubOutWithMock(cros_mark_as_stable, '_SimpleRunCommand')
self._branch = 'test_branch' self._branch = 'test_branch'
self._tracking_branch = 'cros/test'
def testCreateBranchNoPrevious(self): def testCreateBranchNoPrevious(self):
# Test init with no previous branch existing. # Test init with no previous branch existing.
branch = cros_mark_as_stable.GitBranch(self._branch, self._tracking_branch) branch = cros_mark_as_stable._GitBranch(self._branch)
self.mox.StubOutWithMock(branch, 'Exists') self.mox.StubOutWithMock(branch, 'Exists')
self.mox.StubOutWithMock(branch, '_Checkout') self.mox.StubOutWithMock(branch, '_Checkout')
branch.Exists().AndReturn(False) branch.Exists().AndReturn(False)
@ -38,7 +37,7 @@ class GitBranchTest(mox.MoxTestBase):
def testCreateBranchWithPrevious(self): def testCreateBranchWithPrevious(self):
# Test init with previous branch existing. # Test init with previous branch existing.
branch = cros_mark_as_stable.GitBranch(self._branch, self._tracking_branch) branch = cros_mark_as_stable._GitBranch(self._branch)
self.mox.StubOutWithMock(branch, 'Exists') self.mox.StubOutWithMock(branch, 'Exists')
self.mox.StubOutWithMock(branch, 'Delete') self.mox.StubOutWithMock(branch, 'Delete')
self.mox.StubOutWithMock(branch, '_Checkout') self.mox.StubOutWithMock(branch, '_Checkout')
@ -52,36 +51,35 @@ class GitBranchTest(mox.MoxTestBase):
def testCheckoutCreate(self): def testCheckoutCreate(self):
# Test init with no previous branch existing. # Test init with no previous branch existing.
cros_mark_as_stable._SimpleRunCommand( cros_mark_as_stable._SimpleRunCommand(
'git checkout -b %s %s' % (self._branch, self._tracking_branch)) 'git checkout -b %s cros/master' % self._branch)
self.mox.ReplayAll() self.mox.ReplayAll()
branch = cros_mark_as_stable.GitBranch(self._branch, self._tracking_branch) branch = cros_mark_as_stable._GitBranch(self._branch)
branch._Checkout(self._branch) branch._Checkout(self._branch)
self.mox.VerifyAll() self.mox.VerifyAll()
def testCheckoutNoCreate(self): def testCheckoutNoCreate(self):
# Test init with previous branch existing. # Test init with previous branch existing.
cros_mark_as_stable._SimpleRunCommand('git checkout %s' % ( cros_mark_as_stable._SimpleRunCommand('git checkout cros/master')
self._tracking_branch))
self.mox.ReplayAll() self.mox.ReplayAll()
branch = cros_mark_as_stable.GitBranch(self._branch, self._tracking_branch) branch = cros_mark_as_stable._GitBranch(self._branch)
branch._Checkout(self._tracking_branch, False) branch._Checkout('cros/master', False)
self.mox.VerifyAll() self.mox.VerifyAll()
def testDelete(self): def testDelete(self):
branch = cros_mark_as_stable.GitBranch(self._branch, self._tracking_branch) branch = cros_mark_as_stable._GitBranch(self._branch)
self.mox.StubOutWithMock(branch, '_Checkout') self.mox.StubOutWithMock(branch, '_Checkout')
branch._Checkout(self._tracking_branch, create=False) branch._Checkout('cros/master', create=False)
cros_mark_as_stable._SimpleRunCommand('git branch -D ' + self._branch) cros_mark_as_stable._SimpleRunCommand('git branch -D ' + self._branch)
self.mox.ReplayAll() self.mox.ReplayAll()
branch.Delete() branch.Delete()
self.mox.VerifyAll() self.mox.VerifyAll()
def testExists(self): def testExists(self):
branch = cros_mark_as_stable.GitBranch(self._branch, self._tracking_branch) branch = cros_mark_as_stable._GitBranch(self._branch)
# Test if branch exists that is created # Test if branch exists that is created
cros_mark_as_stable._SimpleRunCommand('git branch').AndReturn( cros_mark_as_stable._SimpleRunCommand('git branch').AndReturn(
'%s %s' % (self._branch, self._tracking_branch)) '%s %s' % (self._branch, 'cros/master'))
self.mox.ReplayAll() self.mox.ReplayAll()
self.assertTrue(branch.Exists()) self.assertTrue(branch.Exists())
self.mox.VerifyAll() self.mox.VerifyAll()
@ -92,34 +90,45 @@ class EBuildTest(mox.MoxTestBase):
def setUp(self): def setUp(self):
mox.MoxTestBase.setUp(self) mox.MoxTestBase.setUp(self)
def testInit(self):
self.mox.StubOutWithMock(cros_mark_as_stable._EBuild, '_ParseEBuildPath')
ebuild_path = '/overlay/cat/test_package/test_package-0.0.1-r1.ebuild'
cros_mark_as_stable._EBuild._ParseEBuildPath(
ebuild_path).AndReturn(['/overlay/cat/test_package-0.0.1',
'/overlay/cat/test_package',
1])
self.mox.StubOutWithMock(cros_mark_as_stable.fileinput, 'input')
mock_file = ['EAPI=2', 'CROS_WORKON_COMMIT=old_id',
'KEYWORDS=\"~x86 ~arm\"', 'src_unpack(){}']
cros_mark_as_stable.fileinput.input(ebuild_path).AndReturn(mock_file)
self.mox.ReplayAll()
ebuild = cros_mark_as_stable._EBuild(ebuild_path)
self.mox.VerifyAll()
self.assertEquals(ebuild.package, 'cat/test_package')
self.assertEquals(ebuild.ebuild_path, ebuild_path)
self.assertEquals(ebuild.ebuild_path_no_revision,
'/overlay/cat/test_package-0.0.1')
self.assertEquals(ebuild.ebuild_path_no_version,
'/overlay/cat/test_package')
self.assertEquals(ebuild.current_revision, 1)
def testParseEBuildPath(self): def testParseEBuildPath(self):
# Test with ebuild with revision number. # Test with ebuild with revision number.
fake_ebuild_path = '/path/to/test_package/test_package-0.0.1-r1.ebuild' no_rev, no_version, revision = cros_mark_as_stable._EBuild._ParseEBuildPath(
self.mox.StubOutWithMock(fileinput, 'input') '/path/test_package-0.0.1-r1.ebuild')
fileinput.input(fake_ebuild_path).AndReturn('') self.assertEquals(no_rev, '/path/test_package-0.0.1')
self.mox.ReplayAll() self.assertEquals(no_version, '/path/test_package')
fake_ebuild = cros_mark_as_stable.EBuild(fake_ebuild_path) self.assertEquals(revision, 1)
self.mox.VerifyAll()
self.assertEquals(fake_ebuild.ebuild_path_no_revision,
'/path/to/test_package/test_package-0.0.1')
self.assertEquals(fake_ebuild.ebuild_path_no_version,
'/path/to/test_package/test_package')
self.assertEquals(fake_ebuild.current_revision, 1)
def testParseEBuildPathNoRevisionNumber(self): def testParseEBuildPathNoRevisionNumber(self):
# Test with ebuild without revision number. # Test with ebuild without revision number.
fake_ebuild_path = '/path/to/test_package/test_package-9999.ebuild' no_rev, no_version, revision = cros_mark_as_stable._EBuild._ParseEBuildPath(
self.mox.StubOutWithMock(fileinput, 'input') '/path/test_package-9999.ebuild')
fileinput.input(fake_ebuild_path).AndReturn('') self.assertEquals(no_rev, '/path/test_package-0.0.1')
self.mox.ReplayAll() self.assertEquals(no_version, '/path/test_package')
fake_ebuild = cros_mark_as_stable.EBuild(fake_ebuild_path) self.assertEquals(revision, 0)
self.mox.VerifyAll()
self.assertEquals(fake_ebuild.ebuild_path_no_revision,
'/path/to/test_package/test_package-9999')
self.assertEquals(fake_ebuild.ebuild_path_no_version,
'/path/to/test_package/test_package')
self.assertEquals(fake_ebuild.current_revision, 0)
class EBuildStableMarkerTest(mox.MoxTestBase): class EBuildStableMarkerTest(mox.MoxTestBase):
@ -129,7 +138,7 @@ class EBuildStableMarkerTest(mox.MoxTestBase):
self.mox.StubOutWithMock(cros_mark_as_stable, '_SimpleRunCommand') self.mox.StubOutWithMock(cros_mark_as_stable, '_SimpleRunCommand')
self.mox.StubOutWithMock(cros_mark_as_stable, 'RunCommand') self.mox.StubOutWithMock(cros_mark_as_stable, 'RunCommand')
self.mox.StubOutWithMock(os, 'unlink') self.mox.StubOutWithMock(os, 'unlink')
self.m_ebuild = self.mox.CreateMock(cros_mark_as_stable.EBuild) self.m_ebuild = self.mox.CreateMock(cros_mark_as_stable._EBuild)
self.m_ebuild.is_stable = True self.m_ebuild.is_stable = True
self.m_ebuild.package = 'test_package' self.m_ebuild.package = 'test_package'
self.m_ebuild.current_revision = 1 self.m_ebuild.current_revision = 1
@ -138,7 +147,7 @@ class EBuildStableMarkerTest(mox.MoxTestBase):
self.m_ebuild.ebuild_path = '/path/test_package-0.0.1-r1.ebuild' self.m_ebuild.ebuild_path = '/path/test_package-0.0.1-r1.ebuild'
self.revved_ebuild_path = '/path/test_package-0.0.1-r2.ebuild' self.revved_ebuild_path = '/path/test_package-0.0.1-r2.ebuild'
def testRevWorkOnEBuild(self): def testRevEBuild(self):
self.mox.StubOutWithMock(cros_mark_as_stable.fileinput, 'input') self.mox.StubOutWithMock(cros_mark_as_stable.fileinput, 'input')
self.mox.StubOutWithMock(cros_mark_as_stable.os.path, 'exists') self.mox.StubOutWithMock(cros_mark_as_stable.os.path, 'exists')
self.mox.StubOutWithMock(cros_mark_as_stable.shutil, 'copyfile') self.mox.StubOutWithMock(cros_mark_as_stable.shutil, 'copyfile')
@ -168,7 +177,7 @@ class EBuildStableMarkerTest(mox.MoxTestBase):
self.mox.ReplayAll() self.mox.ReplayAll()
marker = cros_mark_as_stable.EBuildStableMarker(self.m_ebuild) marker = cros_mark_as_stable.EBuildStableMarker(self.m_ebuild)
marker.RevWorkOnEBuild('my_id', redirect_file=m_file) marker.RevEBuild('my_id', redirect_file=m_file)
self.mox.VerifyAll() self.mox.VerifyAll()
def testRevUnchangedEBuild(self): def testRevUnchangedEBuild(self):
@ -200,7 +209,7 @@ class EBuildStableMarkerTest(mox.MoxTestBase):
self.mox.ReplayAll() self.mox.ReplayAll()
marker = cros_mark_as_stable.EBuildStableMarker(self.m_ebuild) marker = cros_mark_as_stable.EBuildStableMarker(self.m_ebuild)
marker.RevWorkOnEBuild('my_id', redirect_file=m_file) marker.RevEBuild('my_id', redirect_file=m_file)
self.mox.VerifyAll() self.mox.VerifyAll()
def testRevMissingEBuild(self): def testRevMissingEBuild(self):
@ -217,7 +226,7 @@ class EBuildStableMarkerTest(mox.MoxTestBase):
ebuild_9999 = self.m_ebuild.ebuild_path_no_version + '-9999.ebuild' ebuild_9999 = self.m_ebuild.ebuild_path_no_version + '-9999.ebuild'
cros_mark_as_stable.os.path.exists(ebuild_9999).AndReturn(False) cros_mark_as_stable.os.path.exists(ebuild_9999).AndReturn(False)
cros_mark_as_stable.Die("Missing unstable ebuild: %s" % ebuild_9999) cros_mark_as_stable.Die("Missing 9999 ebuild: %s" % ebuild_9999)
cros_mark_as_stable.shutil.copyfile(ebuild_9999, self.revved_ebuild_path) cros_mark_as_stable.shutil.copyfile(ebuild_9999, self.revved_ebuild_path)
cros_mark_as_stable.fileinput.input(self.revved_ebuild_path, cros_mark_as_stable.fileinput.input(self.revved_ebuild_path,
inplace=1).AndReturn(mock_file) inplace=1).AndReturn(mock_file)
@ -235,7 +244,7 @@ class EBuildStableMarkerTest(mox.MoxTestBase):
self.mox.ReplayAll() self.mox.ReplayAll()
marker = cros_mark_as_stable.EBuildStableMarker(self.m_ebuild) marker = cros_mark_as_stable.EBuildStableMarker(self.m_ebuild)
marker.RevWorkOnEBuild('my_id', redirect_file=m_file) marker.RevEBuild('my_id', redirect_file=m_file)
self.mox.VerifyAll() self.mox.VerifyAll()