diff options
author | Sebastian Thiel <byronimo@gmail.com> | 2014-11-19 12:16:54 +0100 |
---|---|---|
committer | Sebastian Thiel <byronimo@gmail.com> | 2014-11-19 12:16:54 +0100 |
commit | 1234a1077f24ca0e2f1a9b4d27731482a7ed752b (patch) | |
tree | 755ccbe76bc225ef237264e1b45bcb17202087ec | |
parent | 4d9b7b09a7c66e19a608d76282eacc769e349150 (diff) | |
parent | 257264743154b975bc156f425217593be14727a9 (diff) | |
download | gitpython-1234a1077f24ca0e2f1a9b4d27731482a7ed752b.tar.gz |
Merge branch 'autopep' into 0.3
Resolves https://github.com/gitpython-developers/GitPython/pull/182
48 files changed, 814 insertions, 668 deletions
diff --git a/git/__init__.py b/git/__init__.py index d87dcbdb..5580c9a6 100644 --- a/git/__init__.py +++ b/git/__init__.py @@ -20,7 +20,7 @@ def _init_externals(): import gitdb except ImportError: raise ImportError("'gitdb' could not be found in your PYTHONPATH") - #END verify import + # END verify import #} END initialization @@ -41,13 +41,13 @@ from git.repo import Repo from git.remote import * from git.index import * from git.util import ( - LockFile, - BlockingLockFile, - Stats, - Actor - ) + LockFile, + BlockingLockFile, + Stats, + Actor +) #} END imports __all__ = [name for name, obj in locals().items() - if not (name.startswith('_') or inspect.ismodule(obj))] + if not (name.startswith('_') or inspect.ismodule(obj))] @@ -4,18 +4,19 @@ # This module is part of GitPython and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php -import os, sys +import os +import sys from util import ( - LazyMixin, - stream_copy - ) + LazyMixin, + stream_copy +) from exc import GitCommandError from subprocess import ( - call, - Popen, - PIPE - ) + call, + Popen, + PIPE +) execute_kwargs = ('istream', 'with_keep_cwd', 'with_extended_output', 'with_exceptions', 'as_process', @@ -29,6 +30,7 @@ def dashify(string): class Git(LazyMixin): + """ The Git class manages communication with the Git binary. @@ -246,7 +248,7 @@ class Git(LazyMixin): self._version_info = tuple(int(n) for n in version_numbers.split('.')[:4] if n.isdigit()) else: super(Git, self)._set_cache_(attr) - #END handle version info + # END handle version info @property def working_dir(self): @@ -336,25 +338,25 @@ class Git(LazyMixin): # Allow the user to have the command executed in their working dir. if with_keep_cwd or self._working_dir is None: - cwd = os.getcwd() + cwd = os.getcwd() else: - cwd = self._working_dir + cwd = self._working_dir # Start the process env = os.environ.copy() env["LC_MESSAGES"] = "C" proc = Popen(command, - env=env, - cwd=cwd, - stdin=istream, - stderr=PIPE, - stdout=PIPE, - # Prevent cmd prompt popups on windows by using a shell ... . - # See https://github.com/gitpython-developers/GitPython/pull/126 - shell=sys.platform == 'win32', - close_fds=(os.name == 'posix'), # unsupported on linux - **subprocess_kwargs - ) + env=env, + cwd=cwd, + stdin=istream, + stderr=PIPE, + stdout=PIPE, + # Prevent cmd prompt popups on windows by using a shell ... . + # See https://github.com/gitpython-developers/GitPython/pull/126 + shell=sys.platform == 'win32', + close_fds=(os.name == 'posix'), # unsupported on linux + **subprocess_kwargs + ) if as_process: return self.AutoInterrupt(proc, command) @@ -508,7 +510,7 @@ class Git(LazyMixin): call.extend([dashify(method)]) call.extend(args) return call - #END utility to recreate call after changes + # END utility to recreate call after changes if sys.platform == 'win32': try: @@ -518,7 +520,7 @@ class Git(LazyMixin): # did we switch to git.cmd already, or was it changed from default ? permanently fail if self.GIT_PYTHON_GIT_EXECUTABLE != self.git_exec_name: raise - #END handle overridden variable + # END handle overridden variable type(self).GIT_PYTHON_GIT_EXECUTABLE = self.git_exec_name_win call = [self.GIT_PYTHON_GIT_EXECUTABLE] + list(args) @@ -529,14 +531,14 @@ class Git(LazyMixin): msg = "WARNING: Automatically switched to use git.cmd as git executable, which reduces performance by ~70%." msg += "Its recommended to put git.exe into the PATH or to set the %s environment variable to the executable's location" % self._git_exec_env_var warnings.warn(msg) - #END print of warning - #END catch first failure + # END print of warning + # END catch first failure except WindowsError: raise WindowsError("The system cannot find or execute the file at %r" % self.GIT_PYTHON_GIT_EXECUTABLE) - #END provide better error message + # END provide better error message else: return self.execute(make_call(), **_kwargs) - #END handle windows default installation + # END handle windows default installation def _parse_object_header(self, header_line): """ diff --git a/git/config.py b/git/config.py index 15aa76f0..8a15466f 100644 --- a/git/config.py +++ b/git/config.py @@ -80,7 +80,7 @@ class SectionConstraint(object): It supports all ConfigParser methods that operate on an option""" __slots__ = ("_config", "_section_name") _valid_attrs_ = ("get_value", "set_value", "get", "set", "getint", "getfloat", "getboolean", "has_option", - "remove_section", "remove_option", "options") + "remove_section", "remove_option", "options") def __init__(self, config, section): self._config = config @@ -136,7 +136,7 @@ class GitConfigParser(cp.RawConfigParser, object): # (either : or =), followed # by any # space/tab r'(?P<value>.*)$' # everything up to eol - ) + ) # list of RawConfigParser methods able to change the instance _mutating_methods_ = ("add_section", "remove_section", "remove_option", "set") @@ -165,7 +165,8 @@ class GitConfigParser(cp.RawConfigParser, object): if not read_only: if isinstance(file_or_files, (tuple, list)): - raise ValueError("Write-ConfigParsers can operate on a single file only, multiple files have been passed") + raise ValueError( + "Write-ConfigParsers can operate on a single file only, multiple files have been passed") # END single file check if not isinstance(file_or_files, basestring): @@ -338,7 +339,7 @@ class GitConfigParser(cp.RawConfigParser, object): # make sure we do not overwrite into an existing file if hasattr(fp, 'truncate'): fp.truncate() - #END + # END # END handle stream or file # WRITE DATA @@ -1,25 +1,25 @@ """Module with our own gitdb implementation - it uses the git command""" from exc import ( - GitCommandError, - BadObject - ) + GitCommandError, + BadObject +) from gitdb.base import ( - OInfo, - OStream - ) + OInfo, + OStream +) from gitdb.util import ( - bin_to_hex, - hex_to_bin - ) + bin_to_hex, + hex_to_bin +) from gitdb.db import GitDB from gitdb.db import LooseObjectDB __all__ = ('GitCmdObjectDB', 'GitDB') -#class GitCmdObjectDB(CompoundDB, ObjectDBW): +# class GitCmdObjectDB(CompoundDB, ObjectDBW): class GitCmdObjectDB(LooseObjectDB): diff --git a/git/diff.py b/git/diff.py index d8424e71..456974af 100644 --- a/git/diff.py +++ b/git/diff.py @@ -308,8 +308,8 @@ class Diff(object): new_file, deleted_file = bool(new_file_mode), bool(deleted_file_mode) index.append(Diff(repo, a_path, b_path, a_blob_id, b_blob_id, - old_mode or deleted_file_mode, new_mode or new_file_mode or b_mode, - new_file, deleted_file, rename_from, rename_to, diff[header.end():])) + old_mode or deleted_file_mode, new_mode or new_file_mode or b_mode, + new_file, deleted_file, rename_from, rename_to, diff[header.end():])) return index diff --git a/git/index/base.py b/git/index/base.py index bbbe3028..051423bf 100644 --- a/git/index/base.py +++ b/git/index/base.py @@ -13,54 +13,54 @@ from cStringIO import StringIO from stat import S_ISLNK from typ import ( - BaseIndexEntry, - IndexEntry, - ) + BaseIndexEntry, + IndexEntry, +) from util import ( - TemporaryFileSwap, - post_clear_cache, - default_index, - git_working_dir - ) + TemporaryFileSwap, + post_clear_cache, + default_index, + git_working_dir +) import git.objects import git.diff as diff from git.exc import ( - GitCommandError, - CheckoutError - ) + GitCommandError, + CheckoutError +) from git.objects import ( - Blob, - Submodule, - Tree, - Object, - Commit, - ) + Blob, + Submodule, + Tree, + Object, + Commit, +) from git.objects.util import Serializable from git.util import ( - IndexFileSHA1Writer, - LazyMixin, - LockedFD, - join_path_native, - file_contents_ro, - to_native_path_linux, - to_native_path - ) + IndexFileSHA1Writer, + LazyMixin, + LockedFD, + join_path_native, + file_contents_ro, + to_native_path_linux, + to_native_path +) from fun import ( - entry_key, - write_cache, - read_cache, - aggressive_tree_merge, - write_tree_from_cache, - stat_mode_to_index_mode, - S_IFGITLINK - ) + entry_key, + write_cache, + read_cache, + aggressive_tree_merge, + write_tree_from_cache, + stat_mode_to_index_mode, + S_IFGITLINK +) from gitdb.base import IStream from gitdb.db import MemoryDB @@ -380,7 +380,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): # END for each path def _write_path_to_stdin(self, proc, filepath, item, fmakeexc, fprogress, - read_from_stdout=True): + read_from_stdout=True): """Write path to proc.stdin and make sure it processes the item, including progress. :return: stdout string @@ -572,8 +572,8 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): fprogress(filepath, False, filepath) istream = self.repo.odb.store(IStream(Blob.type, st.st_size, stream)) fprogress(filepath, True, filepath) - return BaseIndexEntry((stat_mode_to_index_mode(st.st_mode), - istream.binsha, 0, to_native_path_linux(filepath))) + return BaseIndexEntry((stat_mode_to_index_mode(st.st_mode), + istream.binsha, 0, to_native_path_linux(filepath))) @git_working_dir def _entries_for_paths(self, paths, path_rewriter, fprogress, entries): @@ -581,9 +581,9 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): if path_rewriter: for path in paths: abspath = os.path.abspath(path) - 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), + 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)) # TODO: variable undefined entries.append(BaseIndexEntry.from_blob(blob)) @@ -599,9 +599,8 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): # END path handling return entries_added - - def add(self, items, force=True, fprogress=lambda *args: None, path_rewriter=None, - write=True): + def add(self, items, force=True, fprogress=lambda *args: None, path_rewriter=None, + write=True): """Add files from the working tree, specific blobs or BaseIndexEntries to the index. @@ -676,7 +675,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): :param write: If True, the index will be written once it was altered. Otherwise the changes only exist in memory and are not available to git commands. - + :return: List(BaseIndexEntries) representing the entries just actually added. @@ -698,23 +697,25 @@ 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") + 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: @git_working_dir def handle_null_entries(self): for ei in null_entries_indices: null_entry = entries[ei] new_entry = self._store_path(null_entry.path, fprogress) - + # update null entry - entries[ei] = BaseIndexEntry((null_entry.mode, new_entry.binsha, null_entry.stage, null_entry.path)) + entries[ei] = BaseIndexEntry( + (null_entry.mode, new_entry.binsha, null_entry.stage, null_entry.path)) # END for each entry index # end closure handle_null_entries(self) @@ -724,7 +725,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 @@ -744,11 +745,11 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): # add the new entries to this instance for entry in entries_added: self.entries[(entry.path, 0)] = IndexEntry.from_base(entry) - + if write: self.write() # END handle write - + return entries_added def _items_to_rela_paths(self, items): @@ -993,7 +994,8 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): raise GitCommandError(("git-checkout-index", ), 128, stderr) if failed_files: valid_files = list(set(iter_checked_out_files) - set(failed_files)) - raise CheckoutError("Some files could not be checked out from the index due to local modifications", failed_files, valid_files, failed_reasons) + raise CheckoutError( + "Some files could not be checked out from the index due to local modifications", failed_files, valid_files, failed_reasons) # END stderr handler if paths is None: @@ -1037,7 +1039,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): if entry.path.startswith(dir): p = entry.path self._write_path_to_stdin(proc, p, p, make_exc, - fprogress, read_from_stdout=False) + fprogress, read_from_stdout=False) checked_out_files.append(p) path_is_directory = True # END if entry is in directory @@ -1046,7 +1048,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable): if not path_is_directory: self._write_path_to_stdin(proc, co_path, path, make_exc, - fprogress, read_from_stdout=False) + fprogress, read_from_stdout=False) checked_out_files.append(co_path) # END path is a file # END for each path diff --git a/git/index/fun.py b/git/index/fun.py index cf55064e..4750463c 100644 --- a/git/index/fun.py +++ b/git/index/fun.py @@ -2,14 +2,14 @@ # more versatile # NOTE: Autodoc hates it if this is a docstring from stat import ( - S_IFDIR, - S_IFLNK, - S_ISLNK, - S_IFDIR, - S_ISDIR, - S_IFMT, - S_IFREG, - ) + S_IFDIR, + S_IFLNK, + S_ISLNK, + S_IFDIR, + S_ISDIR, + S_IFMT, + S_IFREG, +) S_IFGITLINK = S_IFLNK | S_IFDIR # a submodule @@ -18,29 +18,29 @@ from cStringIO import StringIO from git.util import IndexFileSHA1Writer from git.exc import UnmergedEntriesError from git.objects.fun import ( - tree_to_stream, - traverse_tree_recursive, - traverse_trees_recursive - ) + tree_to_stream, + traverse_tree_recursive, + traverse_trees_recursive +) from typ import ( - BaseIndexEntry, - IndexEntry, - CE_NAMEMASK, - CE_STAGESHIFT - ) + BaseIndexEntry, + IndexEntry, + CE_NAMEMASK, + CE_STAGESHIFT +) CE_NAMEMASK_INV = ~CE_NAMEMASK from util import ( - pack, - unpack - ) + pack, + unpack +) from gitdb.base import IStream from gitdb.typ import str_tree_type __all__ = ('write_cache', 'read_cache', 'write_tree_from_cache', 'entry_key', - 'stat_mode_to_index_mode', 'S_IFGITLINK') + 'stat_mode_to_index_mode', 'S_IFGITLINK') def stat_mode_to_index_mode(mode): @@ -86,7 +86,7 @@ def write_cache(entries, stream, extension_data=None, ShaStreamCls=IndexFileSHA1 assert plen == len(path), "Path %s too long to fit into index" % entry[3] flags = plen | (entry[2] & CE_NAMEMASK_INV) # clear possible previous values write(pack(">LLLLLL20sH", entry[6], entry[7], entry[0], - entry[8], entry[9], entry[10], entry[1], flags)) + entry[8], entry[9], entry[10], entry[1], flags)) write(path) real_size = ((tell() - beginoffset + 8) & ~7) write("\0" * ((beginoffset + real_size) - tell())) @@ -101,15 +101,15 @@ def write_cache(entries, stream, extension_data=None, ShaStreamCls=IndexFileSHA1 def read_header(stream): - """Return tuple(version_long, num_entries) from the given stream""" - type_id = stream.read(4) - if type_id != "DIRC": - raise AssertionError("Invalid index file header: %r" % type_id) - version, num_entries = unpack(">LL", stream.read(4 * 2)) + """Return tuple(version_long, num_entries) from the given stream""" + type_id = stream.read(4) + if type_id != "DIRC": + raise AssertionError("Invalid index file header: %r" % type_id) + version, num_entries = unpack(">LL", stream.read(4 * 2)) - # TODO: handle version 3: extended data, see read-cache.c - assert version in (1, 2) - return version, num_entries + # TODO: handle version 3: extended data, see read-cache.c + assert version in (1, 2) + return version, num_entries def entry_key(*entry): @@ -160,7 +160,8 @@ def read_cache(stream): # 4 bytes length of chunk # repeated 0 - N times extension_data = stream.read(~0) - assert len(extension_data) > 19, "Index Footer was not at least a sha on content as it was only %i bytes in size" % len(extension_data) + assert len(extension_data) > 19, "Index Footer was not at least a sha on content as it was only %i bytes in size" % len( + extension_data) content_sha = extension_data[-20:] @@ -265,7 +266,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)) @@ -299,7 +300,7 @@ def aggressive_tree_merge(odb, tree_shas): out_append(_tree_entry_to_baseindexentry(base, 1)) out_append(_tree_entry_to_baseindexentry(theirs, 3)) # END theirs changed - #else: + # else: # theirs didnt change # pass # END handle theirs diff --git a/git/index/typ.py b/git/index/typ.py index 4a6f6a81..a71fc2c6 100644 --- a/git/index/typ.py +++ b/git/index/typ.py @@ -1,13 +1,13 @@ """Module with additional types used by the index""" from util import ( - pack, - unpack - ) + pack, + unpack +) from binascii import ( - b2a_hex, - ) + b2a_hex, +) from git.objects import Blob __all__ = ('BlobFilter', 'BaseIndexEntry', 'IndexEntry') diff --git a/git/index/util.py b/git/index/util.py index 064a22ce..171bd8fc 100644 --- a/git/index/util.py +++ b/git/index/util.py @@ -64,7 +64,8 @@ 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 088dd699..0b40934c 100644 --- a/git/objects/__init__.py +++ b/git/objects/__init__.py @@ -18,4 +18,4 @@ from commit import * from tree import * __all__ = [name for name, obj in locals().items() - if not (name.startswith('_') or inspect.ismodule(obj))] + if not (name.startswith('_') or inspect.ismodule(obj))] diff --git a/git/objects/base.py b/git/objects/base.py index 0fcd25d6..50647a3a 100644 --- a/git/objects/base.py +++ b/git/objects/base.py @@ -6,10 +6,10 @@ from git.util import LazyMixin, join_path_native, stream_copy from util import get_object_type_by_name from gitdb.util import ( - hex_to_bin, - bin_to_hex, - basename - ) + hex_to_bin, + bin_to_hex, + basename +) import gitdb.typ as dbtyp @@ -62,7 +62,7 @@ class Object(LazyMixin): if sha1 == cls.NULL_BIN_SHA: # the NULL binsha is always the root commit return get_object_type_by_name('commit')(repo, sha1) - #END handle special case + # END handle special case oinfo = repo.odb.info(sha1) inst = get_object_type_by_name(oinfo.type)(repo, oinfo.binsha) inst.size = oinfo.size @@ -157,7 +157,8 @@ 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 453afe66..c6adcc94 100644 --- a/git/objects/commit.py +++ b/git/objects/commit.py @@ -5,11 +5,11 @@ # the BSD License: http://www.opensource.org/licenses/bsd-license.php from git.util import ( - Actor, - Iterable, - Stats, - finalize_process - ) + Actor, + Iterable, + Stats, + finalize_process +) from git.diff import Diffable from tree import Tree from gitdb import IStream @@ -17,19 +17,19 @@ from cStringIO import StringIO import base from gitdb.util import ( - hex_to_bin - ) + hex_to_bin +) from util import ( - Traversable, - Serializable, - parse_date, - altz_to_utctz_str, - parse_actor_and_date - ) + Traversable, + Serializable, + parse_date, + altz_to_utctz_str, + parse_actor_and_date +) from time import ( - time, - altzone - ) + time, + altzone +) import os import sys @@ -339,9 +339,9 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): # CREATE NEW COMMIT new_commit = cls(repo, cls.NULL_BIN_SHA, tree, - author, author_time, author_offset, - committer, committer_time, committer_offset, - message, parent_commits, conf_encoding) + author, author_time, author_offset, + committer, committer_time, committer_offset, + message, parent_commits, conf_encoding) stream = StringIO() new_commit._serialize(stream) @@ -384,8 +384,8 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): c = self.committer fmt = "%s %s <%s> %s %s\n" write(fmt % ("author", aname, a.email, - self.authored_date, - altz_to_utctz_str(self.author_tz_offset))) + self.authored_date, + altz_to_utctz_str(self.author_tz_offset))) # encode committer aname = c.name @@ -393,8 +393,8 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): aname = aname.encode(self.encoding) # END handle unicode in name write(fmt % ("committer", aname, c.email, - self.committed_date, - altz_to_utctz_str(self.committer_tz_offset))) + self.committed_date, + altz_to_utctz_str(self.committer_tz_offset))) if self.encoding != self.default_encoding: write("encoding %s\n" % self.encoding) @@ -457,7 +457,8 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): is_next_header = False while True: sigbuf = readline() - if sigbuf == "": break + if sigbuf == "": + break if sigbuf[0:1] != " ": buf = sigbuf.strip() is_next_header = True @@ -472,14 +473,16 @@ class Commit(base.Object, Iterable, Diffable, Traversable, Serializable): try: self.author.name = self.author.name.decode(self.encoding) except UnicodeDecodeError: - print >> sys.stderr, "Failed to decode author name '%s' using encoding %s" % (self.author.name, self.encoding) + print >> sys.stderr, "Failed to decode author name '%s' using encoding %s" % ( + self.author.name, self.encoding) # END handle author's encoding # decode committer name try: self.committer.name = self.committer.name.decode(self.encoding) except UnicodeDecodeError: - print >> sys.stderr, "Failed to decode committer name '%s' using encoding %s" % (self.committer.name, self.encoding) + print >> sys.stderr, "Failed to decode committer name '%s' using encoding %s" % ( + self.committer.name, self.encoding) # END handle author's encoding # a stream from our data simply gives us the plain message diff --git a/git/objects/fun.py b/git/objects/fun.py index 21b89fca..416a52e6 100644 --- a/git/objects/fun.py +++ b/git/objects/fun.py @@ -2,7 +2,7 @@ from stat import S_ISDIR __all__ = ('tree_to_stream', 'tree_entries_from_data', 'traverse_trees_recursive', - 'traverse_tree_recursive') + 'traverse_tree_recursive') def tree_to_stream(entries, write): @@ -167,7 +167,8 @@ def traverse_trees_recursive(odb, tree_shas, path_prefix): # 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 diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 14e1c930..e3d58077 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -1,27 +1,27 @@ import util from util import ( - mkhead, - sm_name, - sm_section, - unbare_repo, - SubmoduleConfigParser, - find_first_remote_branch - ) + mkhead, + sm_name, + sm_section, + unbare_repo, + SubmoduleConfigParser, + find_first_remote_branch +) from git.objects.util import Traversable from StringIO import StringIO # need a dict to set bloody .name field from git.util import ( - Iterable, - join_path_native, - to_native_path_linux, - RemoteProgress, - rmtree - ) + Iterable, + join_path_native, + to_native_path_linux, + RemoteProgress, + rmtree +) from git.config import SectionConstraint from git.exc import ( - InvalidGitRepositoryError, - NoSuchPathError - ) + InvalidGitRepositoryError, + NoSuchPathError +) import stat import git @@ -160,7 +160,8 @@ class Submodule(util.IndexObject, Iterable, Traversable): try: fp_module = cls._sio_modules(parent_commit) except KeyError: - raise IOError("Could not find %s file in the tree of parent commit %s" % (cls.k_modules_file, parent_commit)) + raise IOError("Could not find %s file in the tree of parent commit %s" % + (cls.k_modules_file, parent_commit)) # END handle exceptions # END handle non-bare working tree @@ -237,7 +238,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): # like it ... if url != None: url = to_native_path_linux(url) - #END assure url correctness + # END assure url correctness # INSTANTIATE INTERMEDIATE SM sm = cls(repo, cls.NULL_BIN_SHA, cls.k_default_mode, path, name) @@ -260,7 +261,8 @@ class Submodule(util.IndexObject, Iterable, Traversable): branch_is_default = branch is None if has_module and url is not None: if url not in [r.url for r in sm.module().remotes]: - raise ValueError("Specified URL '%s' does not match any remote url of the repository at '%s'" % (url, sm.abspath)) + raise ValueError( + "Specified URL '%s' does not match any remote url of the repository at '%s'" % (url, sm.abspath)) # END check url # END verify urls match @@ -307,7 +309,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): return sm def update(self, recursive=False, init=True, to_latest_revision=False, progress=None, - dry_run=False): + dry_run=False): """Update the repository of this submodule to point to the checkout we point at with the binsha of this instance. @@ -327,20 +329,20 @@ class Submodule(util.IndexObject, Iterable, Traversable): :return: self""" if self.repo.bare: return self - #END pass in bare mode + # END pass in bare mode if progress is None: progress = UpdateProgress() - #END handle progress + # END handle progress prefix = '' if dry_run: prefix = "DRY-RUN: " - #END handle prefix + # END handle prefix # to keep things plausible in dry-run mode if dry_run: mrepo = None - #END init mrepo + # END init mrepo # ASSURE REPO IS PRESENT AND UPTODATE ##################################### @@ -352,19 +354,19 @@ class Submodule(util.IndexObject, Iterable, Traversable): op = FETCH if i == 0: op |= BEGIN - #END handle start + # END handle start 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 + # END handle dry-run #=============================== if i == len_rmts - 1: op |= END - #END handle end + # END handle end progress.update(op, i, len_rmts, prefix + "Done fetching remote of submodule %r" % self.name) - #END fetch new data + # END fetch new data except InvalidGitRepositoryError: if not init: return self @@ -383,10 +385,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 + # END handle dry-run progress.update(END | CLONE, 0, 1, prefix + "Done cloning to %s" % module_path) if not dry_run: @@ -406,15 +409,15 @@ class Submodule(util.IndexObject, Iterable, Traversable): mrepo.head.ref.set_tracking_branch(remote_branch) except IndexError: print >> sys.stderr, "Warning: Failed to checkout tracking branch %s" % self.branch_path - #END handle tracking branch + # END handle tracking branch # NOTE: Have to write the repo config file as well, otherwise # the default implementation will be offended and not update the repository # Maybe this is a good way to assure it doesn't get into our way, but # we want to stay backwards compatible too ... . Its so redundant ! self.repo.config_writer().set_value(sm_section(self.name), 'url', self.url) - #END handle dry_run - #END handle initalization + # END handle dry_run + # END handle initalization # DETERMINE SHAS TO CHECKOUT ############################ @@ -423,7 +426,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): if mrepo is not None: # mrepo is only set if we are not in dry-run mode or if the module existed is_detached = mrepo.head.is_detached - #END handle dry_run + # END handle dry_run if mrepo is not None and to_latest_revision: msg_base = "Cannot update to latest revision in repository at %r as " % mrepo.working_dir @@ -434,7 +437,8 @@ class Submodule(util.IndexObject, Iterable, Traversable): binsha = rcommit.binsha hexsha = rcommit.hexsha else: - print >> sys.stderr, "%s a tracking branch was not set for local branch '%s'" % (msg_base, mrepo.head.ref) + print >> sys.stderr, "%s a tracking branch was not set for local branch '%s'" % ( + msg_base, mrepo.head.ref) # END handle remote ref else: print >> sys.stderr, "%s there was no local tracking branch" % msg_base @@ -444,7 +448,8 @@ 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 @@ -458,7 +463,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): # branch - this should be prevented when setting the branch option mrepo.head.reset(hexsha, index=True, working_tree=True) # END handle checkout - #END handle dry_run + # END handle dry_run progress.update(END | UPDWKTREE, 0, 1, prefix + "Done updating working tree for submodule %r" % self.name) # END update to new commit only if needed @@ -470,7 +475,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): for submodule in self.iter_items(self.module()): submodule.update(recursive, init, to_latest_revision, progress=progress, dry_run=dry_run) # END handle recursive update - #END handle dry run + # END handle dry run # END for each submodule return self @@ -498,7 +503,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): """ if module + configuration < 1: raise ValueError("You must specify to move at least the module or the configuration of the submodule") - #END handle input + # END handle input module_path = to_native_path_linux(module_path) if module_path.endswith('/'): @@ -508,7 +513,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): # VERIFY DESTINATION if module_path == self.path: return self - #END handle no change + # END handle no change dest_path = join_path_native(self.repo.working_tree_dir, module_path) if os.path.isfile(dest_path): @@ -520,25 +525,25 @@ class Submodule(util.IndexObject, Iterable, Traversable): # if the target item already exists, fail if configuration and tekey in index.entries: raise ValueError("Index entry for target path did alredy exist") - #END handle index key already there + # END handle index key already there # remove existing destination if module: if os.path.exists(dest_path): if len(os.listdir(dest_path)): raise ValueError("Destination module directory was not empty") - #END handle non-emptyness + # END handle non-emptyness if os.path.islink(dest_path): os.remove(dest_path) else: os.rmdir(dest_path) - #END handle link + # END handle link else: # recreate parent directories # NOTE: renames() does that now pass - #END handle existance + # END handle existance # END handle module # move the module into place if possible @@ -547,7 +552,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): if module and os.path.exists(cur_path): os.renames(cur_path, dest_path) renamed_module = True - #END move physical module + # END move physical module # rename the index entry - have to manipulate the index directly as # git-mv cannot be used on submodules ... yeah @@ -561,7 +566,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): index.entries[tekey] = nentry except KeyError: raise InvalidGitRepositoryError("Submodule's entry at %r did not exist" % (self.path)) - #END handle submodule doesn't exist + # END handle submodule doesn't exist # update configuration writer = self.config_writer(index=index) # auto-write @@ -574,7 +579,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): os.renames(dest_path, cur_path) # END undo module renaming raise - #END handle undo rename + # END handle undo rename return self @@ -623,16 +628,17 @@ class Submodule(util.IndexObject, Iterable, Traversable): method = rmtree elif os.path.exists(mp): raise AssertionError("Cannot forcibly delete repository as it was neither a link, nor a directory") - #END handle brutal deletion + # END handle brutal deletion if not dry_run: assert method method(mp) - #END apply deletion method + # END apply deletion method else: # verify we may delete our module mod = self.module() if mod.is_dirty(untracked_files=True): - raise InvalidGitRepositoryError("Cannot delete module at %s with any modifications, unless force is specified" % mod.working_tree_dir) + raise InvalidGitRepositoryError( + "Cannot delete module at %s with any modifications, unless force is specified" % mod.working_tree_dir) # END check for dirt # figure out whether we have new commits compared to the remotes @@ -648,13 +654,14 @@ class Submodule(util.IndexObject, Iterable, Traversable): # END for each remote ref # not a single remote branch contained all our commits if num_branches_with_new_commits == len(rrefs): - raise InvalidGitRepositoryError("Cannot delete module at %s as there are new commits" % mod.working_tree_dir) + raise InvalidGitRepositoryError( + "Cannot delete module at %s as there are new commits" % mod.working_tree_dir) # END handle new commits # have to manually delete references as python's scoping is # not existing, they could keep handles open ( on windows this is a problem ) if len(rrefs): del(rref) - #END handle remotes + # END handle remotes del(rrefs) del(remote) # END for each remote @@ -683,7 +690,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): del(index.entries[index.entry_key(self.path, 0)]) except KeyError: pass - #END delete entry + # END delete entry index.write() # now git config - need the config intact, otherwise we can't query @@ -796,7 +803,7 @@ class Submodule(util.IndexObject, Iterable, Traversable): if hasattr(self, attr): loc[attr] = getattr(self, attr) # END if we have the attribute cache - #END for each attr + # END for each attr self._clear_cache() try: @@ -907,7 +914,8 @@ class Submodule(util.IndexObject, Iterable, Traversable): entry = index.entries[index.entry_key(p, 0)] sm = Submodule(repo, entry.binsha, entry.mode, entry.path) except KeyError: - raise InvalidGitRepositoryError("Gitmodule path %r did not exist in revision of parent commit %s" % (p, parent_commit)) + raise InvalidGitRepositoryError( + "Gitmodule path %r did not exist in revision of parent commit %s" % (p, parent_commit)) # END handle keyerror # END handle critical error diff --git a/git/objects/submodule/root.py b/git/objects/submodule/root.py index 581c5a7c..f68f7567 100644 --- a/git/objects/submodule/root.py +++ b/git/objects/submodule/root.py @@ -1,7 +1,7 @@ from base import Submodule, UpdateProgress from util import ( - find_first_remote_branch - ) + find_first_remote_branch +) from git.exc import InvalidGitRepositoryError import git @@ -13,7 +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)] + 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() @@ -38,15 +39,15 @@ class RootModule(Submodule): def __init__(self, repo): # 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) - ) + 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) + ) def _clear_cache(self): """May not do anything""" @@ -55,7 +56,7 @@ class RootModule(Submodule): #{ Interface def update(self, previous_commit=None, recursive=True, force_remove=False, init=True, - to_latest_revision=False, progress=None, dry_run=False): + to_latest_revision=False, progress=None, dry_run=False): """Update the submodules of this repository to the current HEAD commit. This method behaves smartly by determining changes of the path of a submodules repository, next to changes to the to-be-checked-out commit or the branch to be @@ -84,7 +85,7 @@ class RootModule(Submodule): if progress is None: progress = RootUpdateProgress() - #END assure progress is set + # END assure progress is set prefix = '' if dry_run: @@ -100,11 +101,11 @@ class RootModule(Submodule): previous_commit = repo.commit(repo.head.log_entry(-1).oldhexsha) if previous_commit.binsha == previous_commit.NULL_BIN_SHA: raise IndexError - #END handle initial commit + # END handle initial commit except IndexError: # in new repositories, there is no previous commit previous_commit = cur_commit - #END exception handling + # END exception handling else: previous_commit = repo.commit(previous_commit) # obtain commit object # END handle previous commit @@ -122,7 +123,7 @@ class RootModule(Submodule): op = REMOVE if i == 0: op |= BEGIN - #END handle begin + # END handle begin # fake it into thinking its at the current commit to allow deletion # of previous module. Trigger the cache to be updated before that @@ -130,11 +131,11 @@ class RootModule(Submodule): rsm._parent_commit = repo.head.commit if not dry_run: rsm.remove(configuration=False, module=True, force=force_remove) - #END handle dry-run + # END handle dry-run if i == len_rrsm - 1: op |= END - #END handle end + # END handle end progress.update(op, i, len_rrsm, prefix + "Done removing submodule %r" % rsm.name) # END for each removed submodule @@ -147,15 +148,17 @@ class RootModule(Submodule): psm = psms[csm.name] sm = sms[csm.name] - #PATH CHANGES + # 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) + # END handle dry_run + 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 +174,8 @@ 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] @@ -181,7 +185,8 @@ class RootModule(Submodule): # If we have a tracking branch, it should be available # in the new remote as well. if len([r for r in smr.refs if r.remote_head == sm.branch_name]) == 0: - raise ValueError("Submodule branch named %r was not available in new submodule remote at %r" % (sm.branch_name, sm.url)) + raise ValueError( + "Submodule branch named %r was not available in new submodule remote at %r" % (sm.branch_name, sm.url)) # END head is not detached # now delete the changed one @@ -204,8 +209,9 @@ class RootModule(Submodule): # and its okay to fail here # Alternatively we could just generate a unique name and leave all # existing ones in place - raise InvalidGitRepositoryError("Couldn't find original remote-repo at url %r" % psm.url) - #END handle one single remote + raise InvalidGitRepositoryError( + "Couldn't find original remote-repo at url %r" % psm.url) + # END handle one single remote # END handle check we found a remote orig_name = rmt_for_deletion.name @@ -241,11 +247,12 @@ class RootModule(Submodule): # the user will be able to commit the change easily print >> sys.stderr, "WARNING: Current sha %s was not contained in the tracking branch at the new remote, setting it the the remote's tracking branch" % sm.hexsha sm.binsha = rref.commit.binsha - #END reset binsha + # END reset binsha - #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)) + # 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)) # END skip remote handling if new url already exists in module # END handle url @@ -254,7 +261,8 @@ 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 @@ -263,7 +271,7 @@ class RootModule(Submodule): except OSError: # ... or reuse the existing one tbr = git.Head(smm, sm.branch_path) - #END assure tracking branch exists + # END assure tracking branch exists tbr.set_tracking_branch(find_first_remote_branch(smmr, sm.branch_name)) # figure out whether the previous tracking branch contains @@ -273,19 +281,20 @@ class RootModule(Submodule): tbr = find_first_remote_branch(smmr, psm.branch_name) if len(smm.git.cherry(tbr, psm.branch)) == 0: psm.branch.delete(smm, psm.branch) - #END delete original tracking branch if there are no changes + # END delete original tracking branch if there are no changes except InvalidGitRepositoryError: # ignore it if the previous branch couldn't be found in the # current remotes, this just means we can't handle it pass # END exception handling - #NOTE: All checkout is done in the base implementation of update - #END handle dry_run + # 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) - #END handle branch - #END handle + 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 # FINALLY UPDATE ALL ACTUAL SUBMODULES @@ -293,7 +302,7 @@ class RootModule(Submodule): for sm in sms: # update the submodule using the default method sm.update(recursive=False, init=init, to_latest_revision=to_latest_revision, - progress=progress, dry_run=dry_run) + progress=progress, dry_run=dry_run) # update recursively depth first - question is which inconsitent # state will be better in case it fails somewhere. Defective branch @@ -303,10 +312,10 @@ class RootModule(Submodule): # 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, - init=init, to_latest_revision=to_latest_revision, - progress=progress, dry_run=dry_run) - #END handle dry_run - #END handle recursive + init=init, to_latest_revision=to_latest_revision, + progress=progress, dry_run=dry_run) + # END handle dry_run + # END handle recursive # END for each submodule to update def module(self): diff --git a/git/objects/submodule/util.py b/git/objects/submodule/util.py index bbdf5e1e..01bd03b3 100644 --- a/git/objects/submodule/util.py +++ b/git/objects/submodule/util.py @@ -5,7 +5,7 @@ from StringIO import StringIO import weakref __all__ = ('sm_section', 'sm_name', 'mkhead', 'unbare_repo', 'find_first_remote_branch', - 'SubmoduleConfigParser') + 'SubmoduleConfigParser') #{ Utilities @@ -33,7 +33,7 @@ def unbare_repo(func): def wrapper(self, *args, **kwargs): if self.repo.bare: raise InvalidGitRepositoryError("Method '%s' cannot operate on bare repositories" % func.__name__) - #END bare method + # END bare method return func(self, *args, **kwargs) # END wrapper wrapper.__name__ = func.__name__ @@ -48,7 +48,7 @@ def find_first_remote_branch(remotes, branch_name): except IndexError: continue # END exception handling - #END for remote + # END for remote raise InvalidGitRepositoryError("Didn't find remote branch %r in any of the given remotes", branch_name) #} END utilities diff --git a/git/objects/tag.py b/git/objects/tag.py index 3fd7a4d4..3c379579 100644 --- a/git/objects/tag.py +++ b/git/objects/tag.py @@ -7,9 +7,9 @@ import base from gitdb.util import hex_to_bin from util import ( - get_object_type_by_name, - parse_actor_and_date - ) + get_object_type_by_name, + parse_actor_and_date +) __all__ = ("TagObject", ) @@ -21,7 +21,7 @@ class TagObject(base.Object): __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): + tagger=None, tagged_date=None, tagger_tz_offset=None, message=None): """Initialize a tag object with additional data :param repo: repository this object is located in diff --git a/git/objects/tree.py b/git/objects/tree.py index cc3699f5..9f63e4e3 100644 --- a/git/objects/tree.py +++ b/git/objects/tree.py @@ -11,13 +11,13 @@ from submodule.base import Submodule import git.diff as diff from fun import ( - tree_entries_from_data, - tree_to_stream - ) + tree_entries_from_data, + tree_to_stream +) from gitdb.util import ( - to_bin_sha, - ) + to_bin_sha, +) __all__ = ("TreeModifier", "Tree") @@ -125,11 +125,11 @@ 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 - # tree id added once Tree is defined - } + 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): super(Tree, self).__init__(repo, binsha, mode, path) @@ -212,8 +212,8 @@ class Tree(IndexObject, diff.Diffable, util.Traversable, util.Serializable): 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): + 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) diff --git a/git/objects/util.py b/git/objects/util.py index f6daca0f..f36bf296 100644 --- a/git/objects/util.py +++ b/git/objects/util.py @@ -5,9 +5,9 @@ # the BSD License: http://www.opensource.org/licenses/bsd-license.php """Module for general utility functions""" from git.util import ( - IterableList, - Actor - ) + IterableList, + Actor +) import re from collections import deque as Deque @@ -17,8 +17,8 @@ import time import os __all__ = ('get_object_type_by_name', 'parse_date', 'parse_actor_and_date', - 'ProcessStreamAdapter', 'Traversable', 'altz_to_utctz_str', 'utctz_to_altz', - 'verify_utctz', 'Actor') + 'ProcessStreamAdapter', 'Traversable', 'altz_to_utctz_str', 'utctz_to_altz', + 'verify_utctz', 'Actor') #{ Functions @@ -89,9 +89,9 @@ def verify_utctz(offset): if offset[0] not in "+-": raise fmt_exc if offset[1] not in digits or \ - offset[2] not in digits or \ - offset[3] not in digits or \ - offset[4] not in digits: + offset[2] not in digits or \ + offset[3] not in digits or \ + offset[4] not in digits: raise fmt_exc # END for each char return offset @@ -238,8 +238,8 @@ class Traversable(object): 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): + 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 diff --git a/git/odict.py b/git/odict.py index dbedbde7..c4c80499 100644 --- a/git/odict.py +++ b/git/odict.py @@ -18,7 +18,7 @@ from __future__ import generators __author__ = ('Nicola Larosa <nico-NoSp@m-tekNico.net>,' - 'Michael Foord <fuzzyman AT voidspace DOT org DOT uk>') + 'Michael Foord <fuzzyman AT voidspace DOT org DOT uk>') __docformat__ = "restructuredtext en" @@ -33,7 +33,8 @@ INTP_VER = sys.version_info[:2] if INTP_VER < (2, 2): raise RuntimeError("Python v.2.2 or later required") -import types, warnings +import types +import warnings class OrderedDict(dict): @@ -376,20 +377,20 @@ class OrderedDict(dict): if k in self: if self.strict: raise ValueError('slice assignment must be from ' - 'unique keys') + 'unique keys') else: # NOTE: This removes duplicate keys *first* # so start position might have changed? del self[k] self._sequence = (self._sequence[:pos] + newkeys + - self._sequence[pos:]) + self._sequence[pos:]) dict.update(self, val) else: # extended slice - length of new slice must be the same # as the one being replaced if len(keys) != len(val): raise ValueError('attempt to assign sequence of size %s ' - 'to extended slice of size %s' % (len(val), len(keys))) + 'to extended slice of size %s' % (len(val), len(keys))) # FIXME: efficiency? del self[key] item_list = zip(indexes, val.items()) @@ -399,7 +400,7 @@ class OrderedDict(dict): for pos, (newkey, newval) in item_list: if self.strict and newkey in self: raise ValueError('slice assignment must be from unique' - ' keys') + ' keys') self.insert(pos, newkey, newval) else: if key not in self: @@ -434,7 +435,7 @@ class OrderedDict(dict): """ if name == 'sequence': warnings.warn('Use of the sequence attribute is deprecated.' - ' Use the keys method instead.', DeprecationWarning) + ' Use the keys method instead.', DeprecationWarning) # NOTE: doesn't return anything self.setkeys(value) else: @@ -452,7 +453,7 @@ class OrderedDict(dict): """ if name == 'sequence': warnings.warn('Use of the sequence attribute is deprecated.' - ' Use the keys method instead.', DeprecationWarning) + ' Use the keys method instead.', DeprecationWarning) # NOTE: Still (currently) returns a direct reference. Need to # because code that uses sequence will expect to be able to # mutate it in place. @@ -616,7 +617,7 @@ class OrderedDict(dict): """ if len(args) > 1: raise TypeError, ('pop expected at most 2 arguments, got %s' % - (len(args) + 1)) + (len(args) + 1)) if key in self: val = self[key] del self[key] @@ -703,7 +704,7 @@ class OrderedDict(dict): key, val = item except TypeError: raise TypeError('cannot convert dictionary update' - ' sequence element "%s" to a 2-item sequence' % item) + ' sequence element "%s" to a 2-item sequence' % item) self[key] = val def rename(self, old_key, new_key): @@ -808,7 +809,7 @@ class OrderedDict(dict): if len(values) != len(self): # FIXME: correct error to raise? raise ValueError('Value list is not the same length as the ' - 'OrderedDict.') + 'OrderedDict.') self.update(zip(self, values)) ### Sequence Methods ### @@ -912,7 +913,7 @@ class Keys(object): indexes = range(len(self._main._sequence))[index] if len(indexes) != len(name): raise ValueError('attempt to assign sequence of size %s ' - 'to slice of size %s' % (len(name), len(indexes))) + 'to slice of size %s' % (len(name), len(indexes))) # check they are the same keys # FIXME: Use set old_keys = self._main._sequence[index] @@ -928,68 +929,94 @@ class Keys(object): for i, k, v in vals: if self._main.strict and k in self._main: raise ValueError('slice assignment must be from ' - 'unique keys') + 'unique keys') self._main.insert(i, k, v) else: raise ValueError('Cannot assign to keys') ### following methods pinched from UserList and adapted ### - def __repr__(self): return repr(self._main._sequence) + def __repr__(self): + return repr(self._main._sequence) # FIXME: do we need to check if we are comparing with another ``Keys`` # object? (like the __cast method of UserList) - def __lt__(self, other): return self._main._sequence < other + def __lt__(self, other): + return self._main._sequence < other - def __le__(self, other): return self._main._sequence <= other + def __le__(self, other): + return self._main._sequence <= other - def __eq__(self, other): return self._main._sequence == other + def __eq__(self, other): + return self._main._sequence == other - def __ne__(self, other): return self._main._sequence != other + def __ne__(self, other): + return self._main._sequence != other - def __gt__(self, other): return self._main._sequence > other + def __gt__(self, other): + return self._main._sequence > other - def __ge__(self, other): return self._main._sequence >= other + def __ge__(self, other): + return self._main._sequence >= other # FIXME: do we need __cmp__ as well as rich comparisons? - def __cmp__(self, other): return cmp(self._main._sequence, other) + def __cmp__(self, other): + return cmp(self._main._sequence, other) - def __contains__(self, item): return item in self._main._sequence + def __contains__(self, item): + return item in self._main._sequence - def __len__(self): return len(self._main._sequence) + def __len__(self): + return len(self._main._sequence) - def __iter__(self): return self._main.iterkeys() + def __iter__(self): + return self._main.iterkeys() - def count(self, item): return self._main._sequence.count(item) + def count(self, item): + return self._main._sequence.count(item) - def index(self, item, *args): return self._main._sequence.index(item, *args) + def index(self, item, *args): + return self._main._sequence.index(item, *args) - def reverse(self): self._main._sequence.reverse() + def reverse(self): + self._main._sequence.reverse() - def sort(self, *args, **kwds): self._main._sequence.sort(*args, **kwds) + 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 + def __add__(self, other): + return self._main._sequence + other - def __radd__(self, other): return other + self._main._sequence + def __radd__(self, other): + return other + self._main._sequence ## following methods not implemented for keys ## - def __delitem__(self, i): raise TypeError('Can\'t delete items from keys') + def __delitem__(self, i): + raise TypeError('Can\'t delete items from keys') - def __iadd__(self, other): raise TypeError('Can\'t add in place to keys') + def __iadd__(self, other): + raise TypeError('Can\'t add in place to keys') - def __imul__(self, n): raise TypeError('Can\'t multiply keys in place') + def __imul__(self, n): + raise TypeError('Can\'t multiply keys in place') - def append(self, item): raise TypeError('Can\'t append items to keys') + def append(self, item): + raise TypeError('Can\'t append items to keys') - def insert(self, i, item): raise TypeError('Can\'t insert items into keys') + def insert(self, i, item): + raise TypeError('Can\'t insert items into keys') - def pop(self, i=-1): raise TypeError('Can\'t pop items from keys') + def pop(self, i=-1): + raise TypeError('Can\'t pop items from keys') - def remove(self, item): raise TypeError('Can\'t remove items from keys') + def remove(self, item): + raise TypeError('Can\'t remove items from keys') - def extend(self, other): raise TypeError('Can\'t extend keys') + def extend(self, other): + raise TypeError('Can\'t extend keys') class Items(object): @@ -1027,7 +1054,7 @@ class Items(object): key, value = item if self._main.strict and key in self and (key != orig): raise ValueError('slice assignment must be from ' - 'unique keys') + 'unique keys') # delete the current one del self._main[self._main._sequence[index]] self._main.insert(index, key, value) @@ -1043,44 +1070,62 @@ class Items(object): del self._main[key] ### following methods pinched from UserList and adapted ### - def __repr__(self): return repr(self._main.items()) + def __repr__(self): + return repr(self._main.items()) # FIXME: do we need to check if we are comparing with another ``Items`` # object? (like the __cast method of UserList) - def __lt__(self, other): return self._main.items() < other + def __lt__(self, other): + return self._main.items() < other - def __le__(self, other): return self._main.items() <= other + def __le__(self, other): + return self._main.items() <= other - def __eq__(self, other): return self._main.items() == other + def __eq__(self, other): + return self._main.items() == other - def __ne__(self, other): return self._main.items() != other + def __ne__(self, other): + return self._main.items() != other - def __gt__(self, other): return self._main.items() > other + def __gt__(self, other): + return self._main.items() > other - def __ge__(self, other): return self._main.items() >= other + def __ge__(self, other): + return self._main.items() >= other - def __cmp__(self, other): return cmp(self._main.items(), other) + def __cmp__(self, other): + return cmp(self._main.items(), other) - def __contains__(self, item): return item in self._main.items() + def __contains__(self, item): + return item in self._main.items() - def __len__(self): return len(self._main._sequence) # easier :-) + def __len__(self): + return len(self._main._sequence) # easier :-) - def __iter__(self): return self._main.iteritems() + def __iter__(self): + return self._main.iteritems() - def count(self, item): return self._main.items().count(item) + def count(self, item): + return self._main.items().count(item) - def index(self, item, *args): return self._main.items().index(item, *args) + def index(self, item, *args): + return self._main.items().index(item, *args) - def reverse(self): self._main.reverse() + def reverse(self): + self._main.reverse() - def sort(self, *args, **kwds): self._main.sort(*args, **kwds) + 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 + def __add__(self, other): + return self._main.items() + other - def __radd__(self, other): return other + self._main.items() + def __radd__(self, other): + return other + self._main.items() def append(self, item): """Add an item to the end.""" @@ -1116,7 +1161,8 @@ class Items(object): ## following methods not implemented for items ## - def __imul__(self, n): raise TypeError('Can\'t multiply items in place') + def __imul__(self, n): + raise TypeError('Can\'t multiply items in place') class Values(object): @@ -1153,7 +1199,7 @@ class Values(object): keys = self._main._sequence[index] if len(keys) != len(value): raise ValueError('attempt to assign sequence of size %s ' - 'to slice of size %s' % (len(name), len(keys))) + 'to slice of size %s' % (len(name), len(keys))) # FIXME: efficiency? Would be better to calculate the indexes # directly from the slice object # NOTE: the new keys can collide with existing keys (or even @@ -1164,33 +1210,46 @@ class Values(object): self._main[self._main._sequence[index]] = value ### following methods pinched from UserList and adapted ### - def __repr__(self): return repr(self._main.values()) + def __repr__(self): + return repr(self._main.values()) # FIXME: do we need to check if we are comparing with another ``Values`` # object? (like the __cast method of UserList) - def __lt__(self, other): return self._main.values() < other + def __lt__(self, other): + return self._main.values() < other - def __le__(self, other): return self._main.values() <= other + def __le__(self, other): + return self._main.values() <= other - def __eq__(self, other): return self._main.values() == other + def __eq__(self, other): + return self._main.values() == other - def __ne__(self, other): return self._main.values() != other + def __ne__(self, other): + return self._main.values() != other - def __gt__(self, other): return self._main.values() > other + def __gt__(self, other): + return self._main.values() > other - def __ge__(self, other): return self._main.values() >= other + def __ge__(self, other): + return self._main.values() >= other - def __cmp__(self, other): return cmp(self._main.values(), other) + def __cmp__(self, other): + return cmp(self._main.values(), other) - def __contains__(self, item): return item in self._main.values() + def __contains__(self, item): + return item in self._main.values() - def __len__(self): return len(self._main._sequence) # easier :-) + def __len__(self): + return len(self._main._sequence) # easier :-) - def __iter__(self): return self._main.itervalues() + def __iter__(self): + return self._main.itervalues() - def count(self, item): return self._main.values().count(item) + def count(self, item): + return self._main.values().count(item) - def index(self, item, *args): return self._main.values().index(item, *args) + def index(self, item, *args): + return self._main.values().index(item, *args) def reverse(self): """Reverse the values""" @@ -1205,29 +1264,40 @@ 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 + def __add__(self, other): + return self._main.values() + other - def __radd__(self, other): return other + self._main.values() + def __radd__(self, other): + return other + self._main.values() ## following methods not implemented for values ## - def __delitem__(self, i): raise TypeError('Can\'t delete items from values') + def __delitem__(self, i): + raise TypeError('Can\'t delete items from values') - def __iadd__(self, other): raise TypeError('Can\'t add in place to values') + def __iadd__(self, other): + raise TypeError('Can\'t add in place to values') - def __imul__(self, n): raise TypeError('Can\'t multiply values in place') + def __imul__(self, n): + raise TypeError('Can\'t multiply values in place') - def append(self, item): raise TypeError('Can\'t append items to values') + def append(self, item): + raise TypeError('Can\'t append items to values') - def insert(self, i, item): raise TypeError('Can\'t insert items into values') + def insert(self, i, item): + raise TypeError('Can\'t insert items into values') - def pop(self, i=-1): raise TypeError('Can\'t pop items from values') + def pop(self, i=-1): + raise TypeError('Can\'t pop items from values') - def remove(self, item): raise TypeError('Can\'t remove items from values') + def remove(self, item): + raise TypeError('Can\'t remove items from values') - def extend(self, other): raise TypeError('Can\'t extend values') + def extend(self, other): + raise TypeError('Can\'t extend values') class SequenceOrderedDict(OrderedDict): diff --git a/git/refs/head.py b/git/refs/head.py index 2ef7c23e..6f36a956 100644 --- a/git/refs/head.py +++ b/git/refs/head.py @@ -30,7 +30,7 @@ class HEAD(SymbolicReference): return SymbolicReference(self.repo, self._ORIG_HEAD_NAME) def reset(self, commit='HEAD', index=True, working_tree=False, - paths=None, **kwargs): + 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 commit as well. diff --git a/git/refs/log.py b/git/refs/log.py index 3bc42801..43441884 100644 --- a/git/refs/log.py +++ b/git/refs/log.py @@ -1,24 +1,24 @@ from git.util import ( - join_path, - Actor, - LockedFD, - LockFile, - assure_directory_exists, - to_native_path, - ) + join_path, + Actor, + LockedFD, + LockFile, + assure_directory_exists, + to_native_path, +) from gitdb.util import ( - bin_to_hex, - join, - file_contents_ro_filepath, - ) + bin_to_hex, + join, + file_contents_ro_filepath, +) from git.objects.util import ( - parse_date, - Serializable, - utctz_to_altz, - altz_to_utctz_str, - ) + parse_date, + Serializable, + utctz_to_altz, + altz_to_utctz_str, +) import time import os @@ -86,19 +86,19 @@ class RefLogEntry(tuple): info, msg = line.split('\t', 2) except ValueError: raise ValueError("line is missing tab separator") - #END handle first plit + # END handle first plit oldhexsha = info[:40] newhexsha = info[41:81] for hexsha in (oldhexsha, newhexsha): if not cls._re_hexsha_only.match(hexsha): raise ValueError("Invalid hexsha: %s" % hexsha) # END if hexsha re doesn't match - #END for each hexsha + # END for each hexsha email_end = info.find('>', 82) if email_end == -1: raise ValueError("Missing token: >") - #END handle missing end brace + # END handle missing end brace actor = Actor._from_string(info[82:email_end + 1]) time, tz_offset = parse_date(info[email_end + 2:]) @@ -136,13 +136,13 @@ class RefLog(list, Serializable): except OSError: # it is possible and allowed that the file doesn't exist ! return - #END handle invalid log + # END handle invalid log try: self._deserialize(fmap) finally: fmap.close() - #END handle closing of handle + # END handle closing of handle #{ Interface @@ -174,13 +174,13 @@ class RefLog(list, Serializable): new_entry = RefLogEntry.from_line if isinstance(stream, basestring): stream = file_contents_ro_filepath(stream) - #END handle stream type + # END handle stream type while True: line = stream.readline() if not line: return yield new_entry(line.strip()) - #END endless loop + # END endless loop @classmethod def entry_at(cls, filepath, index): @@ -204,15 +204,15 @@ class RefLog(list, Serializable): line = fp.readline() if not line: break - #END abort on eof - #END handle runup + # END abort on eof + # END handle runup if i != index or not line: raise IndexError - #END handle exception + # END handle exception return RefLogEntry.from_line(line.strip()) - #END handle index + # END handle index def to_file(self, filepath): """Write the contents of the reflog instance to a file at the given filepath. @@ -228,7 +228,7 @@ class RefLog(list, Serializable): # on failure it rolls back automatically, but we make it clear lfd.rollback() raise - #END handle change + # END handle change @classmethod def append_entry(cls, config_reader, filepath, oldbinsha, newbinsha, message): @@ -248,11 +248,12 @@ class RefLog(list, Serializable): do not interfere with readers.""" if len(oldbinsha) != 20 or len(newbinsha) != 20: raise ValueError("Shas need to be given in binary format") - #END handle sha type + # END handle sha type assure_directory_exists(filepath, is_file=True) committer = isinstance(config_reader, Actor) and config_reader or Actor.committer(config_reader) - entry = RefLogEntry((bin_to_hex(oldbinsha), bin_to_hex(newbinsha), committer, (int(time.time()), time.altzone), message)) - + entry = RefLogEntry( + (bin_to_hex(oldbinsha), bin_to_hex(newbinsha), committer, (int(time.time()), time.altzone), message)) + lf = LockFile(filepath) lf._obtain_lock_or_raise() @@ -262,7 +263,7 @@ class RefLog(list, Serializable): finally: fd.close() lf._release_lock() - #END handle write operation + # END handle write operation return entry @@ -271,7 +272,7 @@ class RefLog(list, Serializable): :return: self""" if self._path is None: raise ValueError("Instance was not initialized with a path, use to_file(...) instead") - #END assert path + # END assert path self.to_file(self._path) return self @@ -285,7 +286,7 @@ class RefLog(list, Serializable): # write all entries for e in self: write(repr(e)) - #END for each entry + # END for each entry def _deserialize(self, stream): self.extend(self.iter_entries(stream)) diff --git a/git/refs/reference.py b/git/refs/reference.py index 72494e0a..f71ded72 100644 --- a/git/refs/reference.py +++ b/git/refs/reference.py @@ -1,13 +1,13 @@ from symbolic import SymbolicReference from git.util import ( - LazyMixin, - Iterable, - ) + LazyMixin, + Iterable, +) from gitdb.util import ( - isfile, - hex_to_bin - ) + isfile, + hex_to_bin +) __all__ = ["Reference"] @@ -21,7 +21,7 @@ def require_remote_ref_path(func): if not self.is_remote(): raise ValueError("ref path does not point to a remote reference: %s" % self.path) return func(self, *args) - #END wrapper + # END wrapper wrapper.__name__ = func.__name__ return wrapper #}END utilites @@ -61,8 +61,8 @@ class Reference(SymbolicReference, LazyMixin, Iterable): head = self.repo.head if not head.is_detached and head.ref == self: oldbinsha = self.commit.binsha - #END handle commit retrieval - #END handle message is set + # END handle commit retrieval + # END handle message is set super(Reference, self).set_object(object, logmsg) @@ -80,7 +80,7 @@ class Reference(SymbolicReference, LazyMixin, Iterable): # * scenarios (even 100% of the default ones). # */ self.repo.head.log_append(oldbinsha, logmsg) - #END check if the head + # END check if the head # NOTE: Don't have to overwrite properties as the will only work without a the log diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index fcb1336e..1470c879 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -1,23 +1,23 @@ import os from git.objects import Object, Commit from git.util import ( - join_path, - join_path_native, - to_native_path_linux, - assure_directory_exists - ) + join_path, + join_path_native, + to_native_path_linux, + assure_directory_exists +) from gitdb.exc import BadObject from gitdb.util import ( - join, - dirname, - isdir, - exists, - isfile, - rename, - hex_to_bin, - LockedFD - ) + join, + dirname, + isdir, + exists, + isfile, + rename, + hex_to_bin, + LockedFD +) from log import RefLog @@ -135,7 +135,8 @@ class SymbolicReference(object): # NOTE: We are not a symbolic ref if we are in a packed file, as these # are excluded explictly for sha, path in cls._iter_packed_refs(repo): - if path != ref_path: continue + if path != ref_path: + continue tokens = (sha, path) break # END for each packed ref @@ -170,11 +171,11 @@ class SymbolicReference(object): obj = self._get_object() if obj.type == 'tag': obj = obj.object - #END dereference tag + # END dereference tag if obj.type != Commit.type: raise TypeError("Symbolic Reference pointed to object %r, commit was required" % obj) - #END handle type + # END handle type return obj def set_commit(self, commit, logmsg=None): @@ -194,12 +195,12 @@ class SymbolicReference(object): invalid_type = self.repo.rev_parse(commit).type != Commit.type except BadObject: raise ValueError("Invalid object: %s" % commit) - #END handle exception + # END handle exception # END verify type if invalid_type: raise ValueError("Need commit, got %r" % commit) - #END handle raise + # END handle raise # we leave strings to the rev-parse method below self.set_object(commit, logmsg) @@ -218,7 +219,7 @@ class SymbolicReference(object): :return: self""" if isinstance(object, SymbolicReference): object = object.object - #END resolve references + # END resolve references is_detached = True try: @@ -284,7 +285,7 @@ class SymbolicReference(object): # typecheck if obj is not None and self._points_to_commits_only and obj.type != Commit.type: raise TypeError("Require commit, got %r" % obj) - #END verify type + # END verify type oldbinsha = None if logmsg is not None: @@ -292,8 +293,8 @@ class SymbolicReference(object): oldbinsha = self.commit.binsha except ValueError: oldbinsha = Commit.NULL_BIN_SHA - #END handle non-existing - #END retrieve old hexsha + # END handle non-existing + # END retrieve old hexsha fpath = self.abspath assure_directory_exists(fpath, is_file=True) @@ -306,7 +307,7 @@ class SymbolicReference(object): # Adjust the reflog if logmsg is not None: self.log_append(oldbinsha, logmsg) - #END handle reflog + # END handle reflog return self @@ -355,7 +356,7 @@ class SymbolicReference(object): :param newbinsha: The sha the ref points to now. If None, our current commit sha will be used :return: added RefLogEntry instance""" - # NOTE: we use the committer of the currently active commit - this should be + # NOTE: we use the committer of the currently active commit - this should be # correct to allow overriding the committer on a per-commit level. # See https://github.com/gitpython-developers/GitPython/pull/146 try: @@ -363,9 +364,9 @@ class SymbolicReference(object): except ValueError: committer_or_reader = self.repo.config_reader() # end handle newly cloned repositories - return RefLog.append_entry(committer_or_reader, RefLog.path(self), oldbinsha, - (newbinsha is None and self.commit.binsha) or newbinsha, - message) + return RefLog.append_entry(committer_or_reader, RefLog.path(self), oldbinsha, + (newbinsha is None and self.commit.binsha) or newbinsha, + message) def log_entry(self, index): """:return: RefLogEntry at the given index @@ -422,7 +423,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 @@ -447,7 +448,7 @@ class SymbolicReference(object): reflog_path = RefLog.path(cls(repo, full_ref_path)) if os.path.isfile(reflog_path): os.remove(reflog_path) - #END remove reflog + # END remove reflog @classmethod def _create(cls, repo, path, resolve, reference, force, logmsg=None): @@ -472,7 +473,8 @@ class SymbolicReference(object): target_data = "ref: " + target_data existing_data = open(abs_ref_path, 'rb').read().strip() if existing_data != target_data: - raise OSError("Reference at %r does already exist, pointing to %r, requested was %r" % (full_ref_path, existing_data, target_data)) + raise OSError("Reference at %r does already exist, pointing to %r, requested was %r" % + (full_ref_path, existing_data, target_data)) # END no force handling ref = cls(repo, full_ref_path) diff --git a/git/remote.py b/git/remote.py index c1fc8078..bce11f7d 100644 --- a/git/remote.py +++ b/git/remote.py @@ -11,23 +11,23 @@ from ConfigParser import NoOptionError from config import SectionConstraint from git.util import ( - LazyMixin, - Iterable, - IterableList, - RemoteProgress - ) + LazyMixin, + Iterable, + IterableList, + RemoteProgress +) from refs import ( - Reference, - RemoteReference, - SymbolicReference, - TagReference - ) + Reference, + RemoteReference, + SymbolicReference, + TagReference +) from git.util import ( join_path, finalize_process - ) +) from gitdb.util import join import re @@ -72,8 +72,8 @@ def add_progress(kwargs, git, progress): v = git.version_info if v[0] > 1 or v[1] > 7 or v[2] > 0 or v[3] > 3: kwargs['progress'] = True - #END handle --progress - #END handle progress + # END handle --progress + # END handle progress return kwargs #} END utilities @@ -98,14 +98,14 @@ 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} + '+': FORCED_UPDATE, ' ': FAST_FORWARD, + '=': UP_TO_DATE, '!': ERROR} def __init__(self, flags, local_ref, remote_ref_string, remote, old_commit=None, - summary=''): + summary=''): """ Initialize a new instance """ self.flags = flags self.local_ref = local_ref @@ -199,13 +199,13 @@ class FetchInfo(object): __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} + '=': HEAD_UPTODATE, ' ': FAST_FORWARD} def __init__(self, ref, flags, note='', old_commit=None): """ @@ -274,7 +274,7 @@ class FetchInfo(object): ref_type = TagReference else: raise TypeError("Cannot handle reference type: %r" % ref_type_name) - #END handle ref type + # END handle ref type # create ref instance if ref_type is SymbolicReference: @@ -293,13 +293,13 @@ class FetchInfo(object): ref_path = remote_local_ref if ref_type is not TagReference and not remote_local_ref.startswith(RemoteReference._common_path_default + "/"): ref_type = Reference - #END downgrade remote reference + # END downgrade remote reference elif ref_type is TagReference and 'tags/' in remote_local_ref: # even though its a tag, it is located in refs/remotes ref_path = join_path(RemoteReference._common_path_default, remote_local_ref) else: ref_path = join_path(ref_type._common_path_default, remote_local_ref) - #END obtain refpath + # END obtain refpath # even though the path could be within the git conventions, we make # sure we respect whatever the user wanted, and disabled path checking @@ -490,7 +490,7 @@ class Remote(LazyMixin, Iterable): del(self._config_reader) # it contains cached values, section names are different now except AttributeError: pass - #END handle exception + # END handle exception return self def update(self, **kwargs): @@ -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 @@ -657,5 +657,5 @@ class Remote(LazyMixin, Iterable): del(self._config_reader) except AttributeError: pass - #END handle exception + # END handle exception return SectionConstraint(writer, self._config_section_name()) diff --git a/git/repo/base.py b/git/repo/base.py index 5273d4b2..174f29aa 100644 --- a/git/repo/base.py +++ b/git/repo/base.py @@ -9,35 +9,35 @@ from git.cmd import Git from git.util import ( Actor, finalize_process - ) +) from git.refs import * from git.index import IndexFile from git.objects import * from git.config import GitConfigParser from git.remote import ( - Remote, - digest_process_messages, - add_progress - ) + Remote, + digest_process_messages, + add_progress +) from git.db import ( - GitCmdObjectDB, - GitDB - ) + GitCmdObjectDB, + GitDB +) from gitdb.util import ( - join, - isfile, - hex_to_bin - ) + join, + isfile, + hex_to_bin +) from fun import ( - rev_parse, - is_git_dir, - find_git_dir, - read_gitfile, - touch, - ) + rev_parse, + is_git_dir, + find_git_dir, + read_gitfile, + touch, +) import os import sys @@ -53,6 +53,7 @@ __all__ = ('Repo', ) class Repo(object): + """Represents a git repository and allows you to query references, gather commit information, generate diffs, create and clone repositories query the log. @@ -488,7 +489,8 @@ class Repo(object): # END file handling # END alts handling - alternates = property(_get_alternates, _set_alternates, doc="Retrieve a list of alternates paths or set a list paths to be used as alternates") + alternates = property(_get_alternates, _set_alternates, + doc="Retrieve a list of alternates paths or set a list paths to be used as alternates") def is_dirty(self, index=True, working_tree=True, untracked_files=False): """ @@ -506,7 +508,7 @@ class Repo(object): if index: # diff index against HEAD if isfile(self.index.path) and \ - len(self.git.diff('--cached', *default_args)): + len(self.git.diff('--cached', *default_args)): return True # END index handling if working_tree: @@ -576,7 +578,8 @@ class Repo(object): if self.re_hexsha_only.search(firstpart): # handles # 634396b2f541a9f2d58b00be1a07f0c358b999b3 1 1 7 - indicates blame-data start - # 634396b2f541a9f2d58b00be1a07f0c358b999b3 2 2 - indicates another line of blame with the same data + # 634396b2f541a9f2d58b00be1a07f0c358b999b3 2 2 - indicates + # another line of blame with the same data digits = parts[-1].split(" ") if len(digits) == 3: info = {'id': firstpart} @@ -620,11 +623,12 @@ class Repo(object): c = commits.get(sha) if c is None: 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']), - committed_date=info['committer_date'], - message=info['summary']) + author=Actor._from_string(info['author'] + ' ' + info['author_email']), + authored_date=info['author_date'], + committer=Actor._from_string( + info['committer'] + ' ' + info['committer_email']), + committed_date=info['committer_date'], + message=info['summary']) commits[sha] = c # END if commit objects needs initial creation m = self.re_tab_full_line.search(line) @@ -693,10 +697,11 @@ class Repo(object): # END windows handling try: - proc = git.clone(url, path, with_extended_output=True, as_process=True, v=True, **add_progress(kwargs, git, progress)) + proc = git.clone(url, path, with_extended_output=True, as_process=True, + v=True, **add_progress(kwargs, git, progress)) if progress: digest_process_messages(proc.stderr, progress) - #END handle progress + # END handle progress finalize_process(proc) finally: if prev_cwd is not None: diff --git a/git/repo/fun.py b/git/repo/fun.py index 0bff677a..b8905517 100644 --- a/git/repo/fun.py +++ b/git/repo/fun.py @@ -4,16 +4,16 @@ from gitdb.exc import BadObject from git.refs import SymbolicReference from git.objects import Object from gitdb.util import ( - join, - isdir, - isfile, - dirname, - hex_to_bin, - bin_to_hex - ) + join, + isdir, + isfile, + dirname, + hex_to_bin, + bin_to_hex +) from string import digits -__all__ = ('rev_parse', 'is_git_dir', 'touch', 'read_gitfile', 'find_git_dir', 'name_to_object', +__all__ = ('rev_parse', 'is_git_dir', 'touch', 'read_gitfile', 'find_git_dir', 'name_to_object', 'short_to_long', 'deref_tag', 'to_commit') @@ -30,8 +30,8 @@ def is_git_dir(d): isdir(join(d, 'refs')): headref = join(d, 'HEAD') return isfile(headref) or \ - (os.path.islink(headref) and - os.readlink(headref).startswith('refs')) + (os.path.islink(headref) and + os.readlink(headref).startswith('refs')) return False @@ -46,13 +46,14 @@ def find_git_dir(d): return find_git_dir(d) return None + def read_gitfile(f): """ This is taken from the git setup.c:read_gitfile function. :return gitdir path or None if gitfile is invalid.""" if f is None: return None try: - line = open(f, 'r').readline().rstrip() + line = open(f, 'r').readline().rstrip() except (OSError, IOError): # File might not exist or is unreadable - ignore return None @@ -62,6 +63,7 @@ def read_gitfile(f): path = os.path.realpath(line[8:]) return path if is_git_dir(path) else None + def short_to_long(odb, hexsha): """:return: long hexadecimal sha1 from the given less-than-40 byte hexsha or None if no candidate could be found. @@ -90,7 +92,7 @@ def name_to_object(repo, name, return_ref=False): else: hexsha = name # END handle short shas - #END find sha if it matches + # END find sha if it matches # if we couldn't find an object for what seemed to be a short hexsha # try to find it as reference anyway, it could be named 'aaa' for instance @@ -100,7 +102,7 @@ def name_to_object(repo, name, return_ref=False): hexsha = SymbolicReference.dereference_recursive(repo, base % name) if return_ref: return SymbolicReference(repo, base % name) - #END handle symbolic ref + # END handle symbolic ref break except ValueError: pass @@ -110,7 +112,7 @@ def name_to_object(repo, name, return_ref=False): # didn't find any ref, this is an error if return_ref: raise BadObject("Couldn't find reference named %r" % name) - #END handle return ref + # END handle return ref # tried everything ? fail if hexsha is None: @@ -183,12 +185,12 @@ def rev_parse(repo, rev): ref = name_to_object(repo, rev[:start], return_ref=True) else: obj = name_to_object(repo, rev[:start]) - #END handle token - #END handle refname + # END handle token + # END handle refname if ref is not None: obj = ref.commit - #END handle ref + # END handle ref # END initialize obj on first token start += 1 @@ -227,13 +229,13 @@ def rev_parse(repo, rev): # TODO: Try to parse the other date options, using parse_date # maybe raise NotImplementedError("Support for additional @{...} modes not implemented") - #END handle revlog index + # END handle revlog index try: entry = ref.log_entry(revlog_index) except IndexError: raise IndexError("Invalid revlog index: %i" % revlog_index) - #END handle index out of bound + # END handle index out of bound obj = Object.new_from_sha(repo, hex_to_bin(entry.newhexsha)) diff --git a/git/test/lib/__init__.py b/git/test/lib/__init__.py index e13e227d..26ea13a3 100644 --- a/git/test/lib/__init__.py +++ b/git/test/lib/__init__.py @@ -10,4 +10,4 @@ from asserts import * from helper import * __all__ = [name for name, obj in locals().items() - if not (name.startswith('_') or inspect.ismodule(obj))] + if not (name.startswith('_') or inspect.ismodule(obj))] diff --git a/git/test/lib/helper.py b/git/test/lib/helper.py index 913cf3b6..55e7ba65 100644 --- a/git/test/lib/helper.py +++ b/git/test/lib/helper.py @@ -15,9 +15,9 @@ import cStringIO GIT_REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) __all__ = ( - 'fixture_path', 'fixture', 'absolute_project_path', 'StringProcessAdapter', - 'with_rw_repo', 'with_rw_and_rw_remote_repo', 'TestBase', 'TestCase', 'GIT_REPO' - ) + 'fixture_path', 'fixture', 'absolute_project_path', 'StringProcessAdapter', + 'with_rw_repo', 'with_rw_and_rw_remote_repo', 'TestBase', 'TestCase', 'GIT_REPO' +) #{ Routines @@ -95,7 +95,7 @@ def with_rw_repo(working_tree_ref, bare=False): prefix = 'non_' if bare: prefix = '' - #END handle prefix + # END handle prefix repo_dir = _mktemp("%sbare_%s" % (prefix, func.__name__)) rw_repo = self.rorepo.clone(repo_dir, shared=True, bare=bare, n=True) @@ -158,7 +158,8 @@ def with_rw_and_rw_remote_repo(working_tree_ref): repo_dir = _mktemp("remote_clone_non_bare_repo") rw_remote_repo = self.rorepo.clone(remote_repo_dir, shared=True, bare=True) - rw_repo = rw_remote_repo.clone(repo_dir, shared=True, bare=False, n=True) # recursive alternates info ? + # recursive alternates info ? + rw_repo = rw_remote_repo.clone(repo_dir, shared=True, bare=False, n=True) rw_repo.head.commit = working_tree_ref rw_repo.head.reference.checkout() @@ -191,11 +192,13 @@ def with_rw_and_rw_remote_repo(working_tree_ref): 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())) + raise AssertionError( + 'git-daemon needs to run this test, but windows does not have one. Otherwise, run: git-daemon "%s"' % os.path.dirname(_mktemp())) else: - raise AssertionError('Please start a git-daemon to run this test, execute: git-daemon "%s"' % os.path.dirname(_mktemp())) + raise AssertionError( + 'Please start a git-daemon to run this test, execute: git-daemon "%s"' % os.path.dirname(_mktemp())) # END make assertion - #END catch ls remote error + # END catch ls remote error # adjust working dir prev_cwd = os.getcwd() diff --git a/git/test/performance/lib.py b/git/test/performance/lib.py index 00d41b76..6beff617 100644 --- a/git/test/performance/lib.py +++ b/git/test/performance/lib.py @@ -5,13 +5,13 @@ import shutil import tempfile from git.db import ( - GitCmdObjectDB, - GitDB - ) + GitCmdObjectDB, + GitDB +) from git import ( Repo - ) +) #{ Invvariants k_env_git_repo = "GIT_PYTHON_TEST_GIT_REPO_BASE" diff --git a/git/test/performance/test_commit.py b/git/test/performance/test_commit.py index 009b3d82..c988d160 100644 --- a/git/test/performance/test_commit.py +++ b/git/test/performance/test_commit.py @@ -46,7 +46,8 @@ 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 @@ -84,9 +85,9 @@ class TestPerformance(TestBigRepoRW): st = time() for i in xrange(nc): 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) + 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) stream = StringIO() cm._serialize(stream) @@ -97,4 +98,5 @@ class TestPerformance(TestBigRepoRW): # END commit creation elapsed = time() - st - print >> sys.stderr, "Serialized %i commits to loose objects in %f s ( %f commits / s )" % (nc, elapsed, nc / elapsed) + print >> sys.stderr, "Serialized %i commits to loose objects in %f s ( %f commits / s )" % ( + nc, elapsed, nc / elapsed) diff --git a/git/test/performance/test_odb.py b/git/test/performance/test_odb.py index 5ddbbd53..6696e459 100644 --- a/git/test/performance/test_odb.py +++ b/git/test/performance/test_odb.py @@ -6,7 +6,7 @@ import stat from lib import ( TestBigRepoR - ) +) class TestObjDBPerformance(TestBigRepoR): @@ -21,7 +21,8 @@ class TestObjDBPerformance(TestBigRepoR): nc = len(commits) elapsed = time() - st - print >> sys.stderr, "%s: Retrieved %i commits from ObjectStore in %g s ( %f commits / s )" % (type(repo.odb), nc, elapsed, nc / elapsed) + print >> sys.stderr, "%s: Retrieved %i commits from ObjectStore in %g s ( %f commits / s )" % ( + type(repo.odb), nc, elapsed, nc / elapsed) results[0].append(elapsed) # GET TREES @@ -42,7 +43,8 @@ class TestObjDBPerformance(TestBigRepoR): # END for each commit elapsed = time() - st - print >> sys.stderr, "%s: Retrieved %i objects from %i commits in %g s ( %f objects / s )" % (type(repo.odb), nt, len(commits), elapsed, nt / elapsed) + print >> sys.stderr, "%s: Retrieved %i objects from %i commits in %g s ( %f objects / s )" % ( + type(repo.odb), nt, len(commits), elapsed, nt / elapsed) results[1].append(elapsed) # GET BLOBS @@ -60,7 +62,8 @@ 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 e42867a3..7800144d 100644 --- a/git/test/performance/test_streams.py +++ b/git/test/performance/test_streams.py @@ -14,7 +14,7 @@ from gitdb.test.lib import make_memory_file from lib import ( TestBigRepoR - ) +) class TestObjDBPerformance(TestBigRepoR): @@ -45,7 +45,8 @@ class TestObjDBPerformance(TestBigRepoR): fsize_kib = os.path.getsize(db_file) / 1000 size_kib = size / 1000 - print >> sys.stderr, "Added %i KiB (filesize = %i KiB) of %s data to loose odb in %f s ( %f Write KiB / s)" % (size_kib, fsize_kib, desc, elapsed_add, size_kib / elapsed_add) + print >> sys.stderr, "Added %i KiB (filesize = %i KiB) of %s data to loose odb in %f s ( %f Write KiB / s)" % ( + size_kib, fsize_kib, desc, elapsed_add, size_kib / elapsed_add) # reading all at once st = time() @@ -55,7 +56,8 @@ class TestObjDBPerformance(TestBigRepoR): stream.seek(0) assert shadata == stream.getvalue() - 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) + 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 @@ -74,7 +76,8 @@ class TestObjDBPerformance(TestBigRepoR): assert ''.join(chunks) == stream.getvalue() cs_kib = cs / 1000 - print >> sys.stderr, "Read %i KiB of %s data in %i KiB chunks from loose odb in %f s ( %f Read KiB / s)" % (size_kib, desc, cs_kib, elapsed_readchunks, size_kib / elapsed_readchunks) + print >> sys.stderr, "Read %i KiB of %s data in %i KiB chunks from loose odb in %f s ( %f Read KiB / s)" % ( + size_kib, desc, cs_kib, elapsed_readchunks, size_kib / elapsed_readchunks) # del db file so git has something to do os.remove(db_file) @@ -97,19 +100,23 @@ class TestObjDBPerformance(TestBigRepoR): # as its the same sha, we reuse our path fsize_kib = os.path.getsize(db_file) / 1000 - print >> sys.stderr, "Added %i KiB (filesize = %i KiB) of %s data to using git-hash-object in %f s ( %f Write KiB / s)" % (size_kib, fsize_kib, desc, gelapsed_add, size_kib / gelapsed_add) + print >> sys.stderr, "Added %i KiB (filesize = %i KiB) of %s data to using git-hash-object in %f s ( %f Write KiB / s)" % ( + size_kib, fsize_kib, desc, gelapsed_add, size_kib / gelapsed_add) # compare ... - print >> sys.stderr, "Git-Python is %f %% faster than git when adding big %s files" % (100.0 - (elapsed_add / gelapsed_add) * 100, desc) + print >> sys.stderr, "Git-Python is %f %% faster than git when adding big %s files" % ( + 100.0 - (elapsed_add / gelapsed_add) * 100, desc) # read all st = time() s, t, size, data = rwrepo.git.get_object_data(gitsha) gelapsed_readall = time() - st - print >> sys.stderr, "Read %i KiB of %s data at once using git-cat-file in %f s ( %f Read KiB / s)" % (size_kib, desc, gelapsed_readall, size_kib / gelapsed_readall) + print >> sys.stderr, "Read %i KiB of %s data at once using git-cat-file in %f s ( %f Read KiB / s)" % ( + size_kib, desc, gelapsed_readall, size_kib / gelapsed_readall) # compare - print >> sys.stderr, "Git-Python is %f %% faster than git when reading big %sfiles" % (100.0 - (elapsed_readall / gelapsed_readall) * 100, desc) + print >> sys.stderr, "Git-Python is %f %% faster than git when reading big %sfiles" % ( + 100.0 - (elapsed_readall / gelapsed_readall) * 100, desc) # read chunks st = time() @@ -120,8 +127,10 @@ class TestObjDBPerformance(TestBigRepoR): break # END read stream gelapsed_readchunks = time() - st - print >> sys.stderr, "Read %i KiB of %s data in %i KiB chunks from git-cat-file in %f s ( %f Read KiB / s)" % (size_kib, desc, cs_kib, gelapsed_readchunks, size_kib / gelapsed_readchunks) + print >> sys.stderr, "Read %i KiB of %s data in %i KiB chunks from git-cat-file in %f s ( %f Read KiB / s)" % ( + size_kib, desc, cs_kib, gelapsed_readchunks, size_kib / gelapsed_readchunks) # compare - print >> sys.stderr, "Git-Python is %f %% faster than git when reading big %s files in chunks" % (100.0 - (elapsed_readchunks / gelapsed_readchunks) * 100, desc) + print >> sys.stderr, "Git-Python is %f %% faster than git when reading big %s files in chunks" % ( + 100.0 - (elapsed_readchunks / gelapsed_readchunks) * 100, desc) # END for each randomization factor diff --git a/git/test/performance/test_utils.py b/git/test/performance/test_utils.py index c8d397fb..7db972f7 100644 --- a/git/test/performance/test_utils.py +++ b/git/test/performance/test_utils.py @@ -5,7 +5,7 @@ import stat from lib import ( TestBigRepoR - ) +) class TestUtilPerformance(TestBigRepoR): @@ -44,7 +44,8 @@ class TestUtilPerformance(TestBigRepoR): cli.attr # END for each access elapsed = time() - st - print >> sys.stderr, "Accessed %s.attr %i times in %s s ( %f acc / s)" % (cls.__name__, ni, elapsed, ni / elapsed) + print >> sys.stderr, "Accessed %s.attr %i times in %s s ( %f acc / s)" % ( + cls.__name__, ni, elapsed, ni / elapsed) # END for each class type # check num of sequence-acceses @@ -59,7 +60,8 @@ class TestUtilPerformance(TestBigRepoR): # END for elapsed = time() - st na = ni * 3 - print >> sys.stderr, "Accessed %s[x] %i times in %s s ( %f acc / s)" % (cls.__name__, na, elapsed, na / elapsed) + print >> sys.stderr, "Accessed %s[x] %i times in %s s ( %f acc / s)" % ( + cls.__name__, na, elapsed, na / elapsed) # END for each sequence def test_instantiation(self): @@ -84,7 +86,8 @@ class TestUtilPerformance(TestBigRepoR): # END handle empty cls # END for each item elapsed = time() - st - print >> sys.stderr, "Created %i %ss of size %i in %f s ( %f inst / s)" % (ni, cls.__name__, mni, elapsed, ni / elapsed) + print >> sys.stderr, "Created %i %ss of size %i in %f s ( %f inst / s)" % ( + ni, cls.__name__, mni, elapsed, ni / elapsed) # END for each type # END for each item count @@ -114,21 +117,24 @@ class TestUtilPerformance(TestBigRepoR): one, two, three, four = sequence # END for eac iteration elapsed = time() - st - print >> sys.stderr, "Unpacked %i %ss of size %i in %f s ( %f acc / s)" % (ni, type(sequence).__name__, len(sequence), elapsed, ni / elapsed) + print >> sys.stderr, "Unpacked %i %ss of size %i in %f s ( %f acc / s)" % ( + ni, type(sequence).__name__, len(sequence), elapsed, ni / elapsed) st = time() for i in xrange(ni): one, two, three, four = sequence[0], sequence[1], sequence[2], sequence[3] # END for eac iteration elapsed = time() - st - print >> sys.stderr, "Unpacked %i %ss of size %i individually in %f s ( %f acc / s)" % (ni, type(sequence).__name__, len(sequence), elapsed, ni / elapsed) + print >> sys.stderr, "Unpacked %i %ss of size %i individually in %f s ( %f acc / s)" % ( + ni, type(sequence).__name__, len(sequence), elapsed, ni / elapsed) st = time() for i in xrange(ni): one, two = sequence[0], sequence[1] # END for eac iteration elapsed = time() - st - print >> sys.stderr, "Unpacked %i %ss of size %i individually (2 of 4) in %f s ( %f acc / s)" % (ni, type(sequence).__name__, len(sequence), elapsed, ni / elapsed) + print >> sys.stderr, "Unpacked %i %ss of size %i individually (2 of 4) in %f s ( %f acc / s)" % ( + ni, type(sequence).__name__, len(sequence), elapsed, ni / elapsed) # END for each sequence def test_large_list_vs_iteration(self): @@ -168,7 +174,8 @@ class TestUtilPerformance(TestBigRepoR): inst.__class__() # END for each item elapsed = time() - st - print >> sys.stderr, "Created %i items using inst.__class__ in %f s ( %f items / s)" % (ni, elapsed, ni / elapsed) + print >> sys.stderr, "Created %i items using inst.__class__ in %f s ( %f items / s)" % ( + ni, elapsed, ni / elapsed) st = time() for i in xrange(ni): diff --git a/git/test/test_base.py b/git/test/test_base.py index 81e785ab..d1b57984 100644 --- a/git/test/test_base.py +++ b/git/test/test_base.py @@ -19,9 +19,9 @@ import tempfile class TestBase(TestBase): type_tuples = (("blob", "8741fc1d09d61f02ffd8cded15ff603eff1ec070", "blob.py"), - ("tree", "3a6a5e3eeed3723c09f1ef0399f81ed6b8d82e79", "directory"), - ("commit", "4251bd59fb8e11e40c40548cba38180a9536118c", None), - ("tag", "e56a60e8e9cd333cfba0140a77cd12b0d9398f10", None)) + ("tree", "3a6a5e3eeed3723c09f1ef0399f81ed6b8d82e79", "directory"), + ("commit", "4251bd59fb8e11e40c40548cba38180a9536118c", None), + ("tag", "e56a60e8e9cd333cfba0140a77cd12b0d9398f10", None)) def test_base_object(self): # test interface of base object classes diff --git a/git/test/test_commit.py b/git/test/test_commit.py index 6cd892f0..22a302c6 100644 --- a/git/test/test_commit.py +++ b/git/test/test_commit.py @@ -39,9 +39,9 @@ def assert_commit_serialization(rwrepo, commit_id, print_performance_info=False) assert istream.hexsha == cm.hexsha nc = Commit(rwrepo, Commit.NULL_BIN_SHA, cm.tree, - cm.author, cm.authored_date, cm.author_tz_offset, - cm.committer, cm.committed_date, cm.committer_tz_offset, - cm.message, cm.parents, cm.encoding) + cm.author, cm.authored_date, cm.author_tz_offset, + cm.committer, cm.committed_date, cm.committer_tz_offset, + cm.message, cm.parents, cm.encoding) assert nc.parents == cm.parents stream = StringIO() @@ -62,7 +62,8 @@ 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 @@ -191,8 +192,8 @@ class TestCommit(TestBase): in the commit header. This test ensures that we properly parse it. """ revs = self.rorepo.git.rev_list('933d23bf95a5bd1624fbcdf328d904e1fa173474', - first_parent=True, - bisect_all=True) + first_parent=True, + bisect_all=True) commits = Commit._iter_from_process_or_stream(self.rorepo, StringProcessAdapter(revs)) expected_ids = ( @@ -208,7 +209,8 @@ class TestCommit(TestBase): 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) + assert isinstance(Commit.list_items(self.rorepo, '0.1.5', max_count=5)[ + hex_to_bin('5117c9c8a4d3af19a9958677e45cda9269de1541')], Commit) def test_str(self): commit = Commit(self.rorepo, Commit.NULL_BIN_SHA) diff --git a/git/test/test_config.py b/git/test/test_config.py index b6888023..0e5396a3 100644 --- a/git/test/test_config.py +++ b/git/test/test_config.py @@ -59,7 +59,7 @@ class TestBase(TestCase): file_obj.seek(0) r_config = GitConfigParser(file_obj, read_only=True) - #print file_obj.getvalue() + # print file_obj.getvalue() assert r_config.has_section(sname) assert r_config.has_option(sname, oname) assert r_config.get(sname, oname) == val diff --git a/git/test/test_fun.py b/git/test/test_fun.py index 4672901c..5fa0c77b 100644 --- a/git/test/test_fun.py +++ b/git/test/test_fun.py @@ -1,24 +1,24 @@ from git.test.lib import * from git.objects.fun import ( - traverse_tree_recursive, - traverse_trees_recursive, - tree_to_stream, - tree_entries_from_data - ) + traverse_tree_recursive, + traverse_trees_recursive, + tree_to_stream, + tree_entries_from_data +) from git.index.fun import ( - aggressive_tree_merge - ) + aggressive_tree_merge +) from gitdb.util import bin_to_hex from gitdb.base import IStream from gitdb.typ import str_tree_type from stat import ( - S_IFDIR, - S_IFREG, - S_IFLNK - ) + S_IFDIR, + S_IFREG, + S_IFLNK +) from git.index import IndexFile from cStringIO import StringIO diff --git a/git/test/test_git.py b/git/test/test_git.py index 063a4d38..759d4d44 100644 --- a/git/test/test_git.py +++ b/git/test/test_git.py @@ -7,14 +7,14 @@ import os import mock from git.test.lib import (TestBase, - patch, - raises, - assert_equal, - assert_true, - assert_match, - fixture_path) + patch, + raises, + assert_equal, + assert_true, + assert_match, + fixture_path) from git import (Git, - GitCommandError) + GitCommandError) class TestGit(TestBase): @@ -104,17 +104,18 @@ class TestGit(TestBase): assert isinstance(v, tuple) for n in v: assert isinstance(n, int) - #END verify number types + # END verify number types def test_cmd_override(self): prev_cmd = self.git.GIT_PYTHON_GIT_EXECUTABLE try: # set it to something that doens't exist, assure it raises - type(self.git).GIT_PYTHON_GIT_EXECUTABLE = os.path.join("some", "path", "which", "doesn't", "exist", "gitbinary") + type(self.git).GIT_PYTHON_GIT_EXECUTABLE = os.path.join( + "some", "path", "which", "doesn't", "exist", "gitbinary") self.failUnlessRaises(OSError, self.git.version) finally: type(self.git).GIT_PYTHON_GIT_EXECUTABLE = prev_cmd - #END undo adjustment + # END undo adjustment def test_options_are_passed_to_git(self): # This work because any command after git --version is ignored diff --git a/git/test/test_index.py b/git/test/test_index.py index 3440c5be..c1153e5e 100644 --- a/git/test/test_index.py +++ b/git/test/test_index.py @@ -19,6 +19,7 @@ from gitdb.base import IStream from git.objects import Blob from git.index.typ import BaseIndexEntry + class TestIndex(TestBase): def __init__(self, *args): @@ -68,7 +69,7 @@ class TestIndex(TestBase): last_val = None entry = index.entries.itervalues().next() for attr in ("path", "ctime", "mtime", "dev", "inode", "mode", "uid", - "gid", "size", "binsha", "hexsha", "stage"): + "gid", "size", "binsha", "hexsha", "stage"): val = getattr(entry, attr) # END for each method @@ -104,7 +105,8 @@ class TestIndex(TestBase): 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') @@ -457,7 +459,8 @@ 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 @@ -478,12 +481,14 @@ class TestIndex(TestBase): # 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" new_file_path = self._make_file(new_file_relapath, "hello world", rw_repo) - entries = index.reset(new_commit).add([BaseIndexEntry((010644, null_bin_sha, 0, new_file_relapath))], fprogress=self._fprogress_add) + entries = index.reset(new_commit).add( + [BaseIndexEntry((010644, null_bin_sha, 0, new_file_relapath))], fprogress=self._fprogress_add) self._assert_entries(entries) self._assert_fprogress(entries) assert len(entries) == 1 and entries[0].hexsha != null_hex_sha @@ -678,7 +683,7 @@ class TestIndex(TestBase): fileobj = StringIO(contents) filename = 'my-imaginary-file' istream = rw_bare_repo.odb.store( - IStream(Blob.type, filesize, fileobj)) + IStream(Blob.type, filesize, fileobj)) entry = BaseIndexEntry((100644, istream.binsha, 0, filename)) try: rw_bare_repo.index.add([entry]) @@ -693,5 +698,3 @@ class TestIndex(TestBase): except Exception, e: asserted = "does not have a working tree" in e.message assert asserted, "Adding using a filename is not correctly asserted." - - diff --git a/git/test/test_reflog.py b/git/test/test_reflog.py index fec50095..c281aa44 100644 --- a/git/test/test_reflog.py +++ b/git/test/test_reflog.py @@ -53,7 +53,7 @@ class TestRefLog(TestBase): pp = 'reflog_invalid_' for suffix in ('oldsha', 'newsha', 'email', 'date', 'sep'): self.failUnlessRaises(ValueError, RefLog.from_file, fixture_path(pp + suffix)) - #END for each invalid file + # END for each invalid file # cannot write an uninitialized reflog self.failUnlessRaises(ValueError, RefLog().write) @@ -93,7 +93,7 @@ class TestRefLog(TestBase): # ... and negative for idx in (-1, -24): RefLog.entry_at(rlp, idx) - #END for each index to read + # END for each index to read # END for each reflog # finally remove our temporary data diff --git a/git/test/test_refs.py b/git/test/test_refs.py index ee9d8074..c4f7077b 100644 --- a/git/test/test_refs.py +++ b/git/test/test_refs.py @@ -297,7 +297,7 @@ class TestRefs(TestBase): if remote_head_name in refs: RemoteReference.delete(rw_repo, refs[remote_head_name]) del(refs[remote_head_name]) - #END handle HEAD deletion + # END handle HEAD deletion RemoteReference.delete(rw_repo, *refs) remote_refs_so_far += len(refs) diff --git a/git/test/test_remote.py b/git/test/test_remote.py index a5a73ce1..254ad923 100644 --- a/git/test/test_remote.py +++ b/git/test/test_remote.py @@ -118,10 +118,11 @@ class TestRemote(TestBase): def _do_test_fetch_info(self, repo): self.failUnlessRaises(ValueError, FetchInfo._from_line, repo, "nonsense", '') - self.failUnlessRaises(ValueError, FetchInfo._from_line, repo, "? [up to date] 0.1.7RC -> origin/0.1.7RC", '') + self.failUnlessRaises( + ValueError, FetchInfo._from_line, repo, "? [up to date] 0.1.7RC -> origin/0.1.7RC", '') def _commit_random_file(self, repo): - #Create a file with a random name and random data and commit it to repo. + # 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) @@ -449,8 +450,8 @@ class TestRemote(TestBase): fetch_info_line_fmt = "c437ee5deb8d00cf02f03720693e4c802e99f390 not-for-merge %s '0.3' of git://github.com/gitpython-developers/GitPython" remote_info_line_fmt = "* [new branch] nomatter -> %s" fi = FetchInfo._from_line(self.rorepo, - remote_info_line_fmt % "local/master", - fetch_info_line_fmt % 'remote-tracking branch') + remote_info_line_fmt % "local/master", + fetch_info_line_fmt % 'remote-tracking branch') assert fi.ref.is_valid() assert fi.ref.commit @@ -458,16 +459,16 @@ class TestRemote(TestBase): # or a special path just in refs/something for instance fi = FetchInfo._from_line(self.rorepo, - remote_info_line_fmt % "subdir/tagname", - fetch_info_line_fmt % 'tag') + remote_info_line_fmt % "subdir/tagname", + fetch_info_line_fmt % 'tag') assert isinstance(fi.ref, TagReference) assert fi.ref.path.startswith('refs/tags') # it could be in a remote direcftory though fi = FetchInfo._from_line(self.rorepo, - remote_info_line_fmt % "remotename/tags/tagname", - fetch_info_line_fmt % 'tag') + remote_info_line_fmt % "remotename/tags/tagname", + fetch_info_line_fmt % 'tag') assert isinstance(fi.ref, TagReference) assert fi.ref.path.startswith('refs/remotes/') @@ -475,24 +476,24 @@ class TestRemote(TestBase): # it can also be anywhere ! tag_path = "refs/something/remotename/tags/tagname" fi = FetchInfo._from_line(self.rorepo, - remote_info_line_fmt % tag_path, - fetch_info_line_fmt % 'tag') + remote_info_line_fmt % tag_path, + fetch_info_line_fmt % 'tag') assert isinstance(fi.ref, TagReference) assert fi.ref.path == tag_path # branches default to refs/remotes fi = FetchInfo._from_line(self.rorepo, - remote_info_line_fmt % "remotename/branch", - fetch_info_line_fmt % 'branch') + remote_info_line_fmt % "remotename/branch", + fetch_info_line_fmt % 'branch') assert isinstance(fi.ref, RemoteReference) assert fi.ref.remote_name == 'remotename' # but you can force it anywhere, in which case we only have a references fi = FetchInfo._from_line(self.rorepo, - remote_info_line_fmt % "refs/something/branch", - fetch_info_line_fmt % 'branch') + remote_info_line_fmt % "refs/something/branch", + fetch_info_line_fmt % 'branch') assert type(fi.ref) is Reference assert fi.ref.path == "refs/something/branch" diff --git a/git/test/test_repo.py b/git/test/test_repo.py index 83bcdcbe..2cef4081 100644 --- a/git/test/test_repo.py +++ b/git/test/test_repo.py @@ -17,13 +17,15 @@ from git.util import join_path_native from git.exc import BadObject from gitdb.util import hex_to_bin, bin_to_hex -import os, sys +import os +import sys import tempfile import shutil from cStringIO import StringIO class TestRepo(TestBase): + @raises(InvalidGitRepositoryError) def test_new_should_raise_on_invalid_repo_location(self): Repo(tempfile.gettempdir()) @@ -276,16 +278,16 @@ class TestRepo(TestBase): def test_blame_real(self): c = 0 for item in self.rorepo.head.commit.tree.traverse( - predicate=lambda i, d: i.type == 'blob' and i.path.endswith('.py')): + predicate=lambda i, d: i.type == 'blob' and i.path.endswith('.py')): c += 1 b = self.rorepo.blame(self.rorepo.head, item.path) - #END for each item to traverse + # END for each item to traverse assert c 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")) + join_path_native(base, "__test_other_file")) num_recently_untracked = 0 try: for fpath in files: @@ -577,7 +579,7 @@ class TestRepo(TestBase): # all additional specs work as well assert rev_parse(refspec + "^{tree}") == head.commit.tree assert rev_parse(refspec + ":CHANGES").type == 'blob' - #END operate on non-detached head + # END operate on non-detached head # the last position assert rev_parse('@{1}') != head.commit @@ -622,11 +624,11 @@ class TestRepo(TestBase): os.rename(rwrepo.git_dir, real_path_abs) git_file_path = join_path_native(rwrepo.working_tree_dir, '.git') open(git_file_path, 'wb').write(fixture('git_file')) - + # Create a repo and make sure it's pointing to the relocated .git directory. git_file_repo = Repo(rwrepo.working_tree_dir) assert os.path.abspath(git_file_repo.git_dir) == real_path_abs - + # Test using an absolute gitdir path in the .git file. open(git_file_path, 'wb').write('gitdir: %s\n' % real_path_abs) git_file_repo = Repo(rwrepo.working_tree_dir) diff --git a/git/test/test_submodule.py b/git/test/test_submodule.py index 0ecb5c1f..69640e3c 100644 --- a/git/test/test_submodule.py +++ b/git/test/test_submodule.py @@ -20,8 +20,9 @@ if sys.platform == 'win32': smmap.util.MapRegion._test_read_into_memory = True except ImportError: sys.stderr.write("The submodule tests will fail as some files cannot be removed due to open file handles.\n") - sys.stderr.write("The latest version of gitdb uses a memory map manager which can be configured to work around this problem") -#END handle windows platform + sys.stderr.write( + "The latest version of gitdb uses a memory map manager which can be configured to work around this problem") +# END handle windows platform class TestRootProgress(RootUpdateProgress): @@ -425,7 +426,8 @@ class TestSubmodule(TestBase): assert not sm.module_exists() # was never updated after rwrepo's clone # assure we clone from a local source - sm.config_writer().set_value('url', to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, sm.path))) + sm.config_writer().set_value( + 'url', to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, sm.path))) # dry-run does nothing sm.update(recursive=False, dry_run=True, progress=prog) @@ -535,7 +537,7 @@ class TestSubmodule(TestBase): assert nsmmh.ref.tracking_branch() is None # never set it up until now assert not nsmmh.is_detached - #dry run does nothing + # dry run does nothing rm.update(recursive=False, dry_run=True, progress=prog) assert nsmmh.ref.tracking_branch() is None diff --git a/git/test/test_tree.py b/git/test/test_tree.py index 0f1fb7c3..2c740f1a 100644 --- a/git/test/test_tree.py +++ b/git/test/test_tree.py @@ -8,9 +8,9 @@ import os from git.test.lib import * from git import * from git.objects.fun import ( - traverse_tree_recursive, - traverse_trees_recursive - ) + traverse_tree_recursive, + traverse_trees_recursive +) from cStringIO import StringIO diff --git a/git/test/test_util.py b/git/test/test_util.py index 63842d19..d8682030 100644 --- a/git/test/test_util.py +++ b/git/test/test_util.py @@ -116,7 +116,7 @@ class TestUtils(TestBase): for cr in (None, self.rorepo.config_reader()): assert isinstance(Actor.committer(cr), Actor) assert isinstance(Actor.author(cr), Actor) - #END assure config reader is handled + # END assure config reader is handled def test_iterable_list(self): for args in (('name',), ('name', 'prefix_')): @@ -163,4 +163,4 @@ class TestUtils(TestBase): self.failUnlessRaises(IndexError, l.__delitem__, 0) self.failUnlessRaises(IndexError, l.__delitem__, 'something') - #END for each possible mode + # END for each possible mode diff --git a/git/util.py b/git/util.py index f6aa34e2..0408e384 100644 --- a/git/util.py +++ b/git/util.py @@ -27,9 +27,9 @@ from gitdb.util import ( ) __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') + "join_path_native", "Stats", "IndexFileSHA1Writer", "Iterable", "IterableList", + "BlockingLockFile", "LockFile", 'Actor', 'get_user_id', 'assure_directory_exists', + 'RemoteProgress', 'rmtree') #{ Utility Methods @@ -114,7 +114,7 @@ def assure_directory_exists(path, is_file=False): :return: True if the directory was created, False if it already existed""" if is_file: path = os.path.dirname(path) - #END handle file + # END handle file if not os.path.isdir(path): os.makedirs(path) return True @@ -348,17 +348,17 @@ class Actor(object): default_name = default_email.split('@')[0] for attr, evar, cvar, default in (('name', env_name, cls.conf_name, default_name), - ('email', env_email, cls.conf_email, default_email)): + ('email', env_email, cls.conf_email, default_email)): try: setattr(actor, attr, os.environ[evar]) except KeyError: if config_reader is not None: setattr(actor, attr, config_reader.get_value('user', cvar, default)) - #END config-reader handling + # END config-reader handling if not getattr(actor, attr): setattr(actor, attr, default) - #END handle name - #END for each item to retrieve + # END handle name + # END for each item to retrieve return actor @classmethod @@ -501,7 +501,8 @@ class LockFile(object): return lock_file = self._lock_file_path() if os.path.isfile(lock_file): - raise IOError("Lock for file %r did already exist, delete %r in case the lock is illegal" % (self._file_path, lock_file)) + raise IOError("Lock for file %r did already exist, delete %r in case the lock is illegal" % + (self._file_path, lock_file)) try: fd = os.open(lock_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0) @@ -572,7 +573,8 @@ class BlockingLockFile(LockFile): # readable anymore, raise an execption curtime = time.time() if not os.path.isdir(os.path.dirname(self._lock_file_path())): - msg = "Directory containing the lockfile %r was not readable anymore after waiting %g seconds" % (self._lock_file_path(), curtime - starttime) + msg = "Directory containing the lockfile %r was not readable anymore after waiting %g seconds" % ( + self._lock_file_path(), curtime - starttime) raise IOError(msg) # END handle missing directory @@ -616,7 +618,7 @@ class IterableList(list): rval = list.__contains__(self, attr) if rval: return rval - #END handle match + # END handle match # otherwise make a full name search try: @@ -624,7 +626,7 @@ class IterableList(list): return True except (AttributeError, TypeError): return False - #END handle membership + # END handle membership def __getattr__(self, attr): attr = self._prefix + attr @@ -653,12 +655,12 @@ class IterableList(list): if getattr(item, self._id_attr) == name: delindex = i break - #END search index - #END for each item + # END search index + # END for each item if delindex == -1: raise IndexError("Item with name %s not found" % name) - #END handle error - #END get index to delete + # END handle error + # END get index to delete list.__delitem__(self, delindex) |