diff --git a/git/__init__.py b/git/__init__.py index 0658c3306..ac8c098d2 100644 --- a/git/__init__.py +++ b/git/__init__.py @@ -49,6 +49,6 @@ def _init_externals(): #} END imports -__all__ = [ name for name, obj in locals().items() +__all__ = [ name for name, obj in list(locals().items()) if not (name.startswith('_') or inspect.ismodule(obj)) ] diff --git a/git/cmd.py b/git/cmd.py index 576a5300a..76a61a6bd 100644 --- a/git/cmd.py +++ b/git/cmd.py @@ -5,11 +5,11 @@ # the BSD License: http://www.opensource.org/licenses/bsd-license.php import os, sys -from util import ( +from .util import ( LazyMixin, stream_copy ) -from exc import GitCommandError +from .exc import GitCommandError from subprocess import ( call, @@ -192,7 +192,7 @@ def readlines(self, size=-1): def __iter__(self): return self - def next(self): + def __next__(self): line = self.readline() if not line: raise StopIteration @@ -321,7 +321,7 @@ def execute(self, command, If you add additional keyword arguments to the signature of this method, you must update the execute_kwargs tuple housed in this module.""" if self.GIT_PYTHON_TRACE and not self.GIT_PYTHON_TRACE == 'full': - print ' '.join(command) + print(' '.join(command)) # Allow the user to have the command executed in their working dir. if with_keep_cwd or self._working_dir is None: @@ -370,11 +370,11 @@ def execute(self, command, if self.GIT_PYTHON_TRACE == 'full': cmdstr = " ".join(command) if stderr_value: - print "%s -> %d; stdout: '%s'; stderr: '%s'" % (cmdstr, status, stdout_value, stderr_value) + print("%s -> %d; stdout: '%s'; stderr: '%s'" % (cmdstr, status, stdout_value, stderr_value)) elif stdout_value: - print "%s -> %d; stdout: '%s'" % (cmdstr, status, stdout_value) + print("%s -> %d; stdout: '%s'" % (cmdstr, status, stdout_value)) else: - print "%s -> %d" % (cmdstr, status) + print("%s -> %d" % (cmdstr, status)) # END handle debug printing if with_exceptions and status != 0: @@ -389,7 +389,7 @@ def execute(self, command, def transform_kwargs(self, **kwargs): """Transforms Python style kwargs into git command line options.""" args = list() - for k, v in kwargs.items(): + for k, v in list(kwargs.items()): if len(k) == 1: if v is True: args.append("-%s" % k) diff --git a/git/config.py b/git/config.py index c71bb8ca4..3ec4de794 100644 --- a/git/config.py +++ b/git/config.py @@ -8,9 +8,9 @@ import re import os -import ConfigParser as cp +import configparser as cp import inspect -import cStringIO +import io from git.odict import OrderedDict from git.util import LockFile @@ -97,7 +97,7 @@ def config(self): return self._config -class GitConfigParser(cp.RawConfigParser, object): +class GitConfigParser(cp.RawConfigParser, object, metaclass=MetaParserBuilder): """Implements specifics required to read git style configuration files. This variation behaves much like the git.config command such that the configuration @@ -112,7 +112,6 @@ class GitConfigParser(cp.RawConfigParser, object): :note: The config is case-sensitive even when queried, hence section and option names must match perfectly.""" - __metaclass__ = MetaParserBuilder #{ Configuration @@ -163,7 +162,7 @@ def __init__(self, file_or_files, read_only=True): 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): + if not isinstance(file_or_files, str): file_or_files = file_or_files.name # END get filename from handle/stream # initialize lock base - we want to write @@ -183,8 +182,8 @@ def __del__(self): try: try: self.write() - except IOError,e: - print "Exception during destruction of GitConfigParser: %s" % str(e) + except IOError as e: + print("Exception during destruction of GitConfigParser: %s" % str(e)) finally: self._lock._release_lock() @@ -283,7 +282,7 @@ def read(self): try: fp = open(file_object) close_fp = True - except IOError,e: + except IOError as e: continue # END fp handling @@ -301,7 +300,7 @@ def _write(self, fp): git compatible format""" def write_section(name, section_dict): fp.write("[%s]\n" % name) - for (key, value) in section_dict.items(): + for (key, value) in list(section_dict.items()): if key != "__name__": fp.write("\t%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) # END if key is not __name__ @@ -309,7 +308,7 @@ def write_section(name, section_dict): if self._defaults: write_section(cp.DEFAULTSECT, self._defaults) - map(lambda t: write_section(t[0],t[1]), self._sections.items()) + list(map(lambda t: write_section(t[0],t[1]), list(self._sections.items()))) @needs_values @@ -324,7 +323,7 @@ def write(self): close_fp = False # we have a physical file on disk, so get a lock - if isinstance(fp, (basestring, file)): + if isinstance(fp, (str, file)): self._lock._obtain_lock() # END get lock for physical files @@ -382,7 +381,7 @@ def get_value(self, section, option, default = None): return default raise - types = ( long, float ) + types = ( int, float ) for numtype in types: try: val = numtype( valuestr ) @@ -403,7 +402,7 @@ def get_value(self, section, option, default = None): if vl == 'true': return True - if not isinstance( valuestr, basestring ): + if not isinstance( valuestr, str ): raise TypeError( "Invalid value type: only int, long, float and str are allowed", valuestr ) return valuestr diff --git a/git/db.py b/git/db.py index b1c653779..fb2188816 100644 --- a/git/db.py +++ b/git/db.py @@ -1,5 +1,5 @@ """Module with our own gitdb implementation - it uses the git command""" -from exc import ( +from .exc import ( GitCommandError, BadObject ) diff --git a/git/diff.py b/git/diff.py index 7b3bf6b59..786e0e612 100644 --- a/git/diff.py +++ b/git/diff.py @@ -5,9 +5,9 @@ # the BSD License: http://www.opensource.org/licenses/bsd-license.php import re -from objects.blob import Blob -from objects.util import mode_str_to_int -from exc import GitCommandError +from .objects.blob import Blob +from .objects.util import mode_str_to_int +from .exc import GitCommandError from gitdb.util import hex_to_bin diff --git a/git/odict.py b/git/odict.py index 2c8391d78..802622f80 100644 --- a/git/odict.py +++ b/git/odict.py @@ -15,7 +15,7 @@ # Comments, suggestions and bug reports welcome. """A dict that keeps keys in insertion order""" -from __future__ import generators + __author__ = ('Nicola Larosa ,' 'Michael Foord ') @@ -116,7 +116,7 @@ def __init__(self, init_val=(), strict=False): self.strict = strict dict.__init__(self) if isinstance(init_val, OrderedDict): - self._sequence = init_val.keys() + self._sequence = list(init_val.keys()) dict.update(self, init_val) elif isinstance(init_val, dict): # we lose compatibility with other ordered dict types this way @@ -143,7 +143,7 @@ def __delitem__(self, key): >>> d OrderedDict([(2, 1), (3, 2)]) """ - if isinstance(key, types.SliceType): + if isinstance(key, slice): # FIXME: efficiency? keys = self._sequence[key] for entry in keys: @@ -174,7 +174,7 @@ def __eq__(self, other): if isinstance(other, OrderedDict): # FIXME: efficiency? # Generate both item lists for each compare - return (self.items() == other.items()) + return (list(self.items()) == list(other.items())) else: return False @@ -194,7 +194,7 @@ def __lt__(self, other): raise TypeError('Can only compare with other OrderedDicts') # FIXME: efficiency? # Generate both item lists for each compare - return (self.items() < other.items()) + return (list(self.items()) < list(other.items())) def __le__(self, other): """ @@ -215,7 +215,7 @@ def __le__(self, other): raise TypeError('Can only compare with other OrderedDicts') # FIXME: efficiency? # Generate both item lists for each compare - return (self.items() <= other.items()) + return (list(self.items()) <= list(other.items())) def __ne__(self, other): """ @@ -236,7 +236,7 @@ def __ne__(self, other): if isinstance(other, OrderedDict): # FIXME: efficiency? # Generate both item lists for each compare - return not (self.items() == other.items()) + return not (list(self.items()) == list(other.items())) else: return True @@ -256,7 +256,7 @@ def __gt__(self, other): raise TypeError('Can only compare with other OrderedDicts') # FIXME: efficiency? # Generate both item lists for each compare - return (self.items() > other.items()) + return (list(self.items()) > list(other.items())) def __ge__(self, other): """ @@ -277,7 +277,7 @@ def __ge__(self, other): raise TypeError('Can only compare with other OrderedDicts') # FIXME: efficiency? # Generate both item lists for each compare - return (self.items() >= other.items()) + return (list(self.items()) >= list(other.items())) def __repr__(self): """ @@ -355,13 +355,13 @@ def __setitem__(self, key, val): >>> d OrderedDict([(9, 8), (1, 2), (2, 3), (3, 4)]) """ - if isinstance(key, types.SliceType): + if isinstance(key, slice): if not isinstance(val, OrderedDict): # FIXME: allow a list of tuples? raise TypeError('slice assignment requires an OrderedDict') keys = self._sequence[key] # NOTE: Could use ``range(*key.indices(len(self._sequence)))`` - indexes = range(len(self._sequence))[key] + indexes = list(range(len(self._sequence)))[key] if key.step is None: # NOTE: new slice may not be the same size as the one being # overwritten ! @@ -369,7 +369,7 @@ def __setitem__(self, key, val): # e.g. d[5:3] pos = key.start or 0 del self[key] - newkeys = val.keys() + newkeys = list(val.keys()) for k in newkeys: if k in self: if self.strict: @@ -390,7 +390,7 @@ def __setitem__(self, key, val): 'to extended slice of size %s' % (len(val), len(keys))) # FIXME: efficiency? del self[key] - item_list = zip(indexes, val.items()) + item_list = list(zip(indexes, list(val.items()))) # smallest indexes first - higher indexes not guaranteed to # exist item_list.sort() @@ -415,7 +415,7 @@ def __getitem__(self, key): >>> type(b[2:4]) """ - if isinstance(key, types.SliceType): + if isinstance(key, slice): # FIXME: does this raise the error we want? keys = self._sequence[key] # FIXME: efficiency? @@ -475,7 +475,7 @@ def __deepcopy__(self, memo): False """ from copy import deepcopy - return self.__class__(deepcopy(self.items(), memo), self.strict) + return self.__class__(deepcopy(list(self.items()), memo), self.strict) ### Read-only methods ### @@ -499,7 +499,7 @@ def items(self): >>> d.items() [] """ - return zip(self._sequence, self.values()) + return list(zip(self._sequence, list(self.values()))) def keys(self): """ @@ -538,9 +538,9 @@ def iteritems(self): StopIteration """ def make_iter(self=self): - keys = self.iterkeys() + keys = iter(self.keys()) while True: - key = keys.next() + key = next(keys) yield (key, self[key]) return make_iter() @@ -575,9 +575,9 @@ def itervalues(self): StopIteration """ def make_iter(self=self): - keys = self.iterkeys() + keys = iter(self.keys()) while True: - yield self[keys.next()] + yield self[next(keys)] return make_iter() ### Read-write methods ### @@ -611,7 +611,7 @@ def pop(self, key, *args): TypeError: pop expected at most 2 arguments, got 3 """ if len(args) > 1: - raise TypeError, ('pop expected at most 2 arguments, got %s' % + raise TypeError('pop expected at most 2 arguments, got %s' % (len(args) + 1)) if key in self: val = self[key] @@ -686,7 +686,7 @@ def update(self, from_od): TypeError: cannot convert dictionary update sequence element "4" to a 2-item sequence """ if isinstance(from_od, OrderedDict): - for key, val in from_od.items(): + for key, val in list(from_od.items()): self[key] = val elif isinstance(from_od, dict): # we lose compatibility with other ordered dict types this way @@ -805,7 +805,7 @@ def setvalues(self, values): # FIXME: correct error to raise? raise ValueError('Value list is not the same length as the ' 'OrderedDict.') - self.update(zip(self, values)) + self.update(list(zip(self, values))) ### Sequence Methods ### @@ -900,10 +900,10 @@ def __setitem__(self, index, name): You can only do slice assignment if the new set of keys is a reordering of the original set. """ - if isinstance(index, types.SliceType): + if isinstance(index, slice): # FIXME: efficiency? # check length is the same - indexes = range(len(self._main._sequence))[index] + indexes = list(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))) @@ -917,7 +917,7 @@ def __setitem__(self, index, name): raise KeyError('Keylist is not the same as current keylist.') orig_vals = [self._main[k] for k in name] del self._main[index] - vals = zip(indexes, name, orig_vals) + vals = list(zip(indexes, name, orig_vals)) vals.sort() for i, k, v in vals: if self._main.strict and k in self._main: @@ -943,7 +943,7 @@ def __cmp__(self, other): return cmp(self._main._sequence, other) def __contains__(self, item): return item in self._main._sequence def __len__(self): return len(self._main._sequence) - def __iter__(self): return self._main.iterkeys() + def __iter__(self): return iter(self._main.keys()) def count(self, item): return self._main._sequence.count(item) def index(self, item, *args): return self._main._sequence.index(item, *args) def reverse(self): self._main._sequence.reverse() @@ -980,15 +980,15 @@ def __call__(self): def __getitem__(self, index): """Fetch the item at position i.""" - if isinstance(index, types.SliceType): + if isinstance(index, slice): # fetching a slice returns an OrderedDict - return self._main[index].items() + return list(self._main[index].items()) key = self._main._sequence[index] return (key, self._main[key]) def __setitem__(self, index, item): """Set item at position i to item.""" - if isinstance(index, types.SliceType): + if isinstance(index, slice): # NOTE: item must be an iterable (list of tuples) self._main[index] = OrderedDict(item) else: @@ -1005,7 +1005,7 @@ def __setitem__(self, index, item): def __delitem__(self, i): """Delete the item at position i.""" key = self._main._sequence[i] - if isinstance(i, types.SliceType): + if isinstance(i, slice): for k in key: # FIXME: efficiency? del self._main[k] @@ -1013,29 +1013,29 @@ def __delitem__(self, i): del self._main[key] ### following methods pinched from UserList and adapted ### - def __repr__(self): return repr(self._main.items()) + def __repr__(self): return repr(list(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 __le__(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 __gt__(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 __contains__(self, item): return item in self._main.items() + def __lt__(self, other): return list(self._main.items()) < other + def __le__(self, other): return list(self._main.items()) <= other + def __eq__(self, other): return list(self._main.items()) == other + def __ne__(self, other): return list(self._main.items()) != other + def __gt__(self, other): return list(self._main.items()) > other + def __ge__(self, other): return list(self._main.items()) >= other + def __cmp__(self, other): return cmp(list(self._main.items()), other) + + def __contains__(self, item): return item in list(self._main.items()) def __len__(self): return len(self._main._sequence) # easier :-) - def __iter__(self): return self._main.iteritems() - def count(self, item): return self._main.items().count(item) - def index(self, item, *args): return self._main.items().index(item, *args) + def __iter__(self): return iter(self._main.items()) + def count(self, item): return list(self._main.items()).count(item) + def index(self, item, *args): return list(self._main.items()).index(item, *args) def reverse(self): self._main.reverse() def sort(self, *args, **kwds): self._main.sort(*args, **kwds) - def __mul__(self, n): return self._main.items()*n + def __mul__(self, n): return list(self._main.items())*n __rmul__ = __mul__ - def __add__(self, other): return self._main.items() + other - def __radd__(self, other): return other + self._main.items() + def __add__(self, other): return list(self._main.items()) + other + def __radd__(self, other): return other + list(self._main.items()) def append(self, item): """Add an item to the end.""" @@ -1090,7 +1090,7 @@ def __call__(self): def __getitem__(self, index): """Fetch the value at position i.""" - if isinstance(index, types.SliceType): + if isinstance(index, slice): return [self._main[key] for key in self._main._sequence[index]] else: return self._main[self._main._sequence[index]] @@ -1102,7 +1102,7 @@ def __setitem__(self, index, value): You can only do slice assignment to values if you supply a sequence of equal length to the slice you are replacing. """ - if isinstance(index, types.SliceType): + if isinstance(index, slice): keys = self._main._sequence[index] if len(keys) != len(value): raise ValueError('attempt to assign sequence of size %s ' @@ -1117,41 +1117,41 @@ def __setitem__(self, index, value): 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(list(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 __le__(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 __gt__(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 __contains__(self, item): return item in self._main.values() + def __lt__(self, other): return list(self._main.values()) < other + def __le__(self, other): return list(self._main.values()) <= other + def __eq__(self, other): return list(self._main.values()) == other + def __ne__(self, other): return list(self._main.values()) != other + def __gt__(self, other): return list(self._main.values()) > other + def __ge__(self, other): return list(self._main.values()) >= other + def __cmp__(self, other): return cmp(list(self._main.values()), other) + + def __contains__(self, item): return item in list(self._main.values()) def __len__(self): return len(self._main._sequence) # easier :-) - def __iter__(self): return self._main.itervalues() - def count(self, item): return self._main.values().count(item) - def index(self, item, *args): return self._main.values().index(item, *args) + def __iter__(self): return iter(self._main.values()) + def count(self, item): return list(self._main.values()).count(item) + def index(self, item, *args): return list(self._main.values()).index(item, *args) def reverse(self): """Reverse the values""" - vals = self._main.values() + vals = list(self._main.values()) vals.reverse() # FIXME: efficiency self[:] = vals def sort(self, *args, **kwds): """Sort the values.""" - vals = self._main.values() + vals = list(self._main.values()) vals.sort(*args, **kwds) self[:] = vals - def __mul__(self, n): return self._main.values()*n + def __mul__(self, n): return list(self._main.values())*n __rmul__ = __mul__ - def __add__(self, other): return self._main.values() + other - def __radd__(self, other): return other + self._main.values() + def __add__(self, other): return list(self._main.values()) + other + def __radd__(self, other): return other + list(self._main.values()) ## following methods not implemented for values ## def __delitem__(self, i): raise TypeError('Can\'t delete items from values') diff --git a/git/remote.py b/git/remote.py index ed01783ca..3b8adbdf1 100644 --- a/git/remote.py +++ b/git/remote.py @@ -6,9 +6,9 @@ # Module implementing a remote object allowing easy access to git remotes -from exc import GitCommandError -from ConfigParser import NoOptionError -from config import SectionConstraint +from .exc import GitCommandError +from configparser import NoOptionError +from .config import SectionConstraint from git.util import ( LazyMixin, @@ -17,7 +17,7 @@ RemoteProgress ) -from refs import ( +from .refs import ( Reference, RemoteReference, SymbolicReference, @@ -62,7 +62,7 @@ def finalize_process(proc): """Wait for the process (clone, fetch, pull or push) and handle its errors accordingly""" try: proc.wait() - except GitCommandError,e: + except GitCommandError as e: # if a push has rejected items, the command has non-zero return status # a return status of 128 indicates a connection error - reraise the previous one if proc.poll() == 128: @@ -523,7 +523,7 @@ def _get_fetch_info_from_stderr(self, proc, progress): if line.startswith('From') or line.startswith('remote: Total') or line.startswith('POST'): continue elif line.startswith('warning:'): - print >> sys.stderr, line + print(line, file=sys.stderr) continue elif line.startswith('fatal:'): raise GitCommandError(("Error when fetching: %s" % line,), 2) diff --git a/git/util.py b/git/util.py index a9e87d6f6..96416198c 100644 --- a/git/util.py +++ b/git/util.py @@ -483,7 +483,7 @@ def _obtain_lock_or_raise(self): try: fd = os.open(lock_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0) os.close(fd) - except OSError,e: + except OSError as e: raise IOError(str(e)) self._owns_lock = True @@ -505,7 +505,7 @@ def _release_lock(self): # on bloody windows, the file needs write permissions to be removable. # Why ... if os.name == 'nt': - os.chmod(lfp, 0777) + os.chmod(lfp, 0o777) # END handle win32 os.remove(lfp) except OSError: @@ -521,7 +521,7 @@ class BlockingLockFile(LockFile): be raised during the blocking period, preventing hangs as the lock can never be obtained.""" __slots__ = ("_check_interval", "_max_block_time") - def __init__(self, file_path, check_interval_s=0.3, max_block_time_s=sys.maxint): + def __init__(self, file_path, check_interval_s=0.3, max_block_time_s=sys.maxsize): """Configure the instance :parm check_interval_s: @@ -584,7 +584,7 @@ def __new__(cls, id_attr, prefix=''): def __init__(self, id_attr, prefix=''): self._id_attr = id_attr self._prefix = prefix - if not isinstance(id_attr, basestring): + if not isinstance(id_attr, str): raise ValueError("First parameter must be a string identifying the name-property. Extend the list after initialization") # END help debugging !