Skip to content

Commit 20830d9

Browse files
committed
Convert to Python3
1 parent 32da7fe commit 20830d9

33 files changed

+122
-121
lines changed

doc/source/conf.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@
4242
master_doc = 'index'
4343

4444
# General information about the project.
45-
project = u'GitPython'
46-
copyright = u'Copyright (C) 2008, 2009 Michael Trier and contributors, 2010-2015 Sebastian Thiel'
45+
project = 'GitPython'
46+
copyright = 'Copyright (C) 2008, 2009 Michael Trier and contributors, 2010-2015 Sebastian Thiel'
4747

4848
# The version info for the project you're documenting, acts as replacement for
4949
# |version| and |release|, also used in various other places throughout the
@@ -174,8 +174,8 @@
174174
# Grouping the document tree into LaTeX files. List of tuples
175175
# (source start file, target name, title, author, document class [howto/manual]).
176176
latex_documents = [
177-
('index', 'GitPython.tex', ur'GitPython Documentation',
178-
ur'Michael Trier', 'manual'),
177+
('index', 'GitPython.tex', r'GitPython Documentation',
178+
r'Michael Trier', 'manual'),
179179
]
180180

181181
# The name of an image file (relative to this directory) to place at the top of

git/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,5 +55,5 @@ def _init_externals():
5555

5656
#} END imports
5757

