diff options
Diffstat (limited to 'git')
53 files changed, 409 insertions, 409 deletions
diff --git a/git/__init__.py b/git/__init__.py index 6ccafcbb..17cd890d 100644 --- a/git/__init__.py +++ b/git/__init__.py @@ -49,5 +49,5 @@ from git.util import ( #} END imports -__all__ = [ name for name, obj in locals().items() - if not (name.startswith('_') or inspect.ismodule(obj)) ] +__all__ = [name for name, obj in locals().items() + if not (name.startswith('_') or inspect.ismodule(obj))] @@ -19,7 +19,7 @@ from subprocess import ( execute_kwargs = ('istream', 'with_keep_cwd', 'with_extended_output', 'with_exceptions', 'as_process', - 'output_stream' ) + 'output_stream') __all__ = ('Git', ) @@ -49,7 +49,7 @@ class Git(LazyMixin): # CONFIGURATION # The size in bytes read from stdout when copying git's output to another stream - max_chunk_size = 1024*64 + max_chunk_size = 1024 * 64 git_exec_name = "git" # default that should work on linux and windows git_exec_name_win = "git.cmd" # alternate command name, windows only @@ -71,7 +71,7 @@ class Git(LazyMixin): and possibly raise.""" __slots__ = ("proc", "args") - def __init__(self, proc, args ): + def __init__(self, proc, args): self.proc = proc self.args = args @@ -423,15 +423,15 @@ class Git(LazyMixin): @classmethod def __unpack_args(cls, arg_list): - if not isinstance(arg_list, (list,tuple)): + if not isinstance(arg_list, (list, tuple)): if isinstance(arg_list, unicode): return [arg_list.encode('utf-8')] - return [ str(arg_list) ] + return [str(arg_list)] outlist = list() for arg in arg_list: if isinstance(arg_list, (list, tuple)): - outlist.extend(cls.__unpack_args( arg )) + outlist.extend(cls.__unpack_args(arg)) elif isinstance(arg_list, unicode): outlist.append(arg_list.encode('utf-8')) # END recursion @@ -563,16 +563,16 @@ class Git(LazyMixin): return refstr return refstr + "\n" - def __get_persistent_cmd(self, attr_name, cmd_name, *args,**kwargs): + def __get_persistent_cmd(self, attr_name, cmd_name, *args, **kwargs): cur_val = getattr(self, attr_name) if cur_val is not None: return cur_val - options = { "istream" : PIPE, "as_process" : True } - options.update( kwargs ) + options = {"istream": PIPE, "as_process": True} + options.update(kwargs) - cmd = self._call_process( cmd_name, *args, **options ) - setattr(self, attr_name, cmd ) + cmd = self._call_process(cmd_name, *args, **options) + setattr(self, attr_name, cmd) return cmd def __get_object_header(self, cmd, ref): diff --git a/git/config.py b/git/config.py index 913b965a..b7b36e9e 100644 --- a/git/config.py +++ b/git/config.py @@ -29,7 +29,7 @@ class MetaParserBuilder(type): if kmm in clsdict: mutating_methods = clsdict[kmm] for base in bases: - methods = ( t for t in inspect.getmembers(base, inspect.ismethod) if not t[0].startswith("_") ) + methods = (t for t in inspect.getmembers(base, inspect.ismethod) if not t[0].startswith("_")) for name, method in methods: if name in clsdict: continue @@ -89,7 +89,7 @@ class SectionConstraint(object): def __getattr__(self, attr): if attr in self._valid_attrs_: return lambda *args, **kwargs: self._call_config(attr, *args, **kwargs) - return super(SectionConstraint,self).__getattribute__(attr) + return super(SectionConstraint, self).__getattribute__(attr) def _call_config(self, method, *args, **kwargs): """Call the configuration at the given method which must take a section name @@ -140,7 +140,7 @@ class GitConfigParser(cp.RawConfigParser, object): # list of RawConfigParser methods able to change the instance _mutating_methods_ = ("add_section", "remove_section", "remove_option", "set") - __slots__ = ("_sections", "_defaults", "_file_or_files", "_read_only","_is_initialized", '_lock') + __slots__ = ("_sections", "_defaults", "_file_or_files", "_read_only", "_is_initialized", '_lock') def __init__(self, file_or_files, read_only=True): """Initialize a configuration reader to read the given file_or_files and to @@ -187,7 +187,7 @@ class GitConfigParser(cp.RawConfigParser, object): try: try: self.write() - except IOError,e: + except IOError, e: print "Exception during destruction of GitConfigParser: %s" % str(e) finally: self._lock._release_lock() @@ -246,7 +246,7 @@ class GitConfigParser(cp.RawConfigParser, object): optname, vi, optval = mo.group('option', 'vi', 'value') if vi in ('=', ':') and ';' in optval: pos = optval.find(';') - if pos != -1 and optval[pos-1].isspace(): + if pos != -1 and optval[pos - 1].isspace(): optval = optval[:pos] optval = optval.strip() if optval == '""': @@ -276,7 +276,7 @@ class GitConfigParser(cp.RawConfigParser, object): files_to_read = self._file_or_files if not isinstance(files_to_read, (tuple, list)): - files_to_read = [ files_to_read ] + files_to_read = [files_to_read] for file_object in files_to_read: fp = file_object @@ -286,7 +286,7 @@ class GitConfigParser(cp.RawConfigParser, object): try: fp = open(file_object) close_fp = True - except IOError,e: + except IOError, e: continue # END fp handling @@ -312,7 +312,7 @@ class GitConfigParser(cp.RawConfigParser, object): if self._defaults: write_section(cp.DEFAULTSECT, self._defaults) - map(lambda t: write_section(t[0],t[1]), self._sections.items()) + map(lambda t: write_section(t[0], t[1]), self._sections.items()) @needs_values def write(self): @@ -368,7 +368,7 @@ class GitConfigParser(cp.RawConfigParser, object): """:return: True if this instance may change the configuration file""" return self._read_only - def get_value(self, section, option, default = None): + def get_value(self, section, option, default=None): """ :param default: If not None, the given default value will be returned in case @@ -384,17 +384,17 @@ class GitConfigParser(cp.RawConfigParser, object): return default raise - types = ( long, float ) + types = (long, float) for numtype in types: try: - val = numtype( valuestr ) + val = numtype(valuestr) # truncated value ? - if val != float( valuestr ): + if val != float(valuestr): continue return val - except (ValueError,TypeError): + except (ValueError, TypeError): continue # END for each numeric type @@ -405,8 +405,8 @@ class GitConfigParser(cp.RawConfigParser, object): if vl == 'true': return True - if not isinstance( valuestr, basestring ): - raise TypeError( "Invalid value type: only int, long, float and str are allowed", valuestr ) + if not isinstance(valuestr, basestring): + raise TypeError("Invalid value type: only int, long, float and str are allowed", valuestr) return valuestr @@ -17,7 +17,7 @@ from gitdb.db import GitDB from gitdb.db import LooseObjectDB -__all__ = ('GitCmdObjectDB', 'GitDB' ) +__all__ = ('GitCmdObjectDB', 'GitDB') #class GitCmdObjectDB(CompoundDB, ObjectDBW): diff --git a/git/diff.py b/git/diff.py index a8b12fef..009158fc 100644 --- a/git/diff.py +++ b/git/diff.py @@ -69,8 +69,8 @@ class Diffable(object): On a bare repository, 'other' needs to be provided as Index or as as Tree/Commit, or a git command error will occour""" args = list() - args.append( "--abbrev=40" ) # we need full shas - args.append( "--full-index" ) # get full index paths, not only filenames + args.append("--abbrev=40") # we need full shas + args.append("--full-index") # get full index paths, not only filenames if create_patch: args.append("-p") @@ -82,15 +82,15 @@ class Diffable(object): # fixes https://github.com/gitpython-developers/GitPython/issues/172 args.append('--no-color') - if paths is not None and not isinstance(paths, (tuple,list)): - paths = [ paths ] + if paths is not None and not isinstance(paths, (tuple, list)): + paths = [paths] if other is not None and other is not self.Index: args.insert(0, other) if other is self.Index: args.insert(0, "--cached") - args.insert(0,self) + args.insert(0, self) # paths is list here or None if paths: @@ -136,7 +136,7 @@ class DiffIndex(list): * 'R' for renamed paths * 'M' for paths with modified data""" if change_type not in self.change_type: - raise ValueError( "Invalid change type: %s" % change_type ) + raise ValueError("Invalid change type: %s" % change_type) for diff in self: if change_type == "A" and diff.new_file: @@ -195,8 +195,8 @@ class Diff(object): \.\.(?P<b_blob_id>[0-9A-Fa-f]+)[ ]?(?P<b_mode>.+)?(?:\n|$))? """, re.VERBOSE | re.MULTILINE) # can be used for comparisons - NULL_HEX_SHA = "0"*40 - NULL_BIN_SHA = "\0"*20 + NULL_HEX_SHA = "0" * 40 + NULL_BIN_SHA = "\0" * 20 __slots__ = ("a_blob", "b_blob", "a_mode", "b_mode", "new_file", "deleted_file", "rename_from", "rename_to", "diff") @@ -239,10 +239,10 @@ class Diff(object): return True def __ne__(self, other): - return not ( self == other ) + return not (self == other) def __hash__(self): - return hash(tuple(getattr(self,n) for n in self.__slots__)) + return hash(tuple(getattr(self, n) for n in self.__slots__)) def __str__(self): h = "%s" @@ -254,7 +254,7 @@ class Diff(object): msg = '' l = None # temp line ll = 0 # line length - for b,n in zip((self.a_blob, self.b_blob), ('lhs', 'rhs')): + for b, n in zip((self.a_blob, self.b_blob), ('lhs', 'rhs')): if b: l = "\n%s: %o | %s" % (n, b.mode, b.hexsha) else: @@ -265,7 +265,7 @@ class Diff(object): # END for each blob # add headline - h += '\n' + '='*ll + h += '\n' + '=' * ll if self.deleted_file: msg += '\nfile deleted in rhs' @@ -36,7 +36,7 @@ class GitCommandError(Exception): return ret -class CheckoutError( Exception ): +class CheckoutError(Exception): """Thrown if a file could not be checked out from the index as it contained changes. diff --git a/git/index/base.py b/git/index/base.py index 601f1c0e..197056b3 100644 --- a/git/index/base.py +++ b/git/index/base.py @@ -67,7 +67,7 @@ from gitdb.db import MemoryDB from gitdb.util import to_bin_sha from itertools import izip -__all__ = ( 'IndexFile', 'CheckoutError' ) +__all__ = ('IndexFile', 'CheckoutError') class IndexFile(LazyMixin, diff.Diffable, Serializable): @@ -177,7 +177,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): #} END serializable interface - def write(self, file_path = None, ignore_tree_extension_data=False): + def write(self, file_path=None, ignore_tree_extension_data=False): """Write the current state to our file path or to the given one :param file_path: @@ -322,7 +322,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): # tmp file created in git home directory to be sure renaming # works - /tmp/ dirs could be on another device - tmp_index = tempfile.mktemp('','',repo.git_dir) + tmp_index = tempfile.mktemp('', '', repo.git_dir) arg_list.append("--index-output=%s" % tmp_index) arg_list.extend(treeish) @@ -409,7 +409,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): fprogress(filepath, True, item) return rval - def iter_blobs(self, predicate = lambda t: True): + def iter_blobs(self, predicate=lambda t: True): """ :return: Iterator yielding tuples of Blob objects and stages, tuple(stage, Blob) @@ -471,13 +471,13 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): for blob in iter_blobs: stage_null_key = (blob.path, 0) if stage_null_key in self.entries: - raise ValueError( "Path %r already exists at stage 0" % blob.path ) + raise ValueError("Path %r already exists at stage 0" % blob.path) # END assert blob is not stage 0 already # delete all possible stages for stage in (1, 2, 3): try: - del( self.entries[(blob.path, stage)]) + del(self.entries[(blob.path, stage)]) except KeyError: pass # END ignore key errors @@ -537,9 +537,9 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): if it is not within our git direcotory""" if not os.path.isabs(path): return path - relative_path = path.replace(self.repo.working_tree_dir+os.sep, "") + relative_path = path.replace(self.repo.working_tree_dir + os.sep, "") if relative_path == path: - raise ValueError("Absolute path %r is not in git repository at %r" % (path,self.repo.working_tree_dir)) + raise ValueError("Absolute path %r is not in git repository at %r" % (path, self.repo.working_tree_dir)) return relative_path def _preprocess_add_items(self, items): @@ -653,7 +653,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): if paths and path_rewriter: for path in paths: abspath = os.path.abspath(path) - gitrelative_path = abspath[len(self.repo.working_tree_dir)+1:] + gitrelative_path = abspath[len(self.repo.working_tree_dir) + 1:] blob = Blob(self.repo, Blob.NULL_BIN_SHA, stat_mode_to_index_mode(os.stat(abspath).st_mode), to_native_path_linux(gitrelative_path)) @@ -689,14 +689,14 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): # HANDLE ENTRIES if entries: - null_mode_entries = [ e for e in entries if e.mode == 0 ] + null_mode_entries = [e for e in entries if e.mode == 0] if null_mode_entries: raise ValueError("At least one Entry has a null-mode - please use index.remove to remove files for clarity") # END null mode should be remove # HANLDE ENTRY OBJECT CREATION # create objects if required, otherwise go with the existing shas - null_entries_indices = [ i for i,e in enumerate(entries) if e.binsha == Object.NULL_BIN_SHA ] + null_entries_indices = [i for i, e in enumerate(entries) if e.binsha == Object.NULL_BIN_SHA] if null_entries_indices: for ei in null_entries_indices: null_entry = entries[ei] @@ -711,7 +711,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): # If we have to rewrite the entries, do so now, after we have generated # all object sha's if path_rewriter: - for i,e in enumerate(entries): + for i, e in enumerate(entries): entries[i] = BaseIndexEntry((e.mode, e.binsha, e.stage, path_rewriter(e))) # END for each entry # END handle path rewriting @@ -743,7 +743,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): may be absolute or relative paths, entries or blobs""" paths = list() for item in items: - if isinstance(item, (BaseIndexEntry,(Blob, Submodule))): + if isinstance(item, (BaseIndexEntry, (Blob, Submodule))): paths.append(self._to_relative_path(item.path)) elif isinstance(item, basestring): paths.append(self._to_relative_path(item)) @@ -801,7 +801,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): # process output to gain proper paths # rm 'path' - return [ p[4:-1] for p in removed_paths ] + return [p[4:-1] for p in removed_paths] @post_clear_cache @default_index @@ -847,7 +847,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): # parse result - first 0:n/2 lines are 'checking ', the remaining ones # are the 'renaming' ones which we parse - for ln in xrange(len(mvlines)/2, len(mvlines)): + for ln in xrange(len(mvlines) / 2, len(mvlines)): tokens = mvlines[ln].split(' to ') assert len(tokens) == 2, "Too many tokens in %s" % mvlines[ln] @@ -881,7 +881,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): return Commit.create_from_tree(self.repo, tree, message, parent_commits, head) @classmethod - def _flush_stdin_and_wait(cls, proc, ignore_stdout = False): + def _flush_stdin_and_wait(cls, proc, ignore_stdout=False): proc.stdin.flush() proc.stdin.close() stdout = '' @@ -990,7 +990,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): proc = self.repo.git.checkout_index(*args, **kwargs) proc.wait() fprogress(None, True, None) - rval_iter = ( e.path for e in self.entries.itervalues() ) + rval_iter = (e.path for e in self.entries.itervalues()) handle_stderr(proc, rval_iter) return rval_iter else: @@ -1006,7 +1006,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): kwargs['as_process'] = True kwargs['istream'] = subprocess.PIPE proc = self.repo.git.checkout_index(args, **kwargs) - make_exc = lambda : GitCommandError(("git-checkout-index",)+tuple(args), 128, proc.stderr.read()) + make_exc = lambda: GitCommandError(("git-checkout-index",) + tuple(args), 128, proc.stderr.read()) checked_out_files = list() for path in paths: @@ -1143,7 +1143,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): # if other is not None here, something is wrong if other is not None: - raise ValueError( "other must be None, Diffable.Index, a Tree or Commit, was %r" % other ) + raise ValueError("other must be None, Diffable.Index, a Tree or Commit, was %r" % other) # diff against working copy - can be handled by superclass natively return super(IndexFile, self).diff(other, paths, create_patch, **kwargs) diff --git a/git/index/fun.py b/git/index/fun.py index 2fb09675..aea7e50f 100644 --- a/git/index/fun.py +++ b/git/index/fun.py @@ -209,7 +209,7 @@ def write_tree_from_cache(entries, odb, sl, si=0): # enter recursion # ci - 1 as we want to count our current item as well - sha, tree_entry_list = write_tree_from_cache(entries, odb, slice(ci-1, xi), rbound+1) + sha, tree_entry_list = write_tree_from_cache(entries, odb, slice(ci - 1, xi), rbound + 1) tree_items_append((sha, S_IFDIR, base)) # skip ahead @@ -244,7 +244,7 @@ def aggressive_tree_merge(odb, tree_shas): # one and two way is the same for us, as we don't have to handle an existing # index, instrea - if len(tree_shas) in (1,2): + if len(tree_shas) in (1, 2): for entry in traverse_tree_recursive(odb, tree_shas[-1], ''): out_append(_tree_entry_to_baseindexentry(entry, 0)) # END for each entry @@ -265,7 +265,7 @@ def aggressive_tree_merge(odb, tree_shas): # its a conflict, otherwise we take the changed version # This should be the most common branch, so it comes first if( base[0] != ours[0] and base[0] != theirs[0] and ours[0] != theirs[0] ) or \ - ( base[1] != ours[1] and base[1] != theirs[1] and ours[1] != theirs[1] ): + (base[1] != ours[1] and base[1] != theirs[1] and ours[1] != theirs[1]): # changed by both out_append(_tree_entry_to_baseindexentry(base, 1)) out_append(_tree_entry_to_baseindexentry(ours, 2)) diff --git a/git/index/typ.py b/git/index/typ.py index 2dd82b62..8cc076a5 100644 --- a/git/index/typ.py +++ b/git/index/typ.py @@ -102,7 +102,7 @@ class BaseIndexEntry(tuple): return self[2] @classmethod - def from_blob(cls, blob, stage = 0): + def from_blob(cls, blob, stage=0): """:return: Fully equipped BaseIndexEntry at the given stage""" return cls((blob.mode, blob.binsha, stage << CE_STAGESHIFT, blob.path)) @@ -169,7 +169,7 @@ class IndexEntry(BaseIndexEntry): return IndexEntry((base.mode, base.binsha, base.flags, base.path, time, time, 0, 0, 0, 0, 0)) @classmethod - def from_blob(cls, blob, stage = 0): + def from_blob(cls, blob, stage=0): """:return: Minimal entry resembling the given blob object""" time = pack(">LL", 0, 0) return IndexEntry((blob.mode, blob.binsha, stage << CE_STAGESHIFT, blob.path, time, time, 0, 0, 0, 0, blob.size)) diff --git a/git/index/util.py b/git/index/util.py index 289a3cb1..498c0513 100644 --- a/git/index/util.py +++ b/git/index/util.py @@ -3,7 +3,7 @@ import struct import tempfile import os -__all__ = ( 'TemporaryFileSwap', 'post_clear_cache', 'default_index', 'git_working_dir' ) +__all__ = ('TemporaryFileSwap', 'post_clear_cache', 'default_index', 'git_working_dir') #{ Aliases pack = struct.pack @@ -20,7 +20,7 @@ class TemporaryFileSwap(object): def __init__(self, file_path): self.file_path = file_path - self.tmp_file_path = self.file_path + tempfile.mktemp('','','') + self.tmp_file_path = self.file_path + tempfile.mktemp('', '', '') # it may be that the source does not exist try: os.rename(self.file_path, self.tmp_file_path) @@ -64,7 +64,7 @@ def default_index(func): def check_default_index(self, *args, **kwargs): if self._file_path != self._index_path(): - raise AssertionError( "Cannot call %r on indices that do not represent the default git index" % func.__name__ ) + raise AssertionError("Cannot call %r on indices that do not represent the default git index" % func.__name__) return func(self, *args, **kwargs) # END wrpaper method diff --git a/git/objects/__init__.py b/git/objects/__init__.py index 90fe81a8..5708ac0b 100644 --- a/git/objects/__init__.py +++ b/git/objects/__init__.py @@ -17,5 +17,5 @@ from blob import * from commit import * from tree import * -__all__ = [ name for name, obj in locals().items() - if not (name.startswith('_') or inspect.ismodule(obj)) ] +__all__ = [name for name, obj in locals().items() + if not (name.startswith('_') or inspect.ismodule(obj))] diff --git a/git/objects/base.py b/git/objects/base.py index fce41a3d..d7c92d8a 100644 --- a/git/objects/base.py +++ b/git/objects/base.py @@ -21,11 +21,11 @@ __all__ = ("Object", "IndexObject") class Object(LazyMixin): """Implements an Object which may be Blobs, Trees, Commits and Tags""" - NULL_HEX_SHA = '0'*40 - NULL_BIN_SHA = '\0'*20 + NULL_HEX_SHA = '0' * 40 + NULL_BIN_SHA = '\0' * 20 TYPES = (dbtyp.str_blob_type, dbtyp.str_tree_type, dbtyp.str_commit_type, dbtyp.str_tag_type) - __slots__ = ("repo", "binsha", "size" ) + __slots__ = ("repo", "binsha", "size") type = None # to be set by subclass def __init__(self, repo, binsha): @@ -35,7 +35,7 @@ class Object(LazyMixin): :param repo: repository this object is located in :param binsha: 20 byte SHA1""" - super(Object,self).__init__() + super(Object, self).__init__() self.repo = repo self.binsha = binsha assert len(binsha) == 20, "Require 20 byte binary sha, got %r, len = %i" % (binsha, len(binsha)) @@ -75,7 +75,7 @@ class Object(LazyMixin): self.size = oinfo.size # assert oinfo.type == self.type, _assertion_msg_format % (self.binsha, oinfo.type, self.type) else: - super(Object,self)._set_cache_(attr) + super(Object, self)._set_cache_(attr) def __eq__(self, other): """:return: True if the objects have the same SHA1""" @@ -157,7 +157,7 @@ class IndexObject(Object): def _set_cache_(self, attr): if attr in IndexObject.__slots__: # they cannot be retrieved lateron ( not without searching for them ) - raise AttributeError( "path and mode attributes must have been set during %s object creation" % type(self).__name__ ) + raise AttributeError("path and mode attributes must have been set during %s object creation" % type(self).__name__) else: super(IndexObject, self)._set_cache_(attr) # END hanlde slot attribute diff --git a/git/objects/commit.py b/git/objects/commit.py index b2ed02c0..14cf5bbb 100644 --- a/git/objects/commit.py +++ b/git/objects/commit.py @@ -64,7 +64,7 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): def __init__(self, repo, binsha, tree=None, author=None, authored_date=None, author_tz_offset=None, committer=None, committed_date=None, committer_tz_offset=None, - message=None, parents=None, encoding=None, gpgsig=None): + message=None, parents=None, encoding=None, gpgsig=None): """Instantiate a new Commit. All keyword arguments taking None as default will be implicitly set on first query. :param binsha: 20 byte sha1 @@ -98,7 +98,7 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): :note: Timezone information is in the same format and in the same sign as what time.altzone returns. The sign is inverted compared to git's UTC timezone.""" - super(Commit,self).__init__(repo, binsha) + super(Commit, self).__init__(repo, binsha) if tree is not None: assert isinstance(tree, Tree), "Tree needs to be a Tree instance, was %s" % type(tree) if tree is not None: @@ -235,7 +235,7 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): :param proc: git-rev-list process instance - one sha per line :return: iterator returning Commit objects""" stream = proc_or_stream - if not hasattr(stream,'readline'): + if not hasattr(stream, 'readline'): stream = proc_or_stream.stdout readline = stream.readline @@ -286,7 +286,7 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): parents = parent_commits if parent_commits is None: try: - parent_commits = [ repo.head.commit ] + parent_commits = [repo.head.commit] except ValueError: # empty repositories have no head commit parent_commits = list() @@ -400,7 +400,7 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): if self.gpgsig: write("gpgsig") for sigline in self.gpgsig.rstrip("\n").split("\n"): - write(" "+sigline+"\n") + write(" " + sigline + "\n") write("\n") @@ -416,7 +416,7 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): """:param from_rev_list: if true, the stream format is coming from the rev-list command Otherwise it is assumed to be a plain data stream from our object""" readline = stream.readline - self.tree = Tree(self.repo, hex_to_bin(readline().split()[1]), Tree.tree_id<<12, '') + self.tree = Tree(self.repo, hex_to_bin(readline().split()[1]), Tree.tree_id << 12, '') self.parents = list() next_line = None @@ -449,9 +449,9 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): buf = enc.strip() while buf != "": if buf[0:10] == "encoding ": - self.encoding = buf[buf.find(' ')+1:] + self.encoding = buf[buf.find(' ') + 1:] elif buf[0:7] == "gpgsig ": - sig = buf[buf.find(' ')+1:] + "\n" + sig = buf[buf.find(' ') + 1:] + "\n" is_next_header = False while True: sigbuf = readline() diff --git a/git/objects/fun.py b/git/objects/fun.py index 8f5a5cc2..0bb14376 100644 --- a/git/objects/fun.py +++ b/git/objects/fun.py @@ -15,7 +15,7 @@ def tree_to_stream(entries, write): for binsha, mode, name in entries: mode_str = '' for i in xrange(6): - mode_str = chr(((mode >> (i*3)) & bit_mask) + ord_zero) + mode_str + mode_str = chr(((mode >> (i * 3)) & bit_mask) + ord_zero) + mode_str # END for each 8 octal value # git slices away the first octal if its zero @@ -79,7 +79,7 @@ def tree_entries_from_data(data): # byte is NULL, get next 20 i += 1 - sha = data[i:i+20] + sha = data[i:i + 20] i = i + 20 out.append((sha, mode, name)) # END for each byte in data stream @@ -112,7 +112,7 @@ def _to_full_path(item, path_prefix): """Rebuild entry with given path prefix""" if not item: return item - return (item[0], item[1], path_prefix+item[2]) + return (item[0], item[1], path_prefix + item[2]) def traverse_trees_recursive(odb, tree_shas, path_prefix): @@ -152,7 +152,7 @@ def traverse_trees_recursive(odb, tree_shas, path_prefix): if not item: continue # END skip already done items - entries = [ None for n in range(nt) ] + entries = [None for n in range(nt)] entries[ti] = item sha, mode, name = item # its faster to unpack is_dir = S_ISDIR(mode) # type mode bits @@ -160,14 +160,14 @@ def traverse_trees_recursive(odb, tree_shas, path_prefix): # find this item in all other tree data items # wrap around, but stop one before our current index, hence # ti+nt, not ti+1+nt - for tio in range(ti+1, ti+nt): + for tio in range(ti + 1, ti + nt): tio = tio % nt entries[tio] = _find_by_name(trees_data[tio], name, is_dir, ii) # END for each other item data # if we are a directory, enter recursion if is_dir: - out.extend(traverse_trees_recursive(odb, [((ei and ei[0]) or None) for ei in entries], path_prefix+name+'/')) + out.extend(traverse_trees_recursive(odb, [((ei and ei[0]) or None) for ei in entries], path_prefix + name + '/')) else: out_append(tuple(_to_full_path(e, path_prefix) for e in entries)) # END handle recursion @@ -196,9 +196,9 @@ def traverse_tree_recursive(odb, tree_sha, path_prefix): # unpacking/packing is faster than accessing individual items for sha, mode, name in data: if S_ISDIR(mode): - entries.extend(traverse_tree_recursive(odb, sha, path_prefix+name+'/')) + entries.extend(traverse_tree_recursive(odb, sha, path_prefix + name + '/')) else: - entries.append((sha, mode, path_prefix+name)) + entries.append((sha, mode, path_prefix + name)) # END for each item return entries diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 42048028..770dcffd 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -37,7 +37,7 @@ class UpdateProgress(RemoteProgress): """Class providing detailed progress information to the caller who should derive from it and implement the ``update(...)`` message""" - CLONE, FETCH, UPDWKTREE = [1 << x for x in range(RemoteProgress._num_op_codes, RemoteProgress._num_op_codes+3)] + CLONE, FETCH, UPDWKTREE = [1 << x for x in range(RemoteProgress._num_op_codes, RemoteProgress._num_op_codes + 3)] _num_op_codes = RemoteProgress._num_op_codes + 3 __slots__ = tuple() @@ -75,7 +75,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): __slots__ = ('_parent_commit', '_url', '_branch_path', '_name', '__weakref__') _cache_attrs = ('path', '_url', '_branch_path') - def __init__(self, repo, binsha, mode=None, path=None, name = None, parent_commit=None, url=None, branch_path=None): + def __init__(self, repo, binsha, mode=None, path=None, name=None, parent_commit=None, url=None, branch_path=None): """Initialize this instance with its attributes. We only document the ones that differ from ``IndexObject`` @@ -168,7 +168,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): raise ValueError("Cannot write blobs of 'historical' submodule configurations") # END handle writes of historical submodules - return SubmoduleConfigParser(fp_module, read_only = read_only) + return SubmoduleConfigParser(fp_module, read_only=read_only) def _clear_cache(self): # clear the possibly changed values @@ -277,7 +277,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): url = urls[0] else: # clone new repo - kwargs = {'n' : no_checkout} + kwargs = {'n': no_checkout} if not branch_is_default: kwargs['b'] = br.name # END setup checkout-branch @@ -354,16 +354,16 @@ class Submodule(util.IndexObject, Iterable, Traversable): op |= BEGIN #END handle start - progress.update(op, i, len_rmts, prefix+"Fetching remote %s of submodule %r" % (remote, self.name)) + progress.update(op, i, len_rmts, prefix + "Fetching remote %s of submodule %r" % (remote, self.name)) #=============================== if not dry_run: remote.fetch(progress=progress) #END handle dry-run #=============================== - if i == len_rmts-1: + if i == len_rmts - 1: op |= END #END handle end - progress.update(op, i, len_rmts, prefix+"Done fetching remote of submodule %r" % self.name) + progress.update(op, i, len_rmts, prefix + "Done fetching remote of submodule %r" % self.name) #END fetch new data except InvalidGitRepositoryError: if not init: @@ -383,11 +383,11 @@ class Submodule(util.IndexObject, Iterable, Traversable): # don't check it out at first - nonetheless it will create a local # branch according to the remote-HEAD if possible - progress.update(BEGIN|CLONE, 0, 1, prefix+"Cloning %s to %s in submodule %r" % (self.url, module_path, self.name)) + progress.update(BEGIN | CLONE, 0, 1, prefix + "Cloning %s to %s in submodule %r" % (self.url, module_path, self.name)) if not dry_run: mrepo = git.Repo.clone_from(self.url, module_path, n=True) #END handle dry-run - progress.update(END|CLONE, 0, 1, prefix+"Done cloning to %s" % module_path) + progress.update(END | CLONE, 0, 1, prefix + "Done cloning to %s" % module_path) if not dry_run: # see whether we have a valid branch to checkout @@ -444,7 +444,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): # update the working tree # handles dry_run if mrepo is not None and mrepo.head.commit.binsha != binsha: - progress.update(BEGIN|UPDWKTREE, 0, 1, prefix+"Updating working tree at %s for submodule %r to revision %s" % (self.path, self.name, hexsha)) + progress.update(BEGIN | UPDWKTREE, 0, 1, prefix + "Updating working tree at %s for submodule %r to revision %s" % (self.path, self.name, hexsha)) if not dry_run: if is_detached: # NOTE: for now we force, the user is no supposed to change detached @@ -459,7 +459,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): mrepo.head.reset(hexsha, index=True, working_tree=True) # END handle checkout #END handle dry_run - progress.update(END|UPDWKTREE, 0, 1, prefix+"Done updating working tree for submodule %r" % self.name) + progress.update(END | UPDWKTREE, 0, 1, prefix + "Done updating working tree for submodule %r" % self.name) # END update to new commit only if needed # HANDLE RECURSION @@ -557,7 +557,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): ekey = index.entry_key(self.path, 0) entry = index.entries[ekey] del(index.entries[ekey]) - nentry = git.IndexEntry(entry[:3]+(module_path,)+entry[4:]) + nentry = git.IndexEntry(entry[:3] + (module_path,) + entry[4:]) index.entries[tekey] = nentry except KeyError: raise InvalidGitRepositoryError("Submodule's entry at %r did not exist" % (self.path)) diff --git a/git/objects/submodule/root.py b/git/objects/submodule/root.py index 62ad1f05..b8cc904c 100644 --- a/git/objects/submodule/root.py +++ b/git/objects/submodule/root.py @@ -13,8 +13,8 @@ __all__ = ["RootModule", "RootUpdateProgress"] class RootUpdateProgress(UpdateProgress): """Utility class which adds more opcodes to the UpdateProgress""" - REMOVE, PATHCHANGE, BRANCHCHANGE, URLCHANGE = [1 << x for x in range(UpdateProgress._num_op_codes, UpdateProgress._num_op_codes+4)] - _num_op_codes = UpdateProgress._num_op_codes+4 + REMOVE, PATHCHANGE, BRANCHCHANGE, URLCHANGE = [1 << x for x in range(UpdateProgress._num_op_codes, UpdateProgress._num_op_codes + 4)] + _num_op_codes = UpdateProgress._num_op_codes + 4 __slots__ = tuple() @@ -39,13 +39,13 @@ class RootModule(Submodule): # repo, binsha, mode=None, path=None, name = None, parent_commit=None, url=None, ref=None) super(RootModule, self).__init__( repo, - binsha = self.NULL_BIN_SHA, - mode = self.k_default_mode, - path = '', - name = self.k_root_name, - parent_commit = repo.head.commit, - url = '', - branch_path = git.Head.to_full_path(self.k_head_default) + binsha=self.NULL_BIN_SHA, + mode=self.k_default_mode, + path='', + name=self.k_root_name, + parent_commit=repo.head.commit, + url='', + branch_path=git.Head.to_full_path(self.k_head_default) ) def _clear_cache(self): @@ -126,16 +126,16 @@ class RootModule(Submodule): # fake it into thinking its at the current commit to allow deletion # of previous module. Trigger the cache to be updated before that - progress.update(op, i, len_rrsm, prefix+"Removing submodule %r at %s" % (rsm.name, rsm.abspath)) + progress.update(op, i, len_rrsm, prefix + "Removing submodule %r at %s" % (rsm.name, rsm.abspath)) rsm._parent_commit = repo.head.commit if not dry_run: rsm.remove(configuration=False, module=True, force=force_remove) #END handle dry-run - if i == len_rrsm-1: + if i == len_rrsm - 1: op |= END #END handle end - progress.update(op, i, len_rrsm, prefix+"Done removing submodule %r" % rsm.name) + progress.update(op, i, len_rrsm, prefix + "Done removing submodule %r" % rsm.name) # END for each removed submodule # HANDLE PATH RENAMES @@ -150,12 +150,12 @@ class RootModule(Submodule): #PATH CHANGES ############## if sm.path != psm.path and psm.module_exists(): - progress.update(BEGIN|PATHCHANGE, i, len_csms, prefix+"Moving repository of submodule %r from %s to %s" % (sm.name, psm.abspath, sm.abspath)) + progress.update(BEGIN | PATHCHANGE, i, len_csms, prefix + "Moving repository of submodule %r from %s to %s" % (sm.name, psm.abspath, sm.abspath)) # move the module to the new path if not dry_run: psm.move(sm.path, module=True, configuration=False) #END handle dry_run - progress.update(END|PATHCHANGE, i, len_csms, prefix+"Done moving repository of submodule %r" % sm.name) + progress.update(END | PATHCHANGE, i, len_csms, prefix + "Done moving repository of submodule %r" % sm.name) # END handle path changes if sm.module_exists(): @@ -171,7 +171,7 @@ class RootModule(Submodule): # don't do anything if we already have the url we search in place if len([r for r in rmts if r.url == sm.url]) == 0: - progress.update(BEGIN|URLCHANGE, i, len_csms, prefix+"Changing url of submodule %r from %s to %s" % (sm.name, psm.url, sm.url)) + progress.update(BEGIN | URLCHANGE, i, len_csms, prefix + "Changing url of submodule %r from %s to %s" % (sm.name, psm.url, sm.url)) if not dry_run: assert nn not in [r.name for r in rmts] @@ -245,7 +245,7 @@ class RootModule(Submodule): #NOTE: All checkout is performed by the base implementation of update #END handle dry_run - progress.update(END|URLCHANGE, i, len_csms, prefix+"Done adjusting url of submodule %r" % (sm.name)) + progress.update(END | URLCHANGE, i, len_csms, prefix + "Done adjusting url of submodule %r" % (sm.name)) # END skip remote handling if new url already exists in module # END handle url @@ -254,7 +254,7 @@ class RootModule(Submodule): if sm.branch_path != psm.branch_path: # finally, create a new tracking branch which tracks the # new remote branch - progress.update(BEGIN|BRANCHCHANGE, i, len_csms, prefix+"Changing branch of submodule %r from %s to %s" % (sm.name, psm.branch_path, sm.branch_path)) + progress.update(BEGIN | BRANCHCHANGE, i, len_csms, prefix + "Changing branch of submodule %r from %s to %s" % (sm.name, psm.branch_path, sm.branch_path)) if not dry_run: smm = sm.module() smmr = smm.remotes @@ -283,7 +283,7 @@ class RootModule(Submodule): #NOTE: All checkout is done in the base implementation of update #END handle dry_run - progress.update(END|BRANCHCHANGE, i, len_csms, prefix+"Done changing branch of submodule %r" % sm.name) + progress.update(END | BRANCHCHANGE, i, len_csms, prefix + "Done changing branch of submodule %r" % sm.name) #END handle branch #END handle # END for each common submodule @@ -302,7 +302,7 @@ class RootModule(Submodule): if recursive: # the module would exist by now if we are not in dry_run mode if sm.module_exists(): - type(self)(sm.module()).update( recursive=True, force_remove=force_remove, + type(self)(sm.module()).update(recursive=True, force_remove=force_remove, init=init, to_latest_revision=to_latest_revision, progress=progress, dry_run=dry_run) #END handle dry_run diff --git a/git/objects/submodule/util.py b/git/objects/submodule/util.py index 47b45109..a66fcddc 100644 --- a/git/objects/submodule/util.py +++ b/git/objects/submodule/util.py @@ -4,7 +4,7 @@ from git.config import GitConfigParser from StringIO import StringIO import weakref -__all__ = ( 'sm_section', 'sm_name', 'mkhead', 'unbare_repo', 'find_first_remote_branch', +__all__ = ('sm_section', 'sm_name', 'mkhead', 'unbare_repo', 'find_first_remote_branch', 'SubmoduleConfigParser') #{ Utilities diff --git a/git/objects/tag.py b/git/objects/tag.py index 3690dc45..7ba8ce29 100644 --- a/git/objects/tag.py +++ b/git/objects/tag.py @@ -18,7 +18,7 @@ class TagObject(base.Object): """Non-Lightweight tag carrying additional information about an object we are pointing to.""" type = "tag" - __slots__ = ( "object", "tag", "tagger", "tagged_date", "tagger_tz_offset", "message" ) + __slots__ = ("object", "tag", "tagger", "tagged_date", "tagger_tz_offset", "message") def __init__(self, repo, binsha, object=None, tag=None, tagger=None, tagged_date=None, tagger_tz_offset=None, message=None): @@ -34,7 +34,7 @@ class TagObject(base.Object): it into a different format :param tagged_tz_offset: int_seconds_west_of_utc is the timezone that the authored_date is in, in a format similar to time.altzone""" - super(TagObject, self).__init__(repo, binsha ) + super(TagObject, self).__init__(repo, binsha) if object is not None: self.object = object if tag is not None: diff --git a/git/objects/tree.py b/git/objects/tree.py index 4984823e..e4e49d1a 100644 --- a/git/objects/tree.py +++ b/git/objects/tree.py @@ -125,13 +125,13 @@ class Tree(IndexObject, diff.Diffable, util.Traversable, util.Serializable): tree_id = 004 _map_id_to_type = { - commit_id : Submodule, - blob_id : Blob, - symlink_id : Blob + commit_id: Submodule, + blob_id: Blob, + symlink_id: Blob # tree id added once Tree is defined } - def __init__(self, repo, binsha, mode=tree_id<<12, path=None): + def __init__(self, repo, binsha, mode=tree_id << 12, path=None): super(Tree, self).__init__(repo, binsha, mode, path) @classmethod @@ -170,13 +170,13 @@ class Tree(IndexObject, diff.Diffable, util.Traversable, util.Serializable): tree = self item = self tokens = file.split('/') - for i,token in enumerate(tokens): + for i, token in enumerate(tokens): item = tree[token] if item.type == 'tree': tree = item else: # safety assertion - blobs are at the end of the path - if i != len(tokens)-1: + if i != len(tokens) - 1: raise KeyError(msg % file) return item # END handle item type @@ -189,18 +189,18 @@ class Tree(IndexObject, diff.Diffable, util.Traversable, util.Serializable): if info[2] == file: # [2] == name return self._map_id_to_type[info[1] >> 12](self.repo, info[0], info[1], join_path(self.path, info[2])) # END for each obj - raise KeyError( msg % file ) + raise KeyError(msg % file) # END handle long paths @property def trees(self): """:return: list(Tree, ...) list of trees directly below this tree""" - return [ i for i in self if i.type == "tree" ] + return [i for i in self if i.type == "tree"] @property def blobs(self): """:return: list(Blob, ...) list of blobs directly below this tree""" - return [ i for i in self if i.type == "blob" ] + return [i for i in self if i.type == "blob"] @property def cache(self): @@ -211,9 +211,9 @@ class Tree(IndexObject, diff.Diffable, util.Traversable, util.Serializable): See the ``TreeModifier`` for more information on how to alter the cache""" return TreeModifier(self._cache) - def traverse( self, predicate = lambda i,d: True, - prune = lambda i,d: False, depth = -1, branch_first=True, - visit_once = False, ignore_self=1 ): + def traverse(self, predicate=lambda i, d: True, + prune=lambda i, d: False, depth=-1, branch_first=True, + visit_once=False, ignore_self=1): """For documentation, see util.Traversable.traverse Trees are set to visit_once = False to gain more performance in the traversal""" return super(Tree, self).traverse(predicate, prune, depth, branch_first, visit_once, ignore_self) @@ -238,7 +238,7 @@ class Tree(IndexObject, diff.Diffable, util.Traversable, util.Serializable): return self.__div__(item) # END index is basestring - raise TypeError( "Invalid index type: %r" % item ) + raise TypeError("Invalid index type: %r" % item) def __contains__(self, item): if isinstance(item, IndexObject): diff --git a/git/objects/util.py b/git/objects/util.py index 9f947fcc..6321399d 100644 --- a/git/objects/util.py +++ b/git/objects/util.py @@ -33,7 +33,7 @@ def mode_str_to_int(modestr): for example.""" mode = 0 for iteration, char in enumerate(reversed(modestr[-6:])): - mode += int(char) << iteration*3 + mode += int(char) << iteration * 3 # END for each char return mode @@ -67,15 +67,15 @@ def utctz_to_altz(utctz): returns. Git stores it as UTC timezone which has the opposite sign as well, which explains the -1 * ( that was made explicit here ) :param utctz: git utc timezone string, i.e. +0200""" - return -1 * int(float(utctz)/100*3600) + return -1 * int(float(utctz) / 100 * 3600) def altz_to_utctz_str(altz): """As above, but inverses the operation, returning a string that can be used in commit objects""" - utci = -1 * int((altz / 3600)*100) + utci = -1 * int((altz / 3600) * 100) utcs = str(abs(utci)) - utcs = "0"*(4-len(utcs)) + utcs + utcs = "0" * (4 - len(utcs)) + utcs prefix = (utci < 0 and '-') or '+' return prefix + utcs @@ -144,7 +144,7 @@ def parse_date(string_date): assert splitter > -1 # split date and time - time_part = string_date[splitter+1:] # skip space + time_part = string_date[splitter + 1:] # skip space date_part = string_date[:splitter] # parse time @@ -237,9 +237,9 @@ class Traversable(object): out.extend(self.traverse(*args, **kwargs)) return out - def traverse( self, predicate = lambda i,d: True, - prune = lambda i,d: False, depth = -1, branch_first=True, - visit_once = True, ignore_self=1, as_edge = False ): + def traverse(self, predicate=lambda i, d: True, + prune=lambda i, d: False, depth=-1, branch_first=True, + visit_once=True, ignore_self=1, as_edge=False): """:return: iterator yieling of items found when traversing self :param predicate: f(i,d) returns False if item i at depth d should not be included in the result @@ -272,17 +272,17 @@ class Traversable(object): source to destination""" visited = set() stack = Deque() - stack.append( ( 0 ,self, None ) ) # self is always depth level 0 + stack.append((0, self, None)) # self is always depth level 0 - def addToStack( stack, item, branch_first, depth ): - lst = self._get_intermediate_items( item ) + def addToStack(stack, item, branch_first, depth): + lst = self._get_intermediate_items(item) if not lst: return if branch_first: - stack.extendleft( ( depth , i, item ) for i in lst ) + stack.extendleft((depth, i, item) for i in lst) else: - reviter = ( ( depth , lst[i], item ) for i in range( len( lst )-1,-1,-1) ) - stack.extend( reviter ) + reviter = ((depth, lst[i], item) for i in range(len(lst) - 1, -1, -1)) + stack.extend(reviter) # END addToStack local method while stack: @@ -294,12 +294,12 @@ class Traversable(object): if visit_once: visited.add(item) - rval = ( as_edge and (src, item) ) or item - if prune( rval, d ): + rval = (as_edge and (src, item)) or item + if prune(rval, d): continue - skipStartItem = ignore_self and ( item is self ) - if not skipStartItem and predicate( rval, d ): + skipStartItem = ignore_self and (item is self) + if not skipStartItem and predicate(rval, d): yield rval # only continue to next level if this is appropriate ! @@ -307,7 +307,7 @@ class Traversable(object): if depth > -1 and nd > depth: continue - addToStack( stack, item, branch_first, nd ) + addToStack(stack, item, branch_first, nd) # END for each item on work stack diff --git a/git/odict.py b/git/odict.py index 238c0ea8..55bb1c43 100644 --- a/git/odict.py +++ b/git/odict.py @@ -654,7 +654,7 @@ class OrderedDict(dict): raise IndexError('popitem(): index %s not valid' % i) return (key, self.pop(key)) - def setdefault(self, key, defval = None): + def setdefault(self, key, defval=None): """ >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) >>> d.setdefault(1) @@ -967,7 +967,7 @@ class Keys(object): def sort(self, *args, **kwds): self._main._sequence.sort(*args, **kwds) - def __mul__(self, n): return self._main._sequence*n + def __mul__(self, n): return self._main._sequence * n __rmul__ = __mul__ def __add__(self, other): return self._main._sequence + other @@ -1075,7 +1075,7 @@ class Items(object): def sort(self, *args, **kwds): self._main.sort(*args, **kwds) - def __mul__(self, n): return self._main.items()*n + def __mul__(self, n): return self._main.items() * n __rmul__ = __mul__ def __add__(self, other): return self._main.items() + other @@ -1205,7 +1205,7 @@ class Values(object): vals.sort(*args, **kwds) self[:] = vals - def __mul__(self, n): return self._main.values()*n + def __mul__(self, n): return self._main.values() * n __rmul__ = __mul__ def __add__(self, other): return self._main.values() + other diff --git a/git/refs/head.py b/git/refs/head.py index 662c2c87..958f83fa 100644 --- a/git/refs/head.py +++ b/git/refs/head.py @@ -29,7 +29,7 @@ class HEAD(SymbolicReference): to contain the previous value of HEAD""" return SymbolicReference(self.repo, self._ORIG_HEAD_NAME) - def reset(self, commit='HEAD', index=True, working_tree = False, + def reset(self, commit='HEAD', index=True, working_tree=False, paths=None, **kwargs): """Reset our HEAD to the given commit optionally synchronizing the index and working tree. The reference we refer to will be set to @@ -71,7 +71,7 @@ class HEAD(SymbolicReference): if working_tree: mode = "--hard" if not index: - raise ValueError( "Cannot reset the working tree if the index is not reset as well") + raise ValueError("Cannot reset the working tree if the index is not reset as well") # END working tree handling diff --git a/git/refs/log.py b/git/refs/log.py index 8917f3fa..c075e7a0 100644 --- a/git/refs/log.py +++ b/git/refs/log.py @@ -100,8 +100,8 @@ class RefLogEntry(tuple): raise ValueError("Missing token: >") #END handle missing end brace - actor = Actor._from_string(info[82:email_end+1]) - time, tz_offset = parse_date(info[email_end+2:]) + actor = Actor._from_string(info[82:email_end + 1]) + time, tz_offset = parse_date(info[email_end + 2:]) return RefLogEntry((oldhexsha, newhexsha, actor, (time, tz_offset), msg)) @@ -200,7 +200,7 @@ class RefLog(list, Serializable): return RefLogEntry.from_line(fp.readlines()[index].strip()) else: # read until index is reached - for i in xrange(index+1): + for i in xrange(index + 1): line = fp.readline() if not line: break diff --git a/git/refs/reference.py b/git/refs/reference.py index a8ecc95d..dc745cce 100644 --- a/git/refs/reference.py +++ b/git/refs/reference.py @@ -36,7 +36,7 @@ class Reference(SymbolicReference, LazyMixin, Iterable): _resolve_ref_on_create = True _common_path_default = "refs" - def __init__(self, repo, path, check_path = True): + def __init__(self, repo, path, check_path=True): """Initialize this instance :param repo: Our parent repository @@ -45,7 +45,7 @@ class Reference(SymbolicReference, LazyMixin, Iterable): refs/heads/master :param check_path: if False, you can provide any path. Otherwise the path must start with the default path prefix of this type.""" - if check_path and not path.startswith(self._common_path_default+'/'): + if check_path and not path.startswith(self._common_path_default + '/'): raise ValueError("Cannot instantiate %r from path %s" % (self.__class__.__name__, path)) super(Reference, self).__init__(repo, path) @@ -54,7 +54,7 @@ class Reference(SymbolicReference, LazyMixin, Iterable): #{ Interface - def set_object(self, object, logmsg = None): + def set_object(self, object, logmsg=None): """Special version which checks if the head-log needs an update as well""" oldbinsha = None if logmsg is not None: @@ -95,7 +95,7 @@ class Reference(SymbolicReference, LazyMixin, Iterable): return '/'.join(tokens[2:]) @classmethod - def iter_items(cls, repo, common_path = None): + def iter_items(cls, repo, common_path=None): """Equivalent to SymbolicReference.iter_items, but will return non-detached references as well.""" return cls._iter_items(repo, common_path) diff --git a/git/refs/remote.py b/git/refs/remote.py index 6dd0856c..394ad9e5 100644 --- a/git/refs/remote.py +++ b/git/refs/remote.py @@ -14,7 +14,7 @@ class RemoteReference(Head): _common_path_default = Head._remote_common_path_default @classmethod - def iter_items(cls, repo, common_path = None, remote=None): + def iter_items(cls, repo, common_path=None, remote=None): """Iterate remote references, and if given, constrain them to the given remote""" common_path = common_path or cls._common_path_default if remote is not None: diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 6832b8f2..1115ac9c 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -54,7 +54,7 @@ class SymbolicReference(object): return False def __ne__(self, other): - return not ( self == other ) + return not (self == other) def __hash__(self): return hash(self.path) @@ -99,7 +99,7 @@ class SymbolicReference(object): yield tuple(line.split(' ', 1)) # END for each line - except (OSError,IOError): + except (OSError, IOError): raise StopIteration # END no packed-refs file handling # NOTE: Had try-finally block around here to close the fp, @@ -130,7 +130,7 @@ class SymbolicReference(object): value = fp.read().rstrip() fp.close() tokens = value.split(" ") - except (OSError,IOError): + except (OSError, IOError): # Probably we are just packed, find our entry in the packed refs file # NOTE: We are not a symbolic ref if we are in a packed file, as these # are excluded explictly @@ -177,7 +177,7 @@ class SymbolicReference(object): #END handle type return obj - def set_commit(self, commit, logmsg = None): + def set_commit(self, commit, logmsg=None): """As set_object, but restricts the type of object to be a Commit :raise ValueError: If commit is not a Commit object or doesn't point to @@ -206,7 +206,7 @@ class SymbolicReference(object): return self - def set_object(self, object, logmsg = None): + def set_object(self, object, logmsg=None): """Set the object we point to, possibly dereference our symbolic reference first. If the reference does not exist, it will be created @@ -245,7 +245,7 @@ class SymbolicReference(object): raise TypeError("%s is a detached symbolic reference as it points to %r" % (self, sha)) return self.from_path(self.repo, target_ref_path) - def set_reference(self, ref, logmsg = None): + def set_reference(self, ref, logmsg=None): """Set ourselves to the given ref. It will stay a symbol if the ref is a Reference. Otherwise an Object, given as Object instance or refspec, is assumed and if valid, will be set which effectively detaches the refererence if it was a purely @@ -272,7 +272,7 @@ class SymbolicReference(object): write_value = ref.hexsha elif isinstance(ref, basestring): try: - obj = self.repo.rev_parse(ref+"^{}") # optionally deref tags + obj = self.repo.rev_parse(ref + "^{}") # optionally deref tags write_value = obj.hexsha except BadObject: raise ValueError("Could not extract object from %s" % ref) @@ -378,7 +378,7 @@ class SymbolicReference(object): full_ref_path = path if not cls._common_path_default: return full_ref_path - if not path.startswith(cls._common_path_default+"/"): + if not path.startswith(cls._common_path_default + "/"): full_ref_path = '%s/%s' % (cls._common_path_default, path) return full_ref_path @@ -402,7 +402,7 @@ class SymbolicReference(object): pack_file_path = cls._get_packed_refs_path(repo) try: reader = open(pack_file_path, 'rb') - except (OSError,IOError): + except (OSError, IOError): pass # it didnt exist at all else: new_lines = list() @@ -414,7 +414,7 @@ class SymbolicReference(object): # If we deleted the last line and this one is a tag-reference object, # we drop it as well if ( line.startswith('#') or full_ref_path not in line ) and \ - ( not dropped_last_line or dropped_last_line and not line.startswith('^') ): + (not dropped_last_line or dropped_last_line and not line.startswith('^')): new_lines.append(line) dropped_last_line = False continue @@ -526,7 +526,7 @@ class SymbolicReference(object): if isfile(new_abs_path): if not force: # if they point to the same file, its not an error - if open(new_abs_path,'rb').read().strip() != open(cur_abs_path,'rb').read().strip(): + if open(new_abs_path, 'rb').read().strip() != open(cur_abs_path, 'rb').read().strip(): raise OSError("File at path %r already exists" % new_abs_path) # else: we could remove ourselves and use the otherone, but # but clarity we just continue as usual @@ -545,7 +545,7 @@ class SymbolicReference(object): return self @classmethod - def _iter_items(cls, repo, common_path = None): + def _iter_items(cls, repo, common_path=None): if common_path is None: common_path = cls._common_path_default rela_paths = set() @@ -554,7 +554,7 @@ class SymbolicReference(object): # Currently we do not follow links for root, dirs, files in os.walk(join_path_native(repo.git_dir, common_path)): if 'refs/' not in root: # skip non-refs subfolders - refs_id = [ d for d in dirs if d == 'refs' ] + refs_id = [d for d in dirs if d == 'refs'] if refs_id: dirs[0:] = ['refs'] # END prune non-refs folders @@ -581,7 +581,7 @@ class SymbolicReference(object): # END for each sorted relative refpath @classmethod - def iter_items(cls, repo, common_path = None): + def iter_items(cls, repo, common_path=None): """Find all refs in the repository :param repo: is the Repo @@ -598,7 +598,7 @@ class SymbolicReference(object): List is lexigraphically sorted The returned objects represent actual subclasses, such as Head or TagReference""" - return ( r for r in cls._iter_items(repo, common_path) if r.__class__ == SymbolicReference or not r.is_detached ) + return (r for r in cls._iter_items(repo, common_path) if r.__class__ == SymbolicReference or not r.is_detached) @classmethod def from_path(cls, repo, path): diff --git a/git/refs/tag.py b/git/refs/tag.py index 2845ec7c..ff32224a 100644 --- a/git/refs/tag.py +++ b/git/refs/tag.py @@ -30,7 +30,7 @@ class TagReference(Reference): # it is a tag object which carries the commit as an object - we can point to anything return obj.object else: - raise ValueError( "Tag %s points to a Blob or Tree - have never seen that before" % self ) + raise ValueError("Tag %s points to a Blob or Tree - have never seen that before" % self) @property def tag(self): @@ -71,7 +71,7 @@ class TagReference(Reference): Additional keyword arguments to be passed to git-tag :return: A new TagReference""" - args = ( path, ref ) + args = (path, ref) if message: kwargs['m'] = message if force: diff --git a/git/remote.py b/git/remote.py index 7611f743..a9dcb3cb 100644 --- a/git/remote.py +++ b/git/remote.py @@ -98,11 +98,11 @@ class PushInfo(object): __slots__ = ('local_ref', 'remote_ref_string', 'flags', 'old_commit', '_remote', 'summary') NEW_TAG, NEW_HEAD, NO_MATCH, REJECTED, REMOTE_REJECTED, REMOTE_FAILURE, DELETED, \ - FORCED_UPDATE, FAST_FORWARD, UP_TO_DATE, ERROR = [ 1 << x for x in range(11) ] + FORCED_UPDATE, FAST_FORWARD, UP_TO_DATE, ERROR = [1 << x for x in range(11)] - _flag_map = { 'X' : NO_MATCH, '-' : DELETED, '*' : 0, - '+' : FORCED_UPDATE, ' ' : FAST_FORWARD, - '=' : UP_TO_DATE, '!' : ERROR } + _flag_map = {'X': NO_MATCH, '-': DELETED, '*': 0, + '+': FORCED_UPDATE, ' ': FAST_FORWARD, + '=': UP_TO_DATE, '!': ERROR} def __init__(self, flags, local_ref, remote_ref_string, remote, old_commit=None, summary=''): @@ -139,7 +139,7 @@ class PushInfo(object): # control character handling try: - flags |= cls._flag_map[ control_character ] + flags |= cls._flag_map[control_character] except KeyError: raise ValueError("Control Character %r unknown as parsed from line %r" % (control_character, line)) # END handle control character @@ -196,18 +196,18 @@ class FetchInfo(object): info.old_commit # if info.flags & info.FORCED_UPDATE|info.FAST_FORWARD, # field is set to the previous location of ref, otherwise None """ - __slots__ = ('ref','old_commit', 'flags', 'note') + __slots__ = ('ref', 'old_commit', 'flags', 'note') NEW_TAG, NEW_HEAD, HEAD_UPTODATE, TAG_UPDATE, REJECTED, FORCED_UPDATE, \ - FAST_FORWARD, ERROR = [ 1 << x for x in range(8) ] + FAST_FORWARD, ERROR = [1 << x for x in range(8)] # %c %-*s %-*s -> %s (%s) re_fetch_result = re.compile("^\s*(.) (\[?[\w\s\.]+\]?)\s+(.+) -> ([/\w_\+\.-]+)( \(.*\)?$)?") - _flag_map = { '!' : ERROR, '+' : FORCED_UPDATE, '-' : TAG_UPDATE, '*' : 0, - '=' : HEAD_UPTODATE, ' ' : FAST_FORWARD } + _flag_map = {'!': ERROR, '+': FORCED_UPDATE, '-': TAG_UPDATE, '*': 0, + '=': HEAD_UPTODATE, ' ': FAST_FORWARD} - def __init__(self, ref, flags, note = '', old_commit = None): + def __init__(self, ref, flags, note='', old_commit=None): """ Initialize a new instance """ @@ -306,7 +306,7 @@ class FetchInfo(object): remote_local_ref = ref_type(repo, ref_path, check_path=False) # END create ref instance - note = ( note and note.strip() ) or '' + note = (note and note.strip()) or '' # parse flags from control_character flags = 0 @@ -346,7 +346,7 @@ class Remote(LazyMixin, Iterable): NOTE: When querying configuration, the configuration accessor will be cached to speed up subsequent accesses.""" - __slots__ = ( "repo", "name", "_config_reader" ) + __slots__ = ("repo", "name", "_config_reader") _id_attribute_ = "name" def __init__(self, repo, name): @@ -400,7 +400,7 @@ class Remote(LazyMixin, Iterable): return self.name == other.name def __ne__(self, other): - return not ( self == other ) + return not (self == other) def __hash__(self): return hash(self.name) @@ -415,7 +415,7 @@ class Remote(LazyMixin, Iterable): rbound = section.rfind('"') if lbound == -1 or rbound == -1: raise ValueError("Remote-Section has invalid format: %r" % section) - yield Remote(repo, section[lbound+1:rbound]) + yield Remote(repo, section[lbound + 1:rbound]) # END for each configuration section @property @@ -447,7 +447,7 @@ class Remote(LazyMixin, Iterable): token = " * [would prune] " if not line.startswith(token): raise ValueError("Could not parse git-remote prune result: %r" % line) - fqhn = "%s/%s" % (RemoteReference._common_path_default,line.replace(token, "")) + fqhn = "%s/%s" % (RemoteReference._common_path_default, line.replace(token, "")) out_refs.append(RemoteReference(self.repo, fqhn)) # END for each line return out_refs @@ -464,14 +464,14 @@ class Remote(LazyMixin, Iterable): :return: New Remote instance :raise GitCommandError: in case an origin with that name already exists""" - repo.git.remote( "add", name, url, **kwargs ) + repo.git.remote("add", name, url, **kwargs) return cls(repo, name) # add is an alias add = create @classmethod - def remove(cls, repo, name ): + def remove(cls, repo, name): """Remove the remote with the given name""" repo.git.remote("rm", name) @@ -527,7 +527,7 @@ class Remote(LazyMixin, Iterable): # END for each line # read head information - fp = open(join(self.repo.git_dir, 'FETCH_HEAD'),'r') + fp = open(join(self.repo.git_dir, 'FETCH_HEAD'), 'r') fetch_head_info = fp.readlines() fp.close() @@ -537,7 +537,7 @@ class Remote(LazyMixin, Iterable): # assert len(fetch_info_lines) == len(fetch_head_info), "len(%s) != len(%s)" % (fetch_head_info, fetch_info_lines) output.extend(FetchInfo._from_line(self.repo, err_line, fetch_line) - for err_line,fetch_line in zip(fetch_info_lines, fetch_head_info)) + for err_line, fetch_line in zip(fetch_info_lines, fetch_head_info)) finalize_process(proc) return output diff --git a/git/repo/base.py b/git/repo/base.py index f592f9d7..6e9ab5d3 100644 --- a/git/repo/base.py +++ b/git/repo/base.py @@ -67,7 +67,7 @@ class Repo(object): 'git_dir' is the .git repository directory, which is always set.""" DAEMON_EXPORT_FILE = 'git-daemon-export-ok' - __slots__ = ( "working_dir", "_working_tree_dir", "git_dir", "_bare", "git", "odb" ) + __slots__ = ("working_dir", "_working_tree_dir", "git_dir", "_bare", "git", "odb") # precompiled regex re_whitespace = re.compile(r'\s+') @@ -80,7 +80,7 @@ class Repo(object): # represents the configuration level of a configuration file config_level = ("system", "global", "repository") - def __init__(self, path=None, odbt = DefaultDBType): + def __init__(self, path=None, odbt=DefaultDBType): """Create a new Repo instance :param path: is the path to either the root git directory or the bare git repo:: @@ -127,7 +127,7 @@ class Repo(object): self._bare = False try: - self._bare = self.config_reader("repository").getboolean('core','bare') + self._bare = self.config_reader("repository").getboolean('core', 'bare') except Exception: # lets not assume the option exists, although it should pass @@ -168,7 +168,7 @@ class Repo(object): def _set_description(self, descr): filename = join(self.git_dir, 'description') - file(filename, 'w').write(descr+'\n') + file(filename, 'w').write(descr + '\n') description = property(_get_description, _set_description, doc="the project's description") @@ -180,7 +180,7 @@ class Repo(object): """:return: The working tree directory of our git repository :raise AssertionError: If we are a bare repository""" if self._working_tree_dir is None: - raise AssertionError( "Repository at %r is bare and does not have a working tree directory" % self.git_dir ) + raise AssertionError("Repository at %r is bare and does not have a working tree directory" % self.git_dir) return self._working_tree_dir @property @@ -217,7 +217,7 @@ class Repo(object): @property def head(self): """:return: HEAD Object pointing to the current head reference""" - return HEAD(self,'HEAD') + return HEAD(self, 'HEAD') @property def remotes(self): @@ -276,12 +276,12 @@ class Repo(object): :return: ``git.IterableList(TagReference, ...)`` """ return TagReference.list_items(self) - def tag(self,path): + def tag(self, path): """:return: TagReference Object, reference pointing to a Commit or Tag :param path: path to the tag reference, i.e. 0.1.5 or tags/0.1.5 """ return TagReference(self, path) - def create_head(self, path, commit='HEAD', force=False, logmsg=None ): + def create_head(self, path, commit='HEAD', force=False, logmsg=None): """Create a new head within the repository. For more documentation, please see the Head.create method. @@ -318,7 +318,7 @@ class Repo(object): """Delete the given remote.""" return Remote.remove(self, remote) - def _get_config_path(self, config_level ): + def _get_config_path(self, config_level): # we do not support an absolute path of the gitconfig on windows , # use the global config instead if sys.platform == "win32" and config_level == "system": @@ -331,7 +331,7 @@ class Repo(object): elif config_level == "repository": return join(self.git_dir, "config") - raise ValueError( "Invalid configuration level: %r" % config_level ) + raise ValueError("Invalid configuration level: %r" % config_level) def config_reader(self, config_level=None): """ @@ -350,9 +350,9 @@ class Repo(object): unknown, instead the global path will be used.""" files = None if config_level is None: - files = [ self._get_config_path(f) for f in self.config_level ] + files = [self._get_config_path(f) for f in self.config_level] else: - files = [ self._get_config_path(config_level) ] + files = [self._get_config_path(config_level)] return GitConfigParser(files, read_only=True) def config_writer(self, config_level="repository"): @@ -368,7 +368,7 @@ class Repo(object): system = sytem wide configuration file global = user level configuration file repository = configuration file for this repostory only""" - return GitConfigParser(self._get_config_path(config_level), read_only = False) + return GitConfigParser(self._get_config_path(config_level), read_only=False) def commit(self, rev=None): """The Commit object for the specified revision @@ -377,12 +377,12 @@ class Repo(object): if rev is None: return self.head.commit else: - return self.rev_parse(unicode(rev)+"^0") + return self.rev_parse(unicode(rev) + "^0") def iter_trees(self, *args, **kwargs): """:return: Iterator yielding Tree objects :note: Takes all arguments known to iter_commits method""" - return ( c.tree for c in self.iter_commits(*args, **kwargs) ) + return (c.tree for c in self.iter_commits(*args, **kwargs)) def tree(self, rev=None): """The Tree object for the given treeish revision @@ -400,7 +400,7 @@ class Repo(object): if rev is None: return self.head.commit.tree else: - return self.rev_parse(unicode(rev)+"^{tree}") + return self.rev_parse(unicode(rev) + "^{tree}") def iter_commits(self, rev=None, paths='', **kwargs): """A list of Commit objects representing the history of a given ref/commit @@ -614,7 +614,7 @@ class Repo(object): sha = info['id'] c = commits.get(sha) if c is None: - c = Commit( self, hex_to_bin(sha), + c = Commit(self, hex_to_bin(sha), author=Actor._from_string(info['author'] + ' ' + info['author_email']), authored_date=info['author_date'], committer=Actor._from_string(info['committer'] + ' ' + info['committer_email']), @@ -623,9 +623,9 @@ class Repo(object): commits[sha] = c # END if commit objects needs initial creation m = self.re_tab_full_line.search(line) - text, = m.groups() + text, = m.groups() blames[-1][0] = c - blames[-1][1].append( text ) + blames[-1][1].append(text) info = {'id': sha} # END if we collected commit info # END distinguish filename,summary,rest @@ -710,7 +710,7 @@ class Repo(object): # that contains the remote from which we were clones, git stops liking it # as it will escape the backslashes. Hence we undo the escaping just to be # sure - repo = cls(os.path.abspath(path), odbt = odbt) + repo = cls(os.path.abspath(path), odbt=odbt) if repo.remotes: repo.remotes[0].config_writer.set_value('url', repo.remotes[0].url.replace("\\\\", "\\").replace("\\", "/")) # END handle remote repo @@ -742,7 +742,7 @@ class Repo(object): :return: Repo instance pointing to the cloned directory""" return cls._clone(Git(os.getcwd()), url, to_path, GitCmdObjectDB, progress, **kwargs) - def archive(self, ostream, treeish=None, prefix=None, **kwargs): + def archive(self, ostream, treeish=None, prefix=None, **kwargs): """Archive the tree at the given revision. :parm ostream: file compatible stream object to which the archive will be written :parm treeish: is the treeish name/id, defaults to active branch diff --git a/git/repo/fun.py b/git/repo/fun.py index 15c5762b..4cdaf3f4 100644 --- a/git/repo/fun.py +++ b/git/repo/fun.py @@ -182,7 +182,7 @@ def rev_parse(repo, rev): end = rev.find('}', start) if end == -1: raise ValueError("Missing closing brace to define type in %s" % rev) - output_type = rev[start+1:end] # exclude brace + output_type = rev[start + 1:end] # exclude brace # handle type if output_type == 'commit': @@ -206,7 +206,7 @@ def rev_parse(repo, rev): revlog_index = None try: # transform reversed index into the format of our revlog - revlog_index = -(int(output_type)+1) + revlog_index = -(int(output_type) + 1) except ValueError: # TODO: Try to parse the other date options, using parse_date # maybe @@ -232,7 +232,7 @@ def rev_parse(repo, rev): raise ValueError("Could not accomodate requested object type %r, got %s" % (output_type, obj.type)) # END verify ouput type - start = end+1 # skip brace + start = end + 1 # skip brace parsed_to = start continue # END parse type @@ -270,7 +270,7 @@ def rev_parse(repo, rev): obj = to_commit(obj) # must be n'th parent if num: - obj = obj.parents[num-1] + obj = obj.parents[num - 1] elif token == ":": if obj.type != "tree": obj = obj.tree diff --git a/git/test/lib/__init__.py b/git/test/lib/__init__.py index 77512794..e13e227d 100644 --- a/git/test/lib/__init__.py +++ b/git/test/lib/__init__.py @@ -9,5 +9,5 @@ from mock import * from asserts import * from helper import * -__all__ = [ name for name, obj in locals().items() - if not (name.startswith('_') or inspect.ismodule(obj)) ] +__all__ = [name for name, obj in locals().items() + if not (name.startswith('_') or inspect.ismodule(obj))] diff --git a/git/test/lib/helper.py b/git/test/lib/helper.py index d5045ad7..812aecdc 100644 --- a/git/test/lib/helper.py +++ b/git/test/lib/helper.py @@ -188,7 +188,7 @@ def with_rw_and_rw_remote_repo(working_tree_ref): # try to list remotes to diagnoes whether the server is up try: rw_repo.git.ls_remote(d_remote) - except GitCommandError,e: + except GitCommandError, e: print str(e) if os.name == 'nt': raise AssertionError('git-daemon needs to run this test, but windows does not have one. Otherwise, run: git-daemon "%s"' % os.path.dirname(_mktemp())) diff --git a/git/test/performance/test_commit.py b/git/test/performance/test_commit.py index 79555844..adee2567 100644 --- a/git/test/performance/test_commit.py +++ b/git/test/performance/test_commit.py @@ -46,7 +46,7 @@ class TestPerformance(TestBigRepoRW): # END for each object # END for each commit elapsed_time = time() - st - print >> sys.stderr, "Traversed %i Trees and a total of %i unchached objects in %s [s] ( %f objs/s )" % (nc, no, elapsed_time, no/elapsed_time) + print >> sys.stderr, "Traversed %i Trees and a total of %i unchached objects in %s [s] ( %f objs/s )" % (nc, no, elapsed_time, no / elapsed_time) def test_commit_traversal(self): # bound to cat-file parsing performance @@ -57,7 +57,7 @@ class TestPerformance(TestBigRepoRW): self._query_commit_info(c) # END for each traversed commit elapsed_time = time() - st - print >> sys.stderr, "Traversed %i Commits in %s [s] ( %f commits/s )" % (nc, elapsed_time, nc/elapsed_time) + print >> sys.stderr, "Traversed %i Commits in %s [s] ( %f commits/s )" % (nc, elapsed_time, nc / elapsed_time) def test_commit_iteration(self): # bound to stream parsing performance @@ -68,7 +68,7 @@ class TestPerformance(TestBigRepoRW): self._query_commit_info(c) # END for each traversed commit elapsed_time = time() - st - print >> sys.stderr, "Iterated %i Commits in %s [s] ( %f commits/s )" % (nc, elapsed_time, nc/elapsed_time) + print >> sys.stderr, "Iterated %i Commits in %s [s] ( %f commits/s )" % (nc, elapsed_time, nc / elapsed_time) def test_commit_serialization(self): assert_commit_serialization(self.gitrwrepo, self.head_sha_2k, True) @@ -83,7 +83,7 @@ class TestPerformance(TestBigRepoRW): nc = 5000 st = time() for i in xrange(nc): - cm = Commit( rwrepo, Commit.NULL_BIN_SHA, hc.tree, + cm = Commit(rwrepo, Commit.NULL_BIN_SHA, hc.tree, hc.author, hc.authored_date, hc.author_tz_offset, hc.committer, hc.committed_date, hc.committer_tz_offset, str(i), parents=hc.parents, encoding=hc.encoding) diff --git a/git/test/performance/test_odb.py b/git/test/performance/test_odb.py index 57a953ab..5ddbbd53 100644 --- a/git/test/performance/test_odb.py +++ b/git/test/performance/test_odb.py @@ -12,7 +12,7 @@ from lib import ( class TestObjDBPerformance(TestBigRepoR): def test_random_access(self): - results = [ ["Iterate Commits"], ["Iterate Blobs"], ["Retrieve Blob Data"] ] + results = [["Iterate Commits"], ["Iterate Blobs"], ["Retrieve Blob Data"]] for repo in (self.gitrorepo, self.puregitrorepo): # GET COMMITS st = time() @@ -60,7 +60,7 @@ class TestObjDBPerformance(TestBigRepoR): # END for each bloblist elapsed = time() - st - print >> sys.stderr, "%s: Retrieved %i blob (%i KiB) and their data in %g s ( %f blobs / s, %f KiB / s )" % (type(repo.odb), nb, data_bytes/1000, elapsed, nb / elapsed, (data_bytes / 1000) / elapsed) + print >> sys.stderr, "%s: Retrieved %i blob (%i KiB) and their data in %g s ( %f blobs / s, %f KiB / s )" % (type(repo.odb), nb, data_bytes / 1000, elapsed, nb / elapsed, (data_bytes / 1000) / elapsed) results[2].append(elapsed) # END for each repo type diff --git a/git/test/performance/test_streams.py b/git/test/performance/test_streams.py index c8b59da6..32ae98bf 100644 --- a/git/test/performance/test_streams.py +++ b/git/test/performance/test_streams.py @@ -19,8 +19,8 @@ from lib import ( class TestObjDBPerformance(TestBigRepoR): - large_data_size_bytes = 1000*1000*10 # some MiB should do it - moderate_data_size_bytes = 1000*1000*1 # just 1 MiB + large_data_size_bytes = 1000 * 1000 * 10 # some MiB should do it + moderate_data_size_bytes = 1000 * 1000 * 1 # just 1 MiB @with_rw_repo('HEAD', bare=True) def test_large_data_streaming(self, rwrepo): @@ -58,7 +58,7 @@ class TestObjDBPerformance(TestBigRepoR): print >> sys.stderr, "Read %i KiB of %s data at once from loose odb in %f s ( %f Read KiB / s)" % (size_kib, desc, elapsed_readall, size_kib / elapsed_readall) # reading in chunks of 1 MiB - cs = 512*1000 + cs = 512 * 1000 chunks = list() st = time() ostream = ldb.stream(binsha) diff --git a/git/test/performance/test_utils.py b/git/test/performance/test_utils.py index 4979eaa1..19c37a5f 100644 --- a/git/test/performance/test_utils.py +++ b/git/test/performance/test_utils.py @@ -65,7 +65,7 @@ class TestUtilPerformance(TestBigRepoR): def test_instantiation(self): ni = 100000 max_num_items = 4 - for mni in range(max_num_items+1): + for mni in range(max_num_items + 1): for cls in (tuple, list): st = time() for i in xrange(ni): @@ -74,11 +74,11 @@ class TestUtilPerformance(TestBigRepoR): elif mni == 1: cls((1,)) elif mni == 2: - cls((1,2)) + cls((1, 2)) elif mni == 3: - cls((1,2,3)) + cls((1, 2, 3)) elif mni == 4: - cls((1,2,3,4)) + cls((1, 2, 3, 4)) else: cls(x for x in xrange(mni)) # END handle empty cls @@ -91,22 +91,22 @@ class TestUtilPerformance(TestBigRepoR): # tuple and tuple direct st = time() for i in xrange(ni): - t = (1,2,3,4) + t = (1, 2, 3, 4) # END for each item elapsed = time() - st print >> sys.stderr, "Created %i tuples (1,2,3,4) in %f s ( %f tuples / s)" % (ni, elapsed, ni / elapsed) st = time() for i in xrange(ni): - t = tuple((1,2,3,4)) + t = tuple((1, 2, 3, 4)) # END for each item elapsed = time() - st print >> sys.stderr, "Created %i tuples tuple((1,2,3,4)) in %f s ( %f tuples / s)" % (ni, elapsed, ni / elapsed) def test_unpacking_vs_indexing(self): ni = 1000000 - list_items = [1,2,3,4] - tuple_items = (1,2,3,4) + list_items = [1, 2, 3, 4] + tuple_items = (1, 2, 3, 4) for sequence in (list_items, tuple_items): st = time() diff --git a/git/test/test_actor.py b/git/test/test_actor.py index 40e307ba..5ccf1d2e 100644 --- a/git/test/test_actor.py +++ b/git/test/test_actor.py @@ -18,7 +18,7 @@ class TestActor(object): # base type capabilities assert a == a - assert not ( a != a ) + assert not (a != a) m = set() m.add(a) m.add(a) diff --git a/git/test/test_base.py b/git/test/test_base.py index 42b95b39..211c7479 100644 --- a/git/test/test_base.py +++ b/git/test/test_base.py @@ -18,10 +18,10 @@ import tempfile class TestBase(TestBase): - type_tuples = ( ("blob", "8741fc1d09d61f02ffd8cded15ff603eff1ec070", "blob.py"), + type_tuples = (("blob", "8741fc1d09d61f02ffd8cded15ff603eff1ec070", "blob.py"), ("tree", "3a6a5e3eeed3723c09f1ef0399f81ed6b8d82e79", "directory"), ("commit", "4251bd59fb8e11e40c40548cba38180a9536118c", None), - ("tag", "e56a60e8e9cd333cfba0140a77cd12b0d9398f10", None) ) + ("tag", "e56a60e8e9cd333cfba0140a77cd12b0d9398f10", None)) def test_base_object(self): # test interface of base object classes @@ -35,9 +35,9 @@ class TestBase(TestBase): binsha = hex_to_bin(hexsha) item = None if path is None: - item = obj_type(self.rorepo,binsha) + item = obj_type(self.rorepo, binsha) else: - item = obj_type(self.rorepo,binsha, 0, path) + item = obj_type(self.rorepo, binsha, 0, path) # END handle index objects num_objs += 1 assert item.hexsha == hexsha @@ -51,7 +51,7 @@ class TestBase(TestBase): if isinstance(item, base.IndexObject): num_index_objs += 1 - if hasattr(item,'path'): # never runs here + if hasattr(item, 'path'): # never runs here assert not item.path.startswith("/") # must be relative assert isinstance(item.mode, int) # END index object check @@ -70,7 +70,7 @@ class TestBase(TestBase): # each has a unique sha assert len(s) == num_objs - assert len(s|s) == num_objs + assert len(s | s) == num_objs assert num_index_objs == 2 def test_get_object_type_by_name(self): @@ -78,7 +78,7 @@ class TestBase(TestBase): assert base.Object in get_object_type_by_name(tname).mro() # END for each known type - assert_raises( ValueError, get_object_type_by_name, "doesntexist" ) + assert_raises(ValueError, get_object_type_by_name, "doesntexist") def test_object_resolution(self): # objects must be resolved to shas so they compare equal @@ -87,15 +87,15 @@ class TestBase(TestBase): @with_rw_repo('HEAD', bare=True) def test_with_bare_rw_repo(self, bare_rw_repo): assert bare_rw_repo.config_reader("repository").getboolean("core", "bare") - assert os.path.isfile(os.path.join(bare_rw_repo.git_dir,'HEAD')) + assert os.path.isfile(os.path.join(bare_rw_repo.git_dir, 'HEAD')) @with_rw_repo('0.1.6') def test_with_rw_repo(self, rw_repo): assert not rw_repo.config_reader("repository").getboolean("core", "bare") - assert os.path.isdir(os.path.join(rw_repo.working_tree_dir,'lib')) + assert os.path.isdir(os.path.join(rw_repo.working_tree_dir, 'lib')) @with_rw_and_rw_remote_repo('0.1.6') def test_with_rw_remote_and_rw_repo(self, rw_repo, rw_remote_repo): assert not rw_repo.config_reader("repository").getboolean("core", "bare") assert rw_remote_repo.config_reader("repository").getboolean("core", "bare") - assert os.path.isdir(os.path.join(rw_repo.working_tree_dir,'lib')) + assert os.path.isdir(os.path.join(rw_repo.working_tree_dir, 'lib')) diff --git a/git/test/test_blob.py b/git/test/test_blob.py index a1d95ac2..ddd2893f 100644 --- a/git/test/test_blob.py +++ b/git/test/test_blob.py @@ -16,7 +16,7 @@ class TestBlob(TestBase): assert_equal("image/png", blob.mime_type) def test_mime_type_should_return_text_plain_for_unknown_types(self): - blob = Blob(self.rorepo, **{'binsha': Blob.NULL_BIN_SHA,'path': 'something'}) + blob = Blob(self.rorepo, **{'binsha': Blob.NULL_BIN_SHA, 'path': 'something'}) assert_equal("text/plain", blob.mime_type) def test_nodict(self): diff --git a/git/test/test_commit.py b/git/test/test_commit.py index d6e13762..7bb019f4 100644 --- a/git/test/test_commit.py +++ b/git/test/test_commit.py @@ -62,7 +62,7 @@ def assert_commit_serialization(rwrepo, commit_id, print_performance_info=False) elapsed = time.time() - st if print_performance_info: - print >> sys.stderr, "Serialized %i and deserialized %i commits in %f s ( (%f, %f) commits / s" % (ns, nds, elapsed, ns/elapsed, nds/elapsed) + print >> sys.stderr, "Serialized %i and deserialized %i commits in %f s ( (%f, %f) commits / s" % (ns, nds, elapsed, ns / elapsed, nds / elapsed) # END handle performance info @@ -151,10 +151,10 @@ class TestCommit(TestBase): assert len(list(start.traverse(ignore_self=False, depth=0))) == 1 # prune - assert start.traverse(branch_first=1, prune=lambda i,d: i == p0).next() == p1 + assert start.traverse(branch_first=1, prune=lambda i, d: i == p0).next() == p1 # predicate - assert start.traverse(branch_first=1, predicate=lambda i,d: i == p1).next() == p1 + assert start.traverse(branch_first=1, predicate=lambda i, d: i == p1).next() == p1 # traversal should stop when the beginning is reached self.failUnlessRaises(StopIteration, first.traverse().next) @@ -205,7 +205,7 @@ class TestCommit(TestBase): assert_equal(sha1, commit.hexsha) def test_count(self): - assert self.rorepo.tag('refs/tags/0.1.5').commit.count( ) == 143 + assert self.rorepo.tag('refs/tags/0.1.5').commit.count() == 143 def test_list(self): assert isinstance(Commit.list_items(self.rorepo, '0.1.5', max_count=5)[hex_to_bin('5117c9c8a4d3af19a9958677e45cda9269de1541')], Commit) @@ -221,7 +221,7 @@ class TestCommit(TestBase): def test_equality(self): commit1 = Commit(self.rorepo, Commit.NULL_BIN_SHA) commit2 = Commit(self.rorepo, Commit.NULL_BIN_SHA) - commit3 = Commit(self.rorepo, "\1"*20) + commit3 = Commit(self.rorepo, "\1" * 20) assert_equal(commit1, commit2) assert_not_equal(commit2, commit3) diff --git a/git/test/test_config.py b/git/test/test_config.py index cd1c43ed..de4727e0 100644 --- a/git/test/test_config.py +++ b/git/test/test_config.py @@ -27,7 +27,7 @@ class TestBase(TestCase): for filename in ("git_config", "git_config_global"): file_obj = self._to_memcache(fixture_path(filename)) file_obj_orig = copy(file_obj) - w_config = GitConfigParser(file_obj, read_only = False) + w_config = GitConfigParser(file_obj, read_only=False) w_config.read() # enforce reading assert w_config._sections w_config.write() # enforce writing @@ -36,7 +36,7 @@ class TestBase(TestCase): assert file_obj.getvalue() != file_obj_orig.getvalue() # creating an additional config writer must fail due to exclusive access - self.failUnlessRaises(IOError, GitConfigParser, file_obj, read_only = False) + self.failUnlessRaises(IOError, GitConfigParser, file_obj, read_only=False) # should still have a lock and be able to make changes assert w_config._lock._has_lock() @@ -48,7 +48,7 @@ class TestBase(TestCase): w_config.add_section(sname) assert w_config.has_section(sname) w_config.set(sname, oname, val) - assert w_config.has_option(sname,oname) + assert w_config.has_option(sname, oname) assert w_config.get(sname, oname) == val sname_new = "new_section" @@ -88,7 +88,7 @@ class TestBase(TestCase): # writing must fail self.failUnlessRaises(IOError, r_config.set, section, option, None) - self.failUnlessRaises(IOError, r_config.remove_option, section, option ) + self.failUnlessRaises(IOError, r_config.remove_option, section, option) # END for each option self.failUnlessRaises(IOError, r_config.remove_section, section) # END for each section diff --git a/git/test/test_diff.py b/git/test/test_diff.py index 3c2537da..aacd9368 100644 --- a/git/test/test_diff.py +++ b/git/test/test_diff.py @@ -50,7 +50,7 @@ class TestDiff(TestBase): # be able to deal with it fixtures = ("diff_2", "diff_2f", "diff_f", "diff_i", "diff_mode_only", "diff_new_mode", "diff_numstat", "diff_p", "diff_rename", - "diff_tree_numstat_root" ) + "diff_tree_numstat_root") for fixture_name in fixtures: diff_proc = StringProcessAdapter(fixture(fixture_name)) @@ -62,7 +62,7 @@ class TestDiff(TestBase): assertion_map = dict() for i, commit in enumerate(self.rorepo.iter_commits('0.1.6', max_count=2)): diff_item = commit - if i%2 == 0: + if i % 2 == 0: diff_item = commit.tree # END use tree every second item @@ -75,9 +75,9 @@ class TestDiff(TestBase): if diff_index: self._assert_diff_format(diff_index) for ct in DiffIndex.change_type: - key = 'ct_%s'%ct + key = 'ct_%s' % ct assertion_map.setdefault(key, 0) - assertion_map[key] = assertion_map[key]+len(list(diff_index.iter_change_type(ct))) + assertion_map[key] = assertion_map[key] + len(list(diff_index.iter_change_type(ct))) # END for each changetype # check entries @@ -96,7 +96,7 @@ class TestDiff(TestBase): # assert we could always find at least one instance of the members we # can iterate in the diff index - if not this indicates its not working correctly # or our test does not span the whole range of possibilities - for key,value in assertion_map.items(): + for key, value in assertion_map.items(): assert value, "Did not find diff for %s" % key # END for each iteration type diff --git a/git/test/test_fun.py b/git/test/test_fun.py index f435f31b..9d6f3ea4 100644 --- a/git/test/test_fun.py +++ b/git/test/test_fun.py @@ -65,7 +65,7 @@ class TestFun(TestBase): self._assert_index_entries(aggressive_tree_merge(odb, trees), trees) # too many trees - self.failUnlessRaises(ValueError, aggressive_tree_merge, odb, trees*2) + self.failUnlessRaises(ValueError, aggressive_tree_merge, odb, trees * 2) def mktree(self, odb, entries): """create a tree from the given tree entries and safe it to the database""" @@ -78,7 +78,7 @@ class TestFun(TestBase): @with_rw_repo('0.1.6') def test_three_way_merge(self, rwrepo): def mkfile(name, sha, executable=0): - return (sha, S_IFREG | 0644 | executable*0111, name) + return (sha, S_IFREG | 0644 | executable * 0111, name) def mkcommit(name, sha): return (sha, S_IFDIR | S_IFLNK, name) @@ -88,9 +88,9 @@ class TestFun(TestBase): assert has_conflict == (len([e for e in entries if e.stage != 0]) > 0) mktree = self.mktree - shaa = "\1"*20 - shab = "\2"*20 - shac = "\3"*20 + shaa = "\1" * 20 + shab = "\2" * 20 + shac = "\3" * 20 odb = rwrepo.odb diff --git a/git/test/test_git.py b/git/test/test_git.py index 06410c45..e8a4c6b3 100644 --- a/git/test/test_git.py +++ b/git/test/test_git.py @@ -5,15 +5,15 @@ # the BSD License: http://www.opensource.org/licenses/bsd-license.php import os -from git.test.lib import ( TestBase, +from git.test.lib import (TestBase, patch, raises, assert_equal, assert_true, assert_match, - fixture_path ) -from git import ( Git, - GitCommandError ) + fixture_path) +from git import (Git, + GitCommandError) class TestGit(TestBase): @@ -52,7 +52,7 @@ class TestGit(TestBase): assert_equal(["-s", "-t"], self.git.transform_kwargs(**{'s': True, 't': True})) def test_it_executes_git_to_shell_and_returns_result(self): - assert_match('^git version [\d\.]{2}.*$', self.git.execute(["git","version"])) + assert_match('^git version [\d\.]{2}.*$', self.git.execute(["git", "version"])) def test_it_accepts_stdin(self): filename = fixture_path("cat_file_blob") @@ -71,13 +71,13 @@ class TestGit(TestBase): # read header only import subprocess as sp hexsha = "b2339455342180c7cc1e9bba3e9f181f7baa5167" - g = self.git.cat_file(batch_check=True, istream=sp.PIPE,as_process=True) + g = self.git.cat_file(batch_check=True, istream=sp.PIPE, as_process=True) g.stdin.write("b2339455342180c7cc1e9bba3e9f181f7baa5167\n") g.stdin.flush() obj_info = g.stdout.readline() # read header + data - g = self.git.cat_file(batch=True, istream=sp.PIPE,as_process=True) + g = self.git.cat_file(batch=True, istream=sp.PIPE, as_process=True) g.stdin.write("b2339455342180c7cc1e9bba3e9f181f7baa5167\n") g.stdin.flush() obj_info_two = g.stdout.readline() diff --git a/git/test/test_index.py b/git/test/test_index.py index b902f4d5..f5c92099 100644 --- a/git/test/test_index.py +++ b/git/test/test_index.py @@ -63,8 +63,8 @@ class TestIndex(TestBase): # test entry last_val = None entry = index.entries.itervalues().next() - for attr in ("path","ctime","mtime","dev","inode","mode","uid", - "gid","size","binsha", "hexsha", "stage"): + for attr in ("path", "ctime", "mtime", "dev", "inode", "mode", "uid", + "gid", "size", "binsha", "hexsha", "stage"): val = getattr(entry, attr) # END for each method @@ -76,7 +76,7 @@ class TestIndex(TestBase): # test stage index_merge = IndexFile(self.rorepo, fixture_path("index_merge")) assert len(index_merge.entries) == 106 - assert len(list(e for e in index_merge.entries.itervalues() if e.stage != 0 )) + assert len(list(e for e in index_merge.entries.itervalues() if e.stage != 0)) # write the data - it must match the original tmpfile = tempfile.mktemp() @@ -93,14 +93,14 @@ class TestIndex(TestBase): num_blobs = 0 blist = list() - for blob in tree.traverse(predicate = lambda e,d: e.type == "blob", branch_first=False): - assert (blob.path,0) in index.entries + for blob in tree.traverse(predicate=lambda e, d: e.type == "blob", branch_first=False): + assert (blob.path, 0) in index.entries blist.append(blob) # END for each blob in tree if len(blist) != len(index.entries): iset = set(k[0] for k in index.entries.keys()) bset = set(b.path for b in blist) - raise AssertionError( "CMP Failed: Missing entries in index: %s, missing in tree: %s" % (bset-iset, iset-bset) ) + raise AssertionError("CMP Failed: Missing entries in index: %s, missing in tree: %s" % (bset - iset, iset - bset)) # END assertion message @with_rw_repo('0.1.6') @@ -127,7 +127,7 @@ class TestIndex(TestBase): merge_required = lambda t: t[0] != 0 merge_blobs = list(three_way_index.iter_blobs(merge_required)) assert merge_blobs - assert merge_blobs[0][0] in (1,2,3) + assert merge_blobs[0][0] in (1, 2, 3) assert isinstance(merge_blobs[0][1], Blob) # test BlobFilter @@ -143,12 +143,12 @@ class TestIndex(TestBase): assert unmerged_blob_map # pick the first blob at the first stage we find and use it as resolved version - three_way_index.resolve_blobs( l[0][1] for l in unmerged_blob_map.itervalues() ) + three_way_index.resolve_blobs(l[0][1] for l in unmerged_blob_map.itervalues()) tree = three_way_index.write_tree() assert isinstance(tree, Tree) num_blobs = 0 - for blob in tree.traverse(predicate=lambda item,d: item.type == "blob"): - assert (blob.path,0) in three_way_index.entries + for blob in tree.traverse(predicate=lambda item, d: item.type == "blob"): + assert (blob.path, 0) in three_way_index.entries num_blobs += 1 # END for each blob assert num_blobs == len(three_way_index.entries) @@ -177,7 +177,7 @@ class TestIndex(TestBase): # Add a change with a NULL sha that should conflict with next_commit. We # pretend there was a change, but we do not even bother adding a proper # sha for it ( which makes things faster of course ) - manifest_fake_entry = BaseIndexEntry((manifest_entry[0], "\0"*20, 0, manifest_entry[3])) + manifest_fake_entry = BaseIndexEntry((manifest_entry[0], "\0" * 20, 0, manifest_entry[3])) # try write flag self._assert_entries(rw_repo.index.add([manifest_fake_entry], write=False)) # add actually resolves the null-hex-sha for us as a feature, but we can @@ -278,7 +278,7 @@ class TestIndex(TestBase): assert not index.diff(None) assert cur_branch == rw_repo.active_branch assert cur_commit == rw_repo.head.commit - fp = open(file_path,'rb') + fp = open(file_path, 'rb') try: assert fp.read() != new_data finally: @@ -397,7 +397,7 @@ class TestIndex(TestBase): self.failUnlessRaises(TypeError, index.remove, [1]) # absolute path - deleted_files = index.remove([os.path.join(rw_repo.working_tree_dir,"lib")], r=True) + deleted_files = index.remove([os.path.join(rw_repo.working_tree_dir, "lib")], r=True) assert len(deleted_files) > 1 self.failUnlessRaises(ValueError, index.remove, ["/doesnt/exists"]) @@ -426,7 +426,7 @@ class TestIndex(TestBase): # same index, multiple parents commit_message = "Index with multiple parents\n commit with another line" - commit_multi_parent = index.commit(commit_message,parent_commits=(commit_no_parents, new_commit)) + commit_multi_parent = index.commit(commit_message, parent_commits=(commit_no_parents, new_commit)) assert commit_multi_parent.message == commit_message assert len(commit_multi_parent.parents) == 2 assert commit_multi_parent.parents[0] == commit_no_parents @@ -453,7 +453,7 @@ class TestIndex(TestBase): assert len(entries) == 14 # same file - entries = index.reset(new_commit).add([os.path.abspath(os.path.join('lib', 'git', 'head.py'))]*2, fprogress=self._fprogress_add) + entries = index.reset(new_commit).add([os.path.abspath(os.path.join('lib', 'git', 'head.py'))] * 2, fprogress=self._fprogress_add) self._assert_entries(entries) assert entries[0].mode & 0644 == 0644 # would fail, test is too primitive to handle this case @@ -469,12 +469,12 @@ class TestIndex(TestBase): entries = index.reset(new_commit).add([old_blob], fprogress=self._fprogress_add) self._assert_entries(entries) self._assert_fprogress(entries) - assert index.entries[(old_blob.path,0)].hexsha == old_blob.hexsha and len(entries) == 1 + assert index.entries[(old_blob.path, 0)].hexsha == old_blob.hexsha and len(entries) == 1 # mode 0 not allowed null_hex_sha = Diff.NULL_HEX_SHA null_bin_sha = "\0" * 20 - self.failUnlessRaises(ValueError, index.reset(new_commit).add, [BaseIndexEntry((0, null_bin_sha,0,"doesntmatter"))]) + self.failUnlessRaises(ValueError, index.reset(new_commit).add, [BaseIndexEntry((0, null_bin_sha, 0, "doesntmatter"))]) # add new file new_file_relapath = "my_new_file" @@ -537,7 +537,7 @@ class TestIndex(TestBase): if os.name == 'nt': # simlinks should contain the link as text ( which is what a # symlink actually is ) - open(fake_symlink_path,'rb').read() == link_target + open(fake_symlink_path, 'rb').read() == link_target else: assert S_ISLNK(os.lstat(fake_symlink_path)[ST_MODE]) @@ -657,7 +657,7 @@ class TestIndex(TestBase): H = self.rorepo.tree("25dca42bac17d511b7e2ebdd9d1d679e7626db5f") M = self.rorepo.tree("e746f96bcc29238b79118123028ca170adc4ff0f") - for args in ((B,), (B,H), (B,H,M)): + for args in ((B,), (B, H), (B, H, M)): index = IndexFile.new(self.rorepo, *args) assert isinstance(index, IndexFile) # END for each arg tuple diff --git a/git/test/test_reflog.py b/git/test/test_reflog.py index 76cfd870..a68b25a3 100644 --- a/git/test/test_reflog.py +++ b/git/test/test_reflog.py @@ -52,14 +52,14 @@ class TestRefLog(TestBase): # TODO: Try multiple corrupted ones ! pp = 'reflog_invalid_' for suffix in ('oldsha', 'newsha', 'email', 'date', 'sep'): - self.failUnlessRaises(ValueError, RefLog.from_file, fixture_path(pp+suffix)) + self.failUnlessRaises(ValueError, RefLog.from_file, fixture_path(pp + suffix)) #END for each invalid file # cannot write an uninitialized reflog self.failUnlessRaises(ValueError, RefLog().write) # test serialize and deserialize - results must match exactly - binsha = chr(255)*20 + binsha = chr(255) * 20 msg = "my reflog message" cr = self.rorepo.config_reader() for rlp in (rlp_head, rlp_master): @@ -78,7 +78,7 @@ class TestRefLog(TestBase): # append an entry entry = RefLog.append_entry(cr, tfile, IndexObject.NULL_BIN_SHA, binsha, msg) assert entry.oldhexsha == IndexObject.NULL_HEX_SHA - assert entry.newhexsha == 'f'*40 + assert entry.newhexsha == 'f' * 40 assert entry.message == msg assert RefLog.from_file(tfile)[-1] == entry diff --git a/git/test/test_refs.py b/git/test/test_refs.py index fc58dafa..5658181d 100644 --- a/git/test/test_refs.py +++ b/git/test/test_refs.py @@ -18,7 +18,7 @@ class TestRefs(TestBase): def test_from_path(self): # should be able to create any reference directly - for ref_type in ( Reference, Head, TagReference, RemoteReference ): + for ref_type in (Reference, Head, TagReference, RemoteReference): for name in ('rela_name', 'path/rela_name'): full_path = ref_type.to_full_path(name) instance = ref_type.from_path(self.rorepo, full_path) @@ -36,17 +36,17 @@ class TestRefs(TestBase): for tag in self.rorepo.tags: assert "refs/tags" in tag.path assert tag.name - assert isinstance( tag.commit, Commit ) + assert isinstance(tag.commit, Commit) if tag.tag is not None: - tag_object_refs.append( tag ) + tag_object_refs.append(tag) tagobj = tag.tag # have no dict self.failUnlessRaises(AttributeError, setattr, tagobj, 'someattr', 1) - assert isinstance( tagobj, TagObject ) + assert isinstance(tagobj, TagObject) assert tagobj.tag == tag.name - assert isinstance( tagobj.tagger, Actor ) - assert isinstance( tagobj.tagged_date, int ) - assert isinstance( tagobj.tagger_tz_offset, int ) + assert isinstance(tagobj.tagger, Actor) + assert isinstance(tagobj.tagged_date, int) + assert isinstance(tagobj.tagger_tz_offset, int) assert tagobj.message assert tag.object == tagobj # can't assign the object @@ -59,7 +59,7 @@ class TestRefs(TestBase): def test_tags_author(self): tag = self.rorepo.tags[0] tagobj = tag.tag - assert isinstance( tagobj.tagger, Actor ) + assert isinstance(tagobj.tagger, Actor) tagger_name = tagobj.tagger.name assert tagger_name == 'Michael Trier' @@ -77,7 +77,7 @@ class TestRefs(TestBase): s.add(ref) # END for each ref assert len(s) == ref_count - assert len(s|s) == ref_count + assert len(s | s) == ref_count @with_rw_repo('HEAD', bare=False) def test_heads(self, rwrepo): @@ -127,19 +127,19 @@ class TestRefs(TestBase): # head changes once again, cur_head doesn't change head.set_reference(cur_head, 'reattach head') - assert len(head.log()) == hlog_len+2 + assert len(head.log()) == hlog_len + 2 assert len(cur_head.log()) == blog_len # adjusting the head-ref also adjust the head, so both reflogs are # altered cur_head.set_commit(pcommit, 'changing commit') - assert len(cur_head.log()) == blog_len+1 - assert len(head.log()) == hlog_len+3 + assert len(cur_head.log()) == blog_len + 1 + assert len(head.log()) == hlog_len + 3 # with automatic dereferencing assert head.set_commit(cur_commit, 'change commit once again') is head - assert len(head.log()) == hlog_len+4 - assert len(cur_head.log()) == blog_len+2 + assert len(head.log()) == hlog_len + 4 + assert len(cur_head.log()) == blog_len + 2 # a new branch has just a single entry other_head = Head.create(rwrepo, 'mynewhead', pcommit, logmsg='new head created') @@ -178,10 +178,10 @@ class TestRefs(TestBase): # paths - make sure we have something to do rw_repo.index.reset(old_head_commit.parents[0]) - cur_head.reset(cur_head, paths = "test") - cur_head.reset(new_head_commit, paths = "lib") + cur_head.reset(cur_head, paths="test") + cur_head.reset(new_head_commit, paths="lib") # hard resets with paths don't work, its all or nothing - self.failUnlessRaises(GitCommandError, cur_head.reset, new_head_commit, working_tree=True, paths = "lib") + self.failUnlessRaises(GitCommandError, cur_head.reset, new_head_commit, working_tree=True, paths="lib") # we can do a mixed reset, and then checkout from the index though cur_head.reset(new_head_commit) @@ -224,7 +224,7 @@ class TestRefs(TestBase): commit = 'HEAD' prev_head_commit = cur_head.commit for count, new_name in enumerate(("my_new_head", "feature/feature1")): - actual_commit = commit+"^"*count + actual_commit = commit + "^" * count new_head = Head.create(rw_repo, new_name, actual_commit) assert new_head.is_detached assert cur_head.commit == prev_head_commit @@ -265,7 +265,7 @@ class TestRefs(TestBase): tag_name = "1.0.2" light_tag = TagReference.create(rw_repo, tag_name) self.failUnlessRaises(GitCommandError, TagReference.create, rw_repo, tag_name) - light_tag = TagReference.create(rw_repo, tag_name, "HEAD~1", force = True) + light_tag = TagReference.create(rw_repo, tag_name, "HEAD~1", force=True) assert isinstance(light_tag, TagReference) assert light_tag.name == tag_name assert light_tag.commit == cur_head.commit.parents[0] @@ -362,11 +362,11 @@ class TestRefs(TestBase): # checkout with force as we have a changed a file # clear file - open(new_head.commit.tree.blobs[-1].abspath,'w').close() + open(new_head.commit.tree.blobs[-1].abspath, 'w').close() assert len(new_head.commit.diff(None)) # create a new branch that is likely to touch the file we changed - far_away_head = rw_repo.create_head("far_head",'HEAD~100') + far_away_head = rw_repo.create_head("far_head", 'HEAD~100') self.failUnlessRaises(GitCommandError, far_away_head.checkout) assert active_branch == active_branch.checkout(force=True) assert rw_repo.head.reference != far_away_head @@ -441,7 +441,7 @@ class TestRefs(TestBase): assert os.path.isfile(symbol_ref_abspath) assert symref.commit == new_head.commit - for name in ('absname','folder/rela_name'): + for name in ('absname', 'folder/rela_name'): symref_new_name = symref.rename(name) assert isinstance(symref_new_name, SymbolicReference) assert name in symref_new_name.path diff --git a/git/test/test_remote.py b/git/test/test_remote.py index 19d029e5..638349ba 100644 --- a/git/test/test_remote.py +++ b/git/test/test_remote.py @@ -17,7 +17,7 @@ random.seed(0) class TestRemoteProgress(RemoteProgress): - __slots__ = ( "_seen_lines", "_stages_per_op", '_num_progress_messages' ) + __slots__ = ("_seen_lines", "_stages_per_op", '_num_progress_messages') def __init__(self): super(TestRemoteProgress, self).__init__() @@ -45,9 +45,9 @@ class TestRemoteProgress(RemoteProgress): assert op_id in (self.COUNTING, self.COMPRESSING, self.WRITING) self._stages_per_op.setdefault(op_id, 0) - self._stages_per_op[ op_id ] = self._stages_per_op[ op_id ] | (op_code & self.STAGE_MASK) + self._stages_per_op[op_id] = self._stages_per_op[op_id] | (op_code & self.STAGE_MASK) - if op_code & (self.WRITING|self.END) == (self.WRITING|self.END): + if op_code & (self.WRITING | self.END) == (self.WRITING | self.END): assert message # END check we get message @@ -59,7 +59,7 @@ class TestRemoteProgress(RemoteProgress): return # sometimes objects are not compressed which is okay - assert len(self._seen_ops) in (2,3) + assert len(self._seen_ops) in (2, 3) assert self._stages_per_op # must have seen all stages @@ -86,7 +86,7 @@ class TestRemote(TestBase): assert info.flags != 0 # END reference type flags handling assert isinstance(info.ref, (SymbolicReference, Reference)) - if info.flags & (info.FORCED_UPDATE|info.FAST_FORWARD): + if info.flags & (info.FORCED_UPDATE | info.FAST_FORWARD): assert isinstance(info.old_commit, Commit) else: assert info.old_commit is None @@ -124,12 +124,12 @@ class TestRemote(TestBase): #Create a file with a random name and random data and commit it to repo. # Return the commited absolute file path index = repo.index - new_file = self._make_file(os.path.basename(tempfile.mktemp()),str(random.random()), repo) + new_file = self._make_file(os.path.basename(tempfile.mktemp()), str(random.random()), repo) index.add([new_file]) index.commit("Committing %s" % new_file) return new_file - def _do_test_fetch(self,remote, rw_repo, remote_repo): + def _do_test_fetch(self, remote, rw_repo, remote_repo): # specialized fetch testing to de-clutter the main test self._do_test_fetch_info(rw_repo) @@ -143,7 +143,7 @@ class TestRemote(TestBase): # END fetch and check def get_info(res, remote, name): - return res["%s/%s"%(remote,name)] + return res["%s/%s" % (remote, name)] # put remote head to master as it is garantueed to exist remote_repo.head.reference = remote_repo.heads.master @@ -159,7 +159,7 @@ class TestRemote(TestBase): remote_commit = rhead.commit rhead.reset("HEAD~2", index=False) res = fetch_and_test(remote) - mkey = "%s/%s"%(remote,'master') + mkey = "%s/%s" % (remote, 'master') master_info = res[mkey] assert master_info.flags & FetchInfo.FORCED_UPDATE and master_info.note is not None @@ -192,7 +192,7 @@ class TestRemote(TestBase): RemoteReference.delete(rw_repo, *stale_refs) # test single branch fetch with refspec including target remote - res = fetch_and_test(remote, refspec="master:refs/remotes/%s/master"%remote) + res = fetch_and_test(remote, refspec="master:refs/remotes/%s/master" % remote) assert len(res) == 1 and get_info(res, remote, 'master') # ... with respec and no target @@ -230,7 +230,7 @@ class TestRemote(TestBase): # must clone with a local path for the repo implementation not to freak out # as it wants local paths only ( which I can understand ) other_repo = remote_repo.clone(other_repo_dir, shared=False) - remote_repo_url = "git://localhost%s"%remote_repo.git_dir + remote_repo_url = "git://localhost%s" % remote_repo.git_dir # put origin to git-url other_origin = other_repo.remotes.origin @@ -254,7 +254,7 @@ class TestRemote(TestBase): shutil.rmtree(other_repo_dir) # END test and cleanup - def _assert_push_and_pull(self,remote, rw_repo, remote_repo): + def _assert_push_and_pull(self, remote, rw_repo, remote_repo): # push our changes lhead = rw_repo.head lindex = rw_repo.index @@ -429,7 +429,7 @@ class TestRemote(TestBase): def test_creation_and_removal(self, bare_rw_repo): new_name = "test_new_one" arg_list = (new_name, "git@server:hello.git") - remote = Remote.create(bare_rw_repo, *arg_list ) + remote = Remote.create(bare_rw_repo, *arg_list) assert remote.name == "test_new_one" assert remote in bare_rw_repo.remotes diff --git a/git/test/test_repo.py b/git/test/test_repo.py index 38c03b7a..86d355e6 100644 --- a/git/test/test_repo.py +++ b/git/test/test_repo.py @@ -52,7 +52,7 @@ class TestRepo(TestBase): def test_heads_should_populate_head_data(self): for head in self.rorepo.heads: assert head.name - assert isinstance(head.commit,Commit) + assert isinstance(head.commit, Commit) # END for each head assert isinstance(self.rorepo.heads.master, Head) @@ -84,11 +84,11 @@ class TestRepo(TestBase): assert_equal("Michael Trier", c.author.name) assert_equal("mtrier@gmail.com", c.author.email) assert_equal(1232829715, c.authored_date) - assert_equal(5*3600, c.author_tz_offset) + assert_equal(5 * 3600, c.author_tz_offset) assert_equal("Michael Trier", c.committer.name) assert_equal("mtrier@gmail.com", c.committer.email) assert_equal(1232829715, c.committed_date) - assert_equal(5*3600, c.committer_tz_offset) + assert_equal(5 * 3600, c.committer_tz_offset) assert_equal("Bumped version 0.1.6\n", c.message) c = commits[1] @@ -194,7 +194,7 @@ class TestRepo(TestBase): def test_daemon_export(self): orig_val = self.rorepo.daemon_export self.rorepo.daemon_export = not orig_val - assert self.rorepo.daemon_export == ( not orig_val ) + assert self.rorepo.daemon_export == (not orig_val) self.rorepo.daemon_export = orig_val assert self.rorepo.daemon_export == orig_val @@ -203,7 +203,7 @@ class TestRepo(TestBase): # empty alternates self.rorepo.alternates = [] assert self.rorepo.alternates == [] - alts = [ "other/location", "this/location" ] + alts = ["other/location", "this/location"] self.rorepo.alternates = alts assert alts == self.rorepo.alternates self.rorepo.alternates = cur_alternates @@ -220,9 +220,9 @@ class TestRepo(TestBase): def test_is_dirty(self): self.rorepo._bare = False - for index in (0,1): - for working_tree in (0,1): - for untracked_files in (0,1): + for index in (0, 1): + for working_tree in (0, 1): + for untracked_files in (0, 1): assert self.rorepo.is_dirty(index, working_tree, untracked_files) in (True, False) # END untracked files # END working tree @@ -250,9 +250,9 @@ class TestRepo(TestBase): @patch.object(Git, '_call_process') def test_should_display_blame_information(self, git): git.return_value = fixture('blame') - b = self.rorepo.blame( 'master', 'lib/git.py') + b = self.rorepo.blame('master', 'lib/git.py') assert_equal(13, len(b)) - assert_equal( 2, len(b[0]) ) + assert_equal(2, len(b[0])) # assert_equal(25, reduce(lambda acc, x: acc + len(x[-1]), b)) assert_equal(hash(b[0][0]), hash(b[9][0])) c = b[0][0] @@ -270,9 +270,9 @@ class TestRepo(TestBase): # test the 'lines per commit' entries tlist = b[0][1] - assert_true( tlist ) - assert_true( isinstance( tlist[0], basestring ) ) - assert_true( len( tlist ) < sum( len(t) for t in tlist ) ) # test for single-char bug + assert_true(tlist) + assert_true(isinstance(tlist[0], basestring)) + assert_true(len(tlist) < sum(len(t) for t in tlist)) # test for single-char bug def test_blame_real(self): c = 0 @@ -285,12 +285,12 @@ class TestRepo(TestBase): def test_untracked_files(self): base = self.rorepo.working_tree_dir - files = ( join_path_native(base, "__test_myfile"), - join_path_native(base, "__test_other_file") ) + files = (join_path_native(base, "__test_myfile"), + join_path_native(base, "__test_other_file")) num_recently_untracked = 0 try: for fpath in files: - fd = open(fpath,"wb") + fd = open(fpath, "wb") fd.close() # END for each filename untracked_files = self.rorepo.untracked_files @@ -356,7 +356,7 @@ class TestRepo(TestBase): # full size # size is without terminating newline def mkfull(): - return Git.CatFileContentStream(len(d)-1, StringIO(d)) + return Git.CatFileContentStream(len(d) - 1, StringIO(d)) ts = 5 @@ -378,7 +378,7 @@ class TestRepo(TestBase): s = mktiny() lines = s.readlines() assert len(lines) == 1 and lines[0] == l1p - assert s._stream.tell() == ts+1 + assert s._stream.tell() == ts + 1 # readline no limit s = mkfull() @@ -397,7 +397,7 @@ class TestRepo(TestBase): s = mktiny() assert s.readline() == l1p assert s.readline() == '' - assert s._stream.tell() == ts+1 + assert s._stream.tell() == ts + 1 # read no limit s = mkfull() @@ -416,7 +416,7 @@ class TestRepo(TestBase): assert s.read(2) == l1[:2] assert s._stream.tell() == 2 assert s.read() == l1[2:ts] - assert s._stream.tell() == ts+1 + assert s._stream.tell() == ts + 1 def _assert_rev_parse_types(self, name, rev_obj): rev_parse = self.rorepo.rev_parse @@ -457,7 +457,7 @@ class TestRepo(TestBase): # END get given amount of commits for pn in range(11): - rev = name + "~%i" % (pn+1) + rev = name + "~%i" % (pn + 1) obj2 = rev_parse(rev) assert obj2 == history[pn] self._assert_rev_parse_types(rev, obj2) @@ -471,7 +471,7 @@ class TestRepo(TestBase): # parent with number for pn, parent in enumerate(obj.parents): - rev = name + "^%i" % (pn+1) + rev = name + "^%i" % (pn + 1) assert rev_parse(rev) == parent self._assert_rev_parse_types(rev, parent) # END for each parent @@ -496,7 +496,7 @@ class TestRepo(TestBase): for ref in Reference.iter_items(self.rorepo): path_tokens = ref.path.split("/") for pt in range(len(path_tokens)): - path_section = '/'.join(path_tokens[-(pt+1):]) + path_section = '/'.join(path_tokens[-(pt + 1):]) try: obj = self._assert_rev_parse(path_section) assert obj.type == ref.object.type @@ -521,7 +521,7 @@ class TestRepo(TestBase): # multiple tree types result in the same tree: HEAD^{tree}^{tree}:CHANGES rev = '0.1.4^{tree}^{tree}' assert rev_parse(rev) == tag.object.tree - assert rev_parse(rev+':CHANGES') == tag.object.tree['CHANGES'] + assert rev_parse(rev + ':CHANGES') == tag.object.tree['CHANGES'] # try to get parents from first revision - it should fail as no such revision # exists @@ -529,8 +529,8 @@ class TestRepo(TestBase): commit = rev_parse(first_rev) assert len(commit.parents) == 0 assert commit.hexsha == first_rev - self.failUnlessRaises(BadObject, rev_parse, first_rev+"~") - self.failUnlessRaises(BadObject, rev_parse, first_rev+"^") + self.failUnlessRaises(BadObject, rev_parse, first_rev + "~") + self.failUnlessRaises(BadObject, rev_parse, first_rev + "^") # short SHA1 commit2 = rev_parse(first_rev[:20]) @@ -550,7 +550,7 @@ class TestRepo(TestBase): # try partial parsing max_items = 40 for i, binsha in enumerate(self.rorepo.odb.sha_iter()): - assert rev_parse(bin_to_hex(binsha)[:8-(i%2)]).binsha == binsha + assert rev_parse(bin_to_hex(binsha)[:8 - (i % 2)]).binsha == binsha if i > max_items: # this is rather slow currently, as rev_parse returns an object # which requires accessing packs, it has some additional overhead @@ -576,8 +576,8 @@ class TestRepo(TestBase): refspec = '%s@{0}' % head.ref.name assert rev_parse(refspec) == head.ref.commit # all additional specs work as well - assert rev_parse(refspec+"^{tree}") == head.commit.tree - assert rev_parse(refspec+":CHANGES").type == 'blob' + assert rev_parse(refspec + "^{tree}") == head.commit.tree + assert rev_parse(refspec + ":CHANGES").type == 'blob' #END operate on non-detached head # the last position diff --git a/git/test/test_submodule.py b/git/test/test_submodule.py index 0cf620c1..b657b25e 100644 --- a/git/test/test_submodule.py +++ b/git/test/test_submodule.py @@ -43,7 +43,7 @@ class TestSubmodule(TestBase): def _do_base_tests(self, rwrepo): """Perform all tests in the given repository, it may be bare or nonbare""" # manual instantiation - smm = Submodule(rwrepo, "\0"*20) + smm = Submodule(rwrepo, "\0" * 20) # name needs to be set in advance self.failUnlessRaises(AttributeError, getattr, smm, 'name') @@ -107,7 +107,7 @@ class TestSubmodule(TestBase): prev_parent_commit = smold.parent_commit self.failUnlessRaises(ValueError, smold.set_parent_commit, self.k_subm_current) # the sha is properly updated - smold.set_parent_commit(self.k_subm_changed+"~1") + smold.set_parent_commit(self.k_subm_changed + "~1") assert smold.binsha != sm.binsha # raises if the sm didn't exist in new parent - it keeps its @@ -130,7 +130,7 @@ class TestSubmodule(TestBase): # currently there is only one submodule assert len(list(rwrepo.iter_submodules())) == 1 - assert sm.binsha != "\0"*20 + assert sm.binsha != "\0" * 20 # TEST ADD ########### @@ -303,7 +303,7 @@ class TestSubmodule(TestBase): # add a simple remote repo - trailing slashes are no problem smid = "newsub" osmid = "othersub" - nsm = Submodule.add(rwrepo, smid, sm_repopath, new_smclone_path+"/", None, no_checkout=True) + nsm = Submodule.add(rwrepo, smid, sm_repopath, new_smclone_path + "/", None, no_checkout=True) assert nsm.name == smid assert nsm.module_exists() assert nsm.exists() diff --git a/git/test/test_tree.py b/git/test/test_tree.py index 7edae577..e3743c2d 100644 --- a/git/test/test_tree.py +++ b/git/test/test_tree.py @@ -59,7 +59,7 @@ class TestTree(TestBase): assert len(testtree) == cur_count # fails with a different sha - name exists - hexsha = "1"*40 + hexsha = "1" * 40 self.failUnlessRaises(ValueError, mod.add, hexsha, tree.mode, name) # force it - replace existing one @@ -113,18 +113,18 @@ class TestTree(TestBase): assert len(list(root)) == len(list(root.traverse(depth=1))) # only choose trees - trees_only = lambda i,d: i.type == "tree" - trees = list(root.traverse(predicate = trees_only)) - assert len(trees) == len(list( i for i in root.traverse() if trees_only(i,0) )) + trees_only = lambda i, d: i.type == "tree" + trees = list(root.traverse(predicate=trees_only)) + assert len(trees) == len(list(i for i in root.traverse() if trees_only(i, 0))) # test prune - lib_folder = lambda t,d: t.path == "lib" - pruned_trees = list(root.traverse(predicate = trees_only,prune = lib_folder)) + lib_folder = lambda t, d: t.path == "lib" + pruned_trees = list(root.traverse(predicate=trees_only, prune=lib_folder)) assert len(pruned_trees) < len(trees) # trees and blobs - assert len(set(trees)|set(root.trees)) == len(trees) - assert len(set(b for b in root if isinstance(b, Blob)) | set(root.blobs)) == len( root.blobs ) + assert len(set(trees) | set(root.trees)) == len(trees) + assert len(set(b for b in root if isinstance(b, Blob)) | set(root.blobs)) == len(root.blobs) subitem = trees[0][0] assert "/" in subitem.path assert subitem.name == os.path.basename(subitem.path) @@ -138,6 +138,6 @@ class TestTree(TestBase): # END check for slash # slashes in paths are supported as well - assert root[item.path] == item == root/item.path + assert root[item.path] == item == root / item.path # END for each item assert found_slash diff --git a/git/test/test_util.py b/git/test/test_util.py index ea62425b..63842d19 100644 --- a/git/test/test_util.py +++ b/git/test/test_util.py @@ -30,9 +30,9 @@ class TestUtils(TestBase): def setup(self): self.testdict = { - "string": "42", - "int": 42, - "array": [ 42 ], + "string": "42", + "int": 42, + "array": [42], } def test_it_should_dashify(self): diff --git a/git/util.py b/git/util.py index 8d5cd765..180ed907 100644 --- a/git/util.py +++ b/git/util.py @@ -26,7 +26,7 @@ from gitdb.util import ( to_bin_sha ) -__all__ = ( "stream_copy", "join_path", "to_native_path_windows", "to_native_path_linux", +__all__ = ("stream_copy", "join_path", "to_native_path_windows", "to_native_path_linux", "join_path_native", "Stats", "IndexFileSHA1Writer", "Iterable", "IterableList", "BlockingLockFile", "LockFile", 'Actor', 'get_user_id', 'assure_directory_exists', 'RemoteProgress', 'rmtree') @@ -49,7 +49,7 @@ def rmtree(path): return shutil.rmtree(path, False, onerror) -def stream_copy(source, destination, chunk_size=512*1024): +def stream_copy(source, destination, chunk_size=512 * 1024): """Copy all data from the source stream into the destination stream in chunks of size chunk_size @@ -83,11 +83,11 @@ def join_path(a, *p): def to_native_path_windows(path): - return path.replace('/','\\') + return path.replace('/', '\\') def to_native_path_linux(path): - return path.replace('\\','/') + return path.replace('\\', '/') if sys.platform.startswith('win'): to_native_path = to_native_path_windows @@ -130,7 +130,7 @@ def finalize_process(proc): """Wait for the process (clone, fetch, pull or push) and handle its errors accordingly""" try: proc.wait() - except GitCommandError,e: + except GitCommandError, e: # if a push has rejected items, the command has non-zero return status # a return status of 128 indicates a connection error - reraise the previous one if proc.poll() == 128: @@ -151,7 +151,7 @@ class RemoteProgress(object): """ _num_op_codes = 7 BEGIN, END, COUNTING, COMPRESSING, WRITING, RECEIVING, RESOLVING = [1 << x for x in range(_num_op_codes)] - STAGE_MASK = BEGIN|END + STAGE_MASK = BEGIN | END OP_MASK = ~STAGE_MASK __slots__ = ("_cur_line", "_seen_ops") @@ -176,10 +176,10 @@ class RemoteProgress(object): # find esacpe characters and cut them away - regex will not work with # them as they are non-ascii. As git might expect a tty, it will send them last_valid_index = None - for i,c in enumerate(reversed(sline)): + for i, c in enumerate(reversed(sline)): if ord(c) < 32: # its a slice index - last_valid_index = -i-1 + last_valid_index = -i - 1 # END character was non-ascii # END for each character in sline if last_valid_index is not None: @@ -284,8 +284,8 @@ class Actor(object): can be committers and authors or anything with a name and an email as mentioned in the git log entries.""" # PRECOMPILED REGEX - name_only_regex = re.compile( r'<(.+)>' ) - name_email_regex = re.compile( r'(.*) <(.+?)>' ) + name_only_regex = re.compile(r'<(.+)>') + name_email_regex = re.compile(r'(.*) <(.+?)>') # ENVIRONMENT VARIABLES # read when creating new commits @@ -577,7 +577,7 @@ class BlockingLockFile(LockFile): # END handle missing directory if curtime >= maxtime: - msg = "Waited %g seconds for lock at %r" % ( maxtime - starttime, self._lock_file_path()) + msg = "Waited %g seconds for lock at %r" % (maxtime - starttime, self._lock_file_path()) raise IOError(msg) # END abort if we wait too long time.sleep(self._check_interval) @@ -605,7 +605,7 @@ class IterableList(list): __slots__ = ('_id_attr', '_prefix') def __new__(cls, id_attr, prefix=''): - return super(IterableList,cls).__new__(cls) + return super(IterableList, cls).__new__(cls) def __init__(self, id_attr, prefix=''): self._id_attr = id_attr @@ -636,12 +636,12 @@ class IterableList(list): def __getitem__(self, index): if isinstance(index, int): - return list.__getitem__(self,index) + return list.__getitem__(self, index) try: return getattr(self, index) except AttributeError: - raise IndexError( "No item found with id %r" % (self._prefix + index) ) + raise IndexError("No item found with id %r" % (self._prefix + index)) # END handle getattr def __delitem__(self, index): @@ -679,7 +679,7 @@ class Iterable(object): :note: Favor the iter_items method as it will :return:list(Item,...) list of item instances""" - out_list = IterableList( cls._id_attribute_ ) + out_list = IterableList(cls._id_attribute_) out_list.extend(cls.iter_items(repo, *args, **kwargs)) return out_list |