Fixed pep8 errors

This commit is contained in:
Monty Taylor
2014-03-15 09:04:15 -07:00
committed by Darragh Bailey
parent 942de1ae2e
commit 99caa52b01
16 changed files with 97 additions and 91 deletions

View File

@@ -26,19 +26,21 @@ function test_simple_rebase() {
log DEBUG "Creating a local patch" log DEBUG "Creating a local patch"
cat <<EOP | patch -tsp1 || return 1 cat <<EOP | patch -tsp1 || return 1
diff --git a/setup.py b/setup.py diff --git a/setup.py b/setup.py
index c0a24ea..ebe20bb 100644 index 170ec46..251e1dd 100644
--- a/setup.py --- a/setup.py
+++ b/setup.py +++ b/setup.py
@@ -17,5 +17,6 @@ @@ -28,6 +28,8 @@ setup(
import setuptools version=version.version,
author="Darragh Bailey",
setuptools.setup( author_email="dbailey@hp.com",
+ terrible_local_idea=True, + maintainer="Davide Guerri",
setup_requires=['pbr'], + maintainer_email="davide.guerri@hp.com",
pbr=True) description=("Tool supporting HPCloud git workflows."),
license="Proprietary",
keywords="git hpcloud workflow",
EOP EOP
git commit -a -m "Add terrible local patch" --quiet || return 1 git commit -a -m "Add maintainer info" --quiet || return 1
git push -u origin master --quiet >/dev/null || return 1 git push -u origin master --quiet >/dev/null || return 1
log DEBUG "Cherry picking upstream commits" log DEBUG "Cherry picking upstream commits"

View File

@@ -61,7 +61,8 @@ class Drop(LogDedentMixin, GitMixin):
# test commit "id" presence # test commit "id" presence
self._commit = self.repo.commit(git_object) self._commit = self.repo.commit(git_object)
except BadObject: except BadObject:
raise DropError("Commit '%s' not found (or ambiguous)" % git_object) raise DropError(
"Commit '%s' not found (or ambiguous)" % git_object)
if not author: if not author:
self._author = '%s <%s>' % (self.repo.git.config('user.name'), self._author = '%s <%s>' % (self.repo.git.config('user.name'),

View File

@@ -43,7 +43,8 @@ class ImportUpstream(LogDedentMixin, GitMixin):
def __init__(self, branch=None, upstream=None, import_branch=None, def __init__(self, branch=None, upstream=None, import_branch=None,
extra_branches=None, *args, **kwargs): extra_branches=None, *args, **kwargs):
if not extra_branches: extra_branches = [] if not extra_branches:
extra_branches = []
self._branch = branch self._branch = branch
self._upstream = upstream self._upstream = upstream
self._import_branch = import_branch self._import_branch = import_branch
@@ -72,7 +73,8 @@ class ImportUpstream(LogDedentMixin, GitMixin):
invalid_ref = False invalid_ref = False
for branch in branches: for branch in branches:
if not any(head for head in self.repo.heads if head.name == branch): if not any(head for head in self.repo.heads
if head.name == branch):
msg = "Specified ref does not exist: '%s'" msg = "Specified ref does not exist: '%s'"
self.log.error(msg, branch) self.log.error(msg, branch)
invalid_ref = True invalid_ref = True
@@ -233,7 +235,8 @@ class ImportUpstream(LogDedentMixin, GitMixin):
if len(commit.parents) < 2: if len(commit.parents) < 2:
ancestors.add(commit.hexsha) ancestors.add(commit.hexsha)
elif any(p.hexsha not in ancestors for p in commit.parents): elif any(p.hexsha not in ancestors for p in commit.parents):
self.log.debug("Rebase upto commit SHA1: %s", commit.hexsha) self.log.debug("Rebase upto commit SHA1: %s",
commit.hexsha)
idx = idx + 1 idx = idx + 1
break break
else: else:
@@ -399,7 +402,8 @@ class ImportUpstream(LogDedentMixin, GitMixin):
# the tree object id's match # the tree object id's match
if self.git.rev_parse("HEAD^{tree}") != \ if self.git.rev_parse("HEAD^{tree}") != \
self.git.rev_parse("%s^{tree}" % self.import_branch): self.git.rev_parse("%s^{tree}" % self.import_branch):
raise ImportUpstreamError("Resulting tree does not match import") raise ImportUpstreamError(
"Resulting tree does not match import")
except (GitCommandError, ImportUpstreamError): except (GitCommandError, ImportUpstreamError):
self.log.error( self.log.error(
"""\ """\
@@ -517,7 +521,8 @@ class LocateChangesWalk(LocateChangesStrategy):
self.filters.append(ReverseCommitFilter()) self.filters.append(ReverseCommitFilter())
self.filters.append(DroppedCommitFilter()) self.filters.append(DroppedCommitFilter())
self.filters.append( self.filters.append(
SupersededCommitFilter(self.search_ref, limit=self.searcher.commit)) SupersededCommitFilter(self.search_ref,
limit=self.searcher.commit))
return super(LocateChangesWalk, self).filtered_iter() return super(LocateChangesWalk, self).filtered_iter()
@@ -533,8 +538,8 @@ class LocateChangesWalk(LocateChangesStrategy):
help='Force overwrite of existing import branch if it exists.') help='Force overwrite of existing import branch if it exists.')
@subcommand.arg('--merge', dest='merge', required=False, action='store_true', @subcommand.arg('--merge', dest='merge', required=False, action='store_true',
default=True, default=True,
help='Merge the resulting import branch into the target branch ' help='Merge the resulting import branch into the target branch'
'once complete') ' once complete')
@subcommand.arg('--no-merge', dest='merge', required=False, @subcommand.arg('--no-merge', dest='merge', required=False,
action='store_false', action='store_false',
help="Disable merge of the resulting import branch") help="Disable merge of the resulting import branch")

View File

@@ -1,18 +0,0 @@
#
# Copyright (c) 2012, 2013, 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from git_upstream.lib import note

View File

@@ -18,6 +18,7 @@
from git_upstream.errors import GitUpstreamError from git_upstream.errors import GitUpstreamError
from git import base, GitCommandError from git import base, GitCommandError
class NoteAlreadyExistsError(GitUpstreamError): class NoteAlreadyExistsError(GitUpstreamError):
"""Exception thrown by note related commands""" """Exception thrown by note related commands"""
pass pass
@@ -44,6 +45,7 @@ def add_note(self, message, force=False, note_ref='refs/notes/commits'):
else: else:
raise e raise e
def append_note(self, message, note_ref='refs/notes/commits'): def append_note(self, message, note_ref='refs/notes/commits'):
"""Add a note to an object """Add a note to an object
:param message: note message :param message: note message
@@ -51,6 +53,7 @@ def append_note(self, message, note_ref='refs/notes/commits'):
""" """
self.repo.git.notes('--ref', note_ref, 'append', '-m', message, str(self)) self.repo.git.notes('--ref', note_ref, 'append', '-m', message, str(self))
def note_message(self, note_ref='refs/notes/commits'): def note_message(self, note_ref='refs/notes/commits'):
""" """
Return note message Return note message

View File

@@ -69,7 +69,8 @@ class GitUpstreamCompatCommit(Commit):
message = '\n'.join(messages) message = '\n'.join(messages)
commits.append(GitUpstreamCompatCommit(repo, id=id, parents=parents, commits.append(GitUpstreamCompatCommit(
repo, id=id, parents=parents,
tree=tree, author=author, tree=tree, author=author,
authored_date=authored_date, authored_date=authored_date,
committer=committer, committer=committer,

View File

@@ -21,7 +21,7 @@ from git_upstream.log import LogDedentMixin
from subprocess import call from subprocess import call
import os import os
REBASE_EDITOR_SCRIPT = "rebase-editor.py" REBASE_EDITOR_SCRIPT = "rebase-editor"
# insure name of file will match any naming filters used by editors to # insure name of file will match any naming filters used by editors to
# enable syntax highlighting # enable syntax highlighting

View File

@@ -131,7 +131,8 @@ class UpstreamMergeBaseSearcher(LogDedentMixin, Searcher):
def __init__(self, pattern="upstream/*", search_tags=False, remotes=None, def __init__(self, pattern="upstream/*", search_tags=False, remotes=None,
*args, **kwargs): *args, **kwargs):
if not remotes: remotes = [] if not remotes:
remotes = []
self._pattern = pattern self._pattern = pattern
self._references = ["refs/heads/{0}".format(self.pattern)] self._references = ["refs/heads/{0}".format(self.pattern)]
@@ -160,7 +161,8 @@ class UpstreamMergeBaseSearcher(LogDedentMixin, Searcher):
""" """
Searches the git history including local and remote branches, and tags Searches the git history including local and remote branches, and tags
if tag searching is enabled. References are included in the list to be if tag searching is enabled. References are included in the list to be
checked if they match the pattern that was specified in the constructor. checked if they match the pattern that was specified in the
constructor.
While 'git rev-list' supports a glob option to check all references, it While 'git rev-list' supports a glob option to check all references, it
isn't possible to anchor the pattern, so 'upstream/*' would match all isn't possible to anchor the pattern, so 'upstream/*' would match all
of the following: of the following:
@@ -184,9 +186,8 @@ class UpstreamMergeBaseSearcher(LogDedentMixin, Searcher):
"Searching for most recent merge base with upstream branches") "Searching for most recent merge base with upstream branches")
# process pattern given to get a list of refs to check # process pattern given to get a list of refs to check
rev_list_args = self.git.for_each_ref(*self._references, rev_list_args = self.git.for_each_ref(
format="%(refname:short)" *self._references, format="%(refname:short)").splitlines()
).splitlines()
self.log.info( self.log.info(
"""\ """\
Upstream refs: Upstream refs:
@@ -237,9 +238,9 @@ class UpstreamMergeBaseSearcher(LogDedentMixin, Searcher):
revsions = self.git.rev_list(*rev_list_args).splitlines() revsions = self.git.rev_list(*rev_list_args).splitlines()
# Running 'git merge-base' is relatively expensive to pruning the list # Running 'git merge-base' is relatively expensive to pruning the list
# of revs to search since it needs to construct and walk a large portion # of revs to search since it needs to construct and walk a large
# of the tree for each call. If the constructed graph was retained # portion of the tree for each call. If the constructed graph was
# betweens we could likely remove much of the code above. # retained betweens we could likely remove much of the code above.
self.log.info( self.log.info(
"""\ """\
Running merge-base against each found upstream revision and target Running merge-base against each found upstream revision and target
@@ -264,8 +265,8 @@ class UpstreamMergeBaseSearcher(LogDedentMixin, Searcher):
git rev-list --topo-order --max-count=1 --no-walk \\ git rev-list --topo-order --max-count=1 --no-walk \\
%s %s
""", (" \\\n" + " " * 8).join(merge_bases)) """, (" \\\n" + " " * 8).join(merge_bases))
sha1 = self.git.rev_list(*merge_bases, topo_order=True, max_count=1, sha1 = self.git.rev_list(
no_walk=True) *merge_bases, topo_order=True, max_count=1, no_walk=True)
# now that we have the sha1, make sure to save the commit object # now that we have the sha1, make sure to save the commit object
self.commit = self.repo.commit(sha1) self.commit = self.repo.commit(sha1)
self.log.debug("Most recent merge-base commit is: '%s'", self.log.debug("Most recent merge-base commit is: '%s'",
@@ -418,7 +419,8 @@ class SupersededCommitFilter(LogDedentMixin, GitMixin, CommitFilter):
raise ValueError( raise ValueError(
"Invalid object: no hexsha attribute for 'limit'") "Invalid object: no hexsha attribute for 'limit'")
if not self.is_valid_commit(limit.hexsha): if not self.is_valid_commit(limit.hexsha):
raise ValueError("'limit' object does not contain a valid SHA1") raise ValueError(
"'limit' object does not contain a valid SHA1")
self.limit = limit self.limit = limit
self._regex = None self._regex = None
@@ -609,7 +611,8 @@ class DiscardDuplicateGerritChangeId(LogDedentMixin, GitMixin, CommitFilter):
raise ValueError( raise ValueError(
"Invalid object: no hexsha attribute for 'limit'") "Invalid object: no hexsha attribute for 'limit'")
if not self.is_valid_commit(limit.hexsha): if not self.is_valid_commit(limit.hexsha):
raise ValueError("'limit' object does not contain a valid SHA1") raise ValueError(
"'limit' object does not contain a valid SHA1")
self.limit = limit self.limit = limit
self._regex = None self._regex = None

View File

@@ -104,8 +104,8 @@ class DedentLoggerMeta(type):
""" """
def __new__(cls, name, bases, dict): def __new__(cls, name, bases, dict):
# provide a more intelligent error instead of waiting for setattr/getattr # provide a more intelligent error instead of waiting for
# adding of a wrapper function to fail # setattr/getattr adding of a wrapper function to fail
if logging.Logger not in bases: if logging.Logger not in bases:
raise TypeError("%s not derived from logging.Logger" % name) raise TypeError("%s not derived from logging.Logger" % name)

View File

@@ -58,15 +58,15 @@ def rebase_replace_insn(path, istream):
print stripped print stripped
if __name__ == '__main__': def main():
parser = ArgumentParser( parser = ArgumentParser(
description=__doc__.strip(), description=__doc__.strip(),
) )
parser.add_argument('-v', '--verbose', action='store_true', default=False, parser.add_argument('-v', '--verbose', action='store_true', default=False,
help='Enable verbose mode') help='Enable verbose mode')
parser.add_argument('-i', '--interactive', action='store_true', parser.add_argument('-i', '--interactive', action='store_true',
help='Enable interactive mode, where the user can edit ' help='Enable interactive mode, where the user can edit'
'the list of commits before being applied') ' the list of commits before being applied')
parser.add_argument('ifile', metavar='<new-list>', parser.add_argument('ifile', metavar='<new-list>',
help='File containing the new list of instructions to ' help='File containing the new list of instructions to '
'be placed into the rebase instructions file.') 'be placed into the rebase instructions file.')
@@ -96,7 +96,7 @@ if __name__ == '__main__':
# calling code should only override one of the two editor variables, # calling code should only override one of the two editor variables,
# starting with the one with the highest precedence # starting with the one with the highest precedence
editor=None editor = None
env = os.environ env = os.environ
for var in ['GIT_SEQUENCE_EDITOR', 'GIT_EDITOR']: for var in ['GIT_SEQUENCE_EDITOR', 'GIT_EDITOR']:
editor = env.get('GIT_UPSTREAM_' + var, None) editor = env.get('GIT_UPSTREAM_' + var, None)
@@ -121,3 +121,6 @@ if __name__ == '__main__':
"environment to call as requested by the " "environment to call as requested by the "
"--interactive option.\n") "--interactive option.\n")
sys.exit(2) sys.exit(2)
if __name__ == '__main__':
return main()

View File

@@ -28,7 +28,8 @@ class CommandException(Exception):
# following function is taken from git-review # following function is taken from git-review
def run_command(cmd, status=False, env=None): def run_command(cmd, status=False, env=None):
if not env: env = {} if not env:
env = {}
if VERBOSE: if VERBOSE:
print(datetime.datetime.now(), "Running:", cmd) print(datetime.datetime.now(), "Running:", cmd)
new_env = os.environ new_env = os.environ

View File

@@ -31,3 +31,4 @@ packages =
[entry_points] [entry_points]
console_scripts = console_scripts =
git-upstream = git_upstream.main:main git-upstream = git_upstream.main:main
rebase-editor = git_upstream.rebase_editor:main

View File

@@ -15,10 +15,11 @@ from argparse import ArgumentParser
from git_upstream import commands as c from git_upstream import commands as c
class TestGetSubcommands(testtools.TestCase): class TestGetSubcommands(testtools.TestCase):
"""Test case for get_subcommands function""" """Test case for get_subcommands function"""
_available_subcommands = ('import', 'supersede' ,'drop') _available_subcommands = ('import', 'supersede', 'drop')
def test_available_subcommands(self): def test_available_subcommands(self):
"""Test available subcommands""" """Test available subcommands"""

View File

@@ -14,20 +14,21 @@ from git_upstream.commands import drop as d
from git import repo as r from git import repo as r
from git import GitCommandError from git import GitCommandError
class TestDrop(testtools.TestCase): class TestDrop(testtools.TestCase):
"""Test case for Drop class""" """Test case for Drop class"""
first_commit = "bd6b9eefe961abe8c15cb5dc6905b92e14714a4e" first_commit = "bd6b9eefe961abe8c15cb5dc6905b92e14714a4e"
second_commit = "05fac847a5629e36050dcd69b9a782b2645d3cc7" second_commit = "05fac847a5629e36050dcd69b9a782b2645d3cc7"
invalid_commit = "this_is_an_invalid_commit" invalid_commit = "this_is_an_invalid_commit"
author="Walter White <heisenberg@hp.com>" author = "Walter White <heisenberg@hp.com>"
note_ref = 'refs/notes/upstream-merge' note_ref = 'refs/notes/upstream-merge'
def test_valid_parameters(self): def test_valid_parameters(self):
"""Test drop initialization and read properties""" """Test drop initialization and read properties"""
repo=r.Repo('.') repo = r.Repo('.')
automatic_author='%s <%s>' % (repo.git.config('user.name'), automatic_author = '%s <%s>' % (repo.git.config('user.name'),
repo.git.config('user.email')) repo.git.config('user.email'))
t = d.Drop(git_object=TestDrop.first_commit) t = d.Drop(git_object=TestDrop.first_commit)
self.assertEquals(t.author, automatic_author) self.assertEquals(t.author, automatic_author)

View File

@@ -47,10 +47,11 @@ class TestGetIncrementLevel(testtools.TestCase):
def _test_increment_by_x(self, increment=1): def _test_increment_by_x(self, increment=1):
"""Utility function that tests a given increment""" """Utility function that tests a given increment"""
levels = len(self._levels) levels = len(self._levels)
for level_no in range(levels-increment): for level_no in range(levels - increment):
for level in self._levels[level_no]: for level in self._levels[level_no]:
result = l.get_increment_level(1, level) result = l.get_increment_level(1, level)
self.assertEquals(self._levels[min(level_no+1, levels-1)][0].upper(), self.assertEquals(
self._levels[min(level_no + 1, levels - 1)][0].upper(),
result) result)
def test_increments(self): def test_increments(self):

View File

@@ -15,6 +15,7 @@ from git_upstream.commands import supersede as s
from git import repo as r from git import repo as r
from git import GitCommandError from git import GitCommandError
class TestSupersede(testtools.TestCase): class TestSupersede(testtools.TestCase):
"""Test case for Supersede class""" """Test case for Supersede class"""