58-
__all__ = [name for name, obj in locals().items()
58+
__all__ = [name for name, obj in list(locals().items())
5959
if not (name.startswith('_') or inspect.ismodule(obj))]

git/cmd.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
force_bytes,
2525
PY3,
2626
# just to satisfy flake8 on py3
27-
unicode,
27+
str,
2828
safe_decode,
2929
is_posix,
3030
is_win,
@@ -128,7 +128,7 @@ def slots_to_dict(self, exclude=()):
128128

129129

130130
def dict_to_slots_and__excluded_are_none(self, d, excluded=()):
131-
for k, v in d.items():
131+
for k, v in list(d.items()):
132132
setattr(self, k, v)
133133
for k in excluded:
134134
setattr(self, k, None)
@@ -381,7 +381,7 @@ def readlines(self, size=-1):
381381
def __iter__(self):
382382
return self
383383

384-
def next(self):
384+
def __next__(self):
385385
line = self.readline()
386386
if not line:
387387
raise StopIteration
@@ -714,7 +714,7 @@ def update_environment(self, **kwargs):
714714
:return: dict that maps environment variables to their old values
715715
"""
716716
old_env = {}
717-
for key, value in kwargs.items():
717+
for key, value in list(kwargs.items()):
718718
# set value if it is None
719719
if value is not None:
720720
old_env[key] = self._environment.get(key)
@@ -763,8 +763,8 @@ def transform_kwarg(self, name, value, split_single_char_options):
763763
def transform_kwargs(self, split_single_char_options=True, **kwargs):
764764
"""Transforms Python style kwargs into git command line options."""
765765
args = list()
766-
kwargs = OrderedDict(sorted(kwargs.items(), key=lambda x: x[0]))
767-
for k, v in kwargs.items():
766+
kwargs = OrderedDict(sorted(list(kwargs.items()), key=lambda x: x[0]))
767+
for k, v in list(kwargs.items()):
768768
if isinstance(v, (list, tuple)):
769769
for value in v:
770770
args += self.transform_kwarg(k, value, split_single_char_options)
@@ -777,15 +777,15 @@ def __unpack_args(cls, arg_list):
777777
if not isinstance(arg_list, (list, tuple)):
778778
# This is just required for unicode conversion, as subprocess can't handle it
779779
# However, in any other case, passing strings (usually utf-8 encoded) is totally fine
780-
if not PY3 and isinstance(arg_list, unicode):
780+
if not PY3 and isinstance(arg_list, str):
781781
return [arg_list.encode(defenc)]
782782
return [str(arg_list)]
783783

784784
outlist = list()
785785
for arg in arg_list:
786786
if isinstance(arg_list, (list, tuple)):
787787
outlist.extend(cls.__unpack_args(arg))
788-
elif not PY3 and isinstance(arg_list, unicode):
788+
elif not PY3 and isinstance(arg_list, str):
789789
outlist.append(arg_list.encode(defenc))
790790
# END recursion
791791
else:
@@ -840,8 +840,8 @@ def _call_process(self, method, *args, **kwargs):
840840
:return: Same as ``execute``"""
841841
# Handle optional arguments prior to calling transform_kwargs
842842
# otherwise these'll end up in args, which is bad.
843-
exec_kwargs = dict((k, v) for k, v in kwargs.items() if k in execute_kwargs)
844-
opts_kwargs = dict((k, v) for k, v in kwargs.items() if k not in execute_kwargs)
843+
exec_kwargs = dict((k, v) for k, v in list(kwargs.items()) if k in execute_kwargs)
844+
opts_kwargs = dict((k, v) for k, v in list(kwargs.items()) if k not in execute_kwargs)
845845

846846
insert_after_this_arg = opts_kwargs.pop('insert_kwargs_after', None)
847847

git/compat.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,10 @@ def bchr(n):
4343
return bytes([n])
4444

4545
def mviter(d):
46-
return d.values()
46+
return list(d.values())
4747

4848
range = xrange # @ReservedAssignment
49-
unicode = str
49+
str = str
5050
binary_type = bytes
5151
else:
5252
FileType = file # @UndefinedVariable on PY3
@@ -56,17 +56,17 @@ def mviter(d):
5656
defenc = 'utf-8'
5757
byte_ord = ord
5858
bchr = chr
59-
unicode = unicode
59+
str = str
6060
binary_type = str
6161
range = xrange # @ReservedAssignment
6262

6363
def mviter(d):
64-
return d.itervalues()
64+
return iter(d.values())
6565

6666

6767
def safe_decode(s):
6868
"""Safely decodes a binary string to unicode"""
69-
if isinstance(s, unicode):
69+
if isinstance(s, str):
7070
return s
7171
elif isinstance(s, bytes):
7272
return s.decode(defenc, 'surrogateescape')
@@ -76,7 +76,7 @@ def safe_decode(s):
7676

7777
def safe_encode(s):
7878
"""Safely decodes a binary string to unicode"""
79-
if isinstance(s, unicode):
79+
if isinstance(s, str):
8080
return s.encode(defenc)
8181
elif isinstance(s, bytes):
8282
return s
@@ -86,7 +86,7 @@ def safe_encode(s):
8686

8787
def win_encode(s):
8888
"""Encode unicodes for process arguments on Windows."""
89-
if isinstance(s, unicode):
89+
if isinstance(s, str):
9090
return s.encode(locale.getpreferredencoding(False))
9191
elif isinstance(s, bytes):
9292
return s
@@ -155,7 +155,7 @@ def b(data):
155155
_unichr = chr
156156
bytes_chr = lambda code: bytes((code,))
157157
else:
158-
_unichr = unichr
158+
_unichr = chr
159159
bytes_chr = chr
160160

161161
def surrogateescape_handler(exc):

git/config.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828

2929

3030
try:
31-
import ConfigParser as cp
31+
import configparser as cp
3232
except ImportError:
3333
# PY3
3434
import configparser as cp
@@ -441,15 +441,15 @@ def _write(self, fp):
441441
git compatible format"""
442442
def write_section(name, section_dict):
443443
fp.write(("[%s]\n" % name).encode(defenc))
444-
for (key, value) in section_dict.items():
444+
for (key, value) in list(section_dict.items()):
445445
if key != "__name__":
446446
fp.write(("\t%s = %s\n" % (key, self._value_to_string(value).replace('\n', '\n\t'))).encode(defenc))
447447
# END if key is not __name__
448448
# END section writing
449449

450450
if self._defaults:
451451
write_section(cp.DEFAULTSECT, self._defaults)
452-
for name, value in self._sections.items():
452+
for name, value in list(self._sections.items()):
453453
write_section(name, value)
454454

455455
def items(self, section_name):

git/exc.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ class CommandError(UnicodeMixin, Exception):
3131
#: A unicode print-format with 2 `%s for `<cmdline>` and the rest,
3232
#: e.g.
3333
#: u"'%s' failed%s"
34-
_msg = u"Cmd('%s') failed%s"
34+
_msg = "Cmd('%s') failed%s"
3535

3636
def __init__(self, command, status=None, stderr=None, stdout=None):
3737
if not isinstance(command, (tuple, list)):
@@ -40,19 +40,19 @@ def __init__(self, command, status=None, stderr=None, stdout=None):
4040
self.status = status
4141
if status:
4242
if isinstance(status, Exception):
43-
status = u"%s('%s')" % (type(status).__name__, safe_decode(str(status)))
43+
status = "%s('%s')" % (type(status).__name__, safe_decode(str(status)))
4444
else:
4545
try:
46-
status = u'exit code(%s)' % int(status)
46+
status = 'exit code(%s)' % int(status)
4747
except:
4848
s = safe_decode(str(status))
49-
status = u"'%s'" % s if isinstance(status, string_types) else s
49+
status = "'%s'" % s if isinstance(status, string_types) else s
5050

5151
self._cmd = safe_decode(command[0])
52-
self._cmdline = u' '.join(safe_decode(i) for i in command)
53-
self._cause = status and u" due to: %s" % status or "!"
54-
self.stdout = stdout and u"\n stdout: '%s'" % safe_decode(stdout) or ''
55-
self.stderr = stderr and u"\n stderr: '%s'" % safe_decode(stderr) or ''
52+
self._cmdline = ' '.join(safe_decode(i) for i in command)
53+
self._cause = status and " due to: %s" % status or "!"
54+
self.stdout = stdout and "\n stdout: '%s'" % safe_decode(stdout) or ''
55+
self.stderr = stderr and "\n stderr: '%s'" % safe_decode(stderr) or ''
5656

5757
def __unicode__(self):
5858
return (self._msg + "\n cmdline: %s%s%s") % (
@@ -64,7 +64,7 @@ class GitCommandNotFound(CommandError):
6464
the GIT_PYTHON_GIT_EXECUTABLE environment variable"""
6565
def __init__(self, command, cause):
6666
super(GitCommandNotFound, self).__init__(command, cause)
67-
self._msg = u"Cmd('%s') not found%s"
67+
self._msg = "Cmd('%s') not found%s"
6868

6969

7070
class GitCommandError(CommandError):
@@ -114,7 +114,7 @@ class HookExecutionError(CommandError):
114114

115115
def __init__(self, command, status, stderr=None, stdout=None):
116116
super(HookExecutionError, self).__init__(command, status, stderr, stdout)
117-
self._msg = u"Hook('%s') failed%s"
117+
self._msg = "Hook('%s') failed%s"
118118

119119

120120
class RepositoryDirtyError(Exception):

git/index/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Initialize the index package"""
22
# flake8: noqa
3-
from __future__ import absolute_import
3+
44

55
from .base import *
66
from .typ import *

git/index/base.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ def _deserialize(self, stream):
171171

172172
def _entries_sorted(self):
173173
""":return: list of entries, in a sorted fashion, first by path, then by stage"""
174-
return sorted(self.entries.values(), key=lambda e: (e.path, e.stage))
174+
return sorted(list(self.entries.values()), key=lambda e: (e.path, e.stage))
175175

176176
def _serialize(self, stream, ignore_extension_data=False):
177177
entries = self._entries_sorted()
@@ -280,7 +280,7 @@ def new(cls, repo, *tree_sha):
280280

281281
inst = cls(repo)
282282
# convert to entries dict
283-
entries = dict(izip(((e.path, e.stage) for e in base_entries),
283+
entries = dict(zip(((e.path, e.stage) for e in base_entries),
284284
(IndexEntry.from_base(e) for e in base_entries)))
285285

286286
inst.entries = entries
@@ -915,7 +915,7 @@ def move(self, items, skip_errors=False, **kwargs):
915915

916916
# parse result - first 0:n/2 lines are 'checking ', the remaining ones
917917
# are the 'renaming' ones which we parse
918-
for ln in xrange(int(len(mvlines) / 2), len(mvlines)):
918+
for ln in range(int(len(mvlines) / 2), len(mvlines)):
919919
tokens = mvlines[ln].split(' to ')
920920
assert len(tokens) == 2, "Too many tokens in %s" % mvlines[ln]
921921

git/objects/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
Import all submodules main classes into the package space
33
"""
44
# flake8: noqa
5-
from __future__ import absolute_import
5+
66

77
import inspect
88

@@ -22,5 +22,5 @@
2222

2323
# must come after submodule was made available
2424

25-
__all__ = [name for name, obj in locals().items()
25+
__all__ = [name for name, obj in list(locals().items())
2626
if not (name.startswith('_') or inspect.ismodule(obj))]

git/objects/fun.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def tree_to_stream(entries, write):
2222

2323
for binsha, mode, name in entries:
2424
mode_str = b''
25-
for i in xrange(6):
25+
for i in range(6):
2626
mode_str = bchr(((mode >> (i * 3)) & bit_mask) + ord_zero) + mode_str
2727
# END for each 8 octal value
2828

git/refs/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# flake8: noqa
2-
from __future__ import absolute_import
2+
33
# import all modules in order, fix the names they require
44
from .symbolic import *
55
from .reference import *

git/refs/log.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def format(self):
4848
""":return: a string suitable to be placed in a reflog file"""
4949
act = self.actor
5050
time = self.time
51-
return u"{0} {1} {2} <{3}> {4!s} {5}\t{6}\n".format(self.oldhexsha,
51+
return "{0} {1} {2} <{3}> {4!s} {5}\t{6}\n".format(self.oldhexsha,
5252
self.newhexsha,
5353
act.name,
5454
act.email,
@@ -222,7 +222,7 @@ def entry_at(cls, filepath, index):
222222
return RefLogEntry.from_line(fp.readlines()[index].strip())
223223
else:
224224
# read until index is reached
225-
for i in xrange(index + 1):
225+
for i in range(index + 1):
226226
line = fp.readline()
227227
if not line:
228228
break

git/remote.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
SymbolicReference,
3636
TagReference
3737
)
38+
import collections
3839

3940

4041
log = logging.getLogger('git.remote')
@@ -66,7 +67,7 @@ def to_progress_instance(progress):
6667
RemoteProgress().
6768
"""
6869
# new API only needs progress as a function
69-
if callable(progress):
70+
if isinstance(progress, collections.Callable):
7071
return CallableRemoteProgress(progress)
7172

7273
# where None is passed create a parser that eats the progress

git/repo/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
"""Initialize the Repo package"""
22
# flake8: noqa
3-
from __future__ import absolute_import
3+
44
from .base import *

git/repo/base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -726,9 +726,9 @@ def blame_incremental(self, rev, file, **kwargs):
726726
break
727727

728728
yield BlameEntry(commits[hexsha],
729-
range(lineno, lineno + num_lines),
729+
list(range(lineno, lineno + num_lines)),
730730
safe_decode(orig_filename),
731-
range(orig_lineno, orig_lineno + num_lines))
731+
list(range(orig_lineno, orig_lineno + num_lines)))
732732

733733
def blame(self, rev, file, incremental=False, **kwargs):
734734
"""The blame information for the given file at the given revision.

git/repo/fun.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ def rev_parse(repo, rev):
287287
try:
288288
if token == "~":
289289
obj = to_commit(obj)
290-
for _ in xrange(num):
290+
for _ in range(num):
291291
obj = obj.parents[0]
292292
# END for each history item to walk
293293
elif token == "^":

git/test/lib/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@
99
from .asserts import *
1010
from .helper import *
1111

12-
__all__ = [name for name, obj in locals().items()
12+
__all__ = [name for name, obj in list(locals().items())
1313
if not (name.startswith('_') or inspect.ismodule(obj))]

git/test/lib/helper.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
#
44
# This module is part of GitPython and is released under
55
# the BSD License: http://www.opensource.org/licenses/bsd-license.php
6-
from __future__ import print_function
6+
77

88
import contextlib
99
from functools import wraps

0 commit comments

Comments
 (0)