浏览代码

Revert "Change the way methods that take a path argument behave."

This reverts commit 7a02943889d2744f6329103e71089ad037eaf109 and
fd2f4f425a02d3fa47babac845ef44fb654f1e9f.
Gary van der Merwe 10 年之前
父节点
当前提交
1d4d526b6e

+ 1 - 1
dulwich/file.py

@@ -104,7 +104,7 @@ class _GitFile(object):
                      'truncate', 'write', 'writelines')
     def __init__(self, filename, mode, bufsize):
         self._filename = filename
-        self._lockfilename = self._filename + b'.lock'
+        self._lockfilename = '%s.lock' % self._filename
         fd = os.open(self._lockfilename,
             os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0))
         self._file = os.fdopen(fd, mode, bufsize)

+ 3 - 3
dulwich/hooks.py

@@ -100,7 +100,7 @@ class PreCommitShellHook(ShellHook):
     """pre-commit shell hook"""
 
     def __init__(self, controldir):
-        filepath = os.path.join(controldir, b'hooks', b'pre-commit')
+        filepath = os.path.join(controldir, 'hooks', 'pre-commit')
 
         ShellHook.__init__(self, 'pre-commit', filepath, 0)
 
@@ -109,7 +109,7 @@ class PostCommitShellHook(ShellHook):
     """post-commit shell hook"""
 
     def __init__(self, controldir):
-        filepath = os.path.join(controldir, b'hooks', b'post-commit')
+        filepath = os.path.join(controldir, 'hooks', 'post-commit')
 
         ShellHook.__init__(self, 'post-commit', filepath, 0)
 
@@ -122,7 +122,7 @@ class CommitMsgShellHook(ShellHook):
     """
 
     def __init__(self, controldir):
-        filepath = os.path.join(controldir, b'hooks', b'commit-msg')
+        filepath = os.path.join(controldir, 'hooks', 'commit-msg')
 
         def prepare_msg(*args):
             (fd, path) = tempfile.mkstemp()

+ 3 - 13
dulwich/index.py

@@ -480,15 +480,12 @@ def build_index_from_tree(prefix, index_path, object_store, tree_id,
         in a working dir. Suiteable only for fresh clones.
     """
 
-    if not isinstance(prefix, bytes):
-        prefix = prefix.encode(sys.getfilesystemencoding())
-
     index = Index(index_path)
 
     for entry in object_store.iter_tree_contents(tree_id):
         if not validate_path(entry.path):
             continue
-        full_path = os.path.join(prefix, entry.path)
+        full_path = os.path.join(prefix, entry.path.decode(sys.getfilesystemencoding()))
 
         if not os.path.exists(os.path.dirname(full_path)):
             os.makedirs(os.path.dirname(full_path))
@@ -516,11 +513,7 @@ def blob_from_path_and_stat(path, st):
         with open(path, 'rb') as f:
             blob.data = f.read()
     else:
-        if not isinstance(path, bytes):
-            blob.data = os.readlink(path.encode(sys.getfilesystemencoding()))
-        else:
-            blob.data = os.readlink(path)
-
+        blob.data = os.readlink(path).encode(sys.getfilesystemencoding())
     return blob
 
 
@@ -532,11 +525,8 @@ def get_unstaged_changes(index, path):
     :return: iterator over paths with unstaged changes
     """
     # For each entry in the index check the sha1 & ensure not staged
-    if not isinstance(path, bytes):
-        path = path.encode(sys.getfilesystemencoding())
-
     for name, entry in index.iteritems():
-        fp = os.path.join(path, name)
+        fp = os.path.join(path, name.decode(sys.getfilesystemencoding()))
         blob = blob_from_path_and_stat(fp, os.lstat(fp))
         if blob.id != entry.sha:
             yield name

+ 20 - 23
dulwich/object_store.py

@@ -63,8 +63,8 @@ from dulwich.pack import (
     PackStreamCopier,
     )
 
-INFODIR = b'info'
-PACKDIR = b'pack'
+INFODIR = 'info'
+PACKDIR = 'pack'
 
 
 class BaseObjectStore(object):
@@ -425,7 +425,7 @@ class DiskObjectStore(PackBasedObjectStore):
 
     def _read_alternate_paths(self):
         try:
-            f = GitFile(os.path.join(self.path, INFODIR, b'alternates'),
+            f = GitFile(os.path.join(self.path, INFODIR, "alternates"),
                     'rb')
         except (OSError, IOError) as e:
             if e.errno == errno.ENOENT:
@@ -437,9 +437,9 @@ class DiskObjectStore(PackBasedObjectStore):
                 if l[0] == b"#":
                     continue
                 if os.path.isabs(l):
-                    yield l
+                    yield l.decode(sys.getfilesystemencoding())
                 else:
-                    yield os.path.join(self.path, l)
+                    yield os.path.join(self.path, l).decode(sys.getfilesystemencoding())
 
     def add_alternate_path(self, path):
         """Add an alternate path to this object store.
@@ -449,7 +449,7 @@ class DiskObjectStore(PackBasedObjectStore):
         except OSError as e:
             if e.errno != errno.EEXIST:
                 raise
-        alternates_path = os.path.join(self.path, INFODIR, b'alternates')
+        alternates_path = os.path.join(self.path, INFODIR, "alternates")
         with GitFile(alternates_path, 'wb') as f:
             try:
                 orig_f = open(alternates_path, 'rb')
@@ -459,7 +459,7 @@ class DiskObjectStore(PackBasedObjectStore):
             else:
                 with orig_f:
                     f.write(orig_f.read())
-            f.write(path + b"\n")
+            f.write(path.encode(sys.getfilesystemencoding()) + b"\n")
 
         if not os.path.isabs(path):
             path = os.path.join(self.path, path)
@@ -477,10 +477,10 @@ class DiskObjectStore(PackBasedObjectStore):
         self._pack_cache_time = os.stat(self.pack_dir).st_mtime
         pack_files = set()
         for name in pack_dir_contents:
-            assert type(name) is bytes
+            assert isinstance(name, basestring if sys.version_info[0] == 2 else str)
             # TODO: verify that idx exists first
-            if name.startswith(b'pack-') and name.endswith(b'.pack'):
-                pack_files.add(name[:-len(b'.pack')])
+            if name.startswith("pack-") and name.endswith(".pack"):
+                pack_files.add(name[:-len(".pack")])
 
         # Open newly appeared pack files
         for f in pack_files:
@@ -507,7 +507,7 @@ class DiskObjectStore(PackBasedObjectStore):
             if len(base) != 2:
                 continue
             for rest in os.listdir(os.path.join(self.path, base)):
-                yield (base+rest)
+                yield (base+rest).encode(sys.getfilesystemencoding())
 
     def _get_loose_object(self, sha):
         path = self._get_shafile_path(sha)
@@ -524,7 +524,8 @@ class DiskObjectStore(PackBasedObjectStore):
     def _get_pack_basepath(self, entries):
         suffix = iter_sha1(entry[0] for entry in entries)
         # TODO: Handle self.pack_dir being bytes
-        return os.path.join(self.pack_dir, b"pack-" + suffix)
+        suffix = suffix.decode('ascii')
+        return os.path.join(self.pack_dir, "pack-" + suffix)
 
     def _complete_thin_pack(self, f, path, copier, indexer):
         """Move a specific file containing a pack into the pack directory.
@@ -566,10 +567,10 @@ class DiskObjectStore(PackBasedObjectStore):
         # Move the pack in.
         entries.sort()
         pack_base_name = self._get_pack_basepath(entries)
-        os.rename(path, pack_base_name + b'.pack')
+        os.rename(path, pack_base_name + '.pack')
 
         # Write the index.
-        index_file = GitFile(pack_base_name + b'.idx', 'wb')
+        index_file = GitFile(pack_base_name + '.idx', 'wb')
         try:
             write_pack_index_v2(index_file, entries, pack_sha)
             index_file.close()
@@ -596,10 +597,7 @@ class DiskObjectStore(PackBasedObjectStore):
         :return: A Pack object pointing at the now-completed thin pack in the
             objects/pack directory.
         """
-        fd, path = tempfile.mkstemp(
-            dir=self.path.decode(sys.getfilesystemencoding()),
-            prefix='tmp_pack_')
-        path = path.encode(sys.getfilesystemencoding())
+        fd, path = tempfile.mkstemp(dir=self.path, prefix='tmp_pack_')
         with os.fdopen(fd, 'w+b') as f:
             indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
             copier = PackStreamCopier(read_all, read_some, f,
@@ -618,9 +616,9 @@ class DiskObjectStore(PackBasedObjectStore):
         with PackData(path) as p:
             entries = p.sorted_entries()
             basename = self._get_pack_basepath(entries)
-            with GitFile(basename+b'.idx', "wb") as f:
+            with GitFile(basename+".idx", "wb") as f:
                 write_pack_index_v2(f, entries, p.get_stored_checksum())
-        os.rename(path, basename + b'.pack')
+        os.rename(path, basename + ".pack")
         final_pack = Pack(basename)
         self._add_known_pack(basename, final_pack)
         return final_pack
@@ -632,8 +630,7 @@ class DiskObjectStore(PackBasedObjectStore):
             call when the pack is finished and an abort
             function.
         """
-        pack_dir_str = self.pack_dir.decode(sys.getfilesystemencoding())
-        fd, path = tempfile.mkstemp(dir=pack_dir_str, suffix='.pack')
+        fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
         f = os.fdopen(fd, 'wb')
         def commit():
             os.fsync(fd)
@@ -672,7 +669,7 @@ class DiskObjectStore(PackBasedObjectStore):
         except OSError as e:
             if e.errno != errno.EEXIST:
                 raise
-        os.mkdir(os.path.join(path, INFODIR))
+        os.mkdir(os.path.join(path, "info"))
         os.mkdir(os.path.join(path, PACKDIR))
         return cls(path)
 

+ 4 - 2
dulwich/objects.py

@@ -112,10 +112,12 @@ def hex_to_filename(path, hex):
     # os.path.join accepts bytes or unicode, but all args must be of the same
     # type. Make sure that hex which is expected to be bytes, is the same type
     # as path.
-    directory = hex[:2]
+    if getattr(path, 'encode', None) is not None:
+        hex = hex.decode('ascii')
+    dir = hex[:2]
     file = hex[2:]
     # Check from object dir
-    return os.path.join(path, directory, file)
+    return os.path.join(path, dir, file)
 
 
 def filename_to_hex(filename):

+ 7 - 7
dulwich/pack.py

@@ -1474,12 +1474,12 @@ def write_pack(filename, objects, deltify=None, delta_window_size=None):
     :param deltify: Whether to deltify pack objects
     :return: Tuple with checksum of pack file and index file
     """
-    with GitFile(filename + b'.pack', 'wb') as f:
+    with GitFile(filename + '.pack', 'wb') as f:
         entries, data_sum = write_pack_objects(f, objects,
             delta_window_size=delta_window_size, deltify=deltify)
     entries = [(k, v[0], v[1]) for (k, v) in entries.items()]
     entries.sort()
-    with GitFile(filename + b'.idx', 'wb') as f:
+    with GitFile(filename + '.idx', 'wb') as f:
         return data_sum, write_pack_index_v2(f, entries, data_sum)
 
 
@@ -1785,8 +1785,8 @@ class Pack(object):
         self._basename = basename
         self._data = None
         self._idx = None
-        self._idx_path = self._basename + b'.idx'
-        self._data_path = self._basename + b'.pack'
+        self._idx_path = self._basename + '.idx'
+        self._data_path = self._basename + '.pack'
         self._data_load = lambda: PackData(self._data_path)
         self._idx_load = lambda: load_pack_index(self._idx_path)
         self.resolve_ext_ref = resolve_ext_ref
@@ -1795,7 +1795,7 @@ class Pack(object):
     def from_lazy_objects(self, data_fn, idx_fn):
         """Create a new pack object from callables to load pack data and
         index objects."""
-        ret = Pack(b'')
+        ret = Pack('')
         ret._data_load = data_fn
         ret._idx_load = idx_fn
         return ret
@@ -1803,7 +1803,7 @@ class Pack(object):
     @classmethod
     def from_objects(self, data, idx):
         """Create a new pack object from pack data and index objects."""
-        ret = Pack(b'')
+        ret = Pack('')
         ret._data_load = lambda: data
         ret._idx_load = lambda: idx
         return ret
@@ -1930,7 +1930,7 @@ class Pack(object):
                     determine whether or not a .keep file is obsolete.
         :return: The path of the .keep file, as a string.
         """
-        keepfile_name = self._basename + b'.keep'
+        keepfile_name = '%s.keep' % self._basename
         with GitFile(keepfile_name, 'wb') as keepfile:
             if msg:
                 keepfile.write(msg)

+ 1 - 4
dulwich/porcelain.py

@@ -539,10 +539,7 @@ def push(repo, remote_location, refs_path,
             return refs
 
         err_encoding = getattr(errstream, 'encoding', 'utf-8')
-        if not isinstance(remote_location, bytes):
-            remote_location_bytes = remote_location.encode(err_encoding)
-        else:
-            remote_location_bytes = remote_location
+        remote_location_bytes = remote_location.encode(err_encoding)
         try:
             client.send_pack(path, update_refs,
                 r.object_store.generate_pack_contents, progress=errstream.write)

+ 10 - 11
dulwich/refs.py

@@ -23,7 +23,6 @@
 """
 import errno
 import os
-import sys
 
 from dulwich.errors import (
     PackedRefsException,
@@ -44,8 +43,6 @@ SYMREF = b'ref: '
 LOCAL_BRANCH_PREFIX = b'refs/heads/'
 BAD_REF_CHARS = set(b'\177 ~^:?*[')
 
-path_sep_bytes = os.path.sep.encode(sys.getfilesystemencoding())
-
 
 def check_ref_format(refname):
     """Check if a refname is correctly formatted.
@@ -398,9 +395,10 @@ class DiskRefsContainer(RefsContainer):
         subkeys = set()
         path = self.refpath(base)
         for root, dirs, files in os.walk(path):
-            dir = root[len(path):].strip(path_sep_bytes).replace(path_sep_bytes, b'/')
+            dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
             for filename in files:
-                refname = (dir + b'/' + filename).strip(b'/')
+                refname = (("%s/%s" % (dir, filename))
+                           .strip("/").encode('ascii'))
                 # check_ref_format requires at least one /, so we prepend the
                 # base before calling it.
                 if check_ref_format(base + b'/' + refname):
@@ -416,9 +414,9 @@ class DiskRefsContainer(RefsContainer):
             allkeys.add(b'HEAD')
         path = self.refpath(b'')
         for root, dirs, files in os.walk(self.refpath(b'refs')):
-            dir = root[len(path):].strip(path_sep_bytes).replace(path_sep_bytes, b'/')
+            dir = root[len(path):].strip(os.path.sep).replace(os.path.sep, "/")
             for filename in files:
-                refname = (dir + b'/' + filename).strip(b'/')
+                refname = ("%s/%s" % (dir, filename)).strip("/").encode('ascii')
                 if check_ref_format(refname):
                     allkeys.add(refname)
         allkeys.update(self.get_packed_refs())
@@ -428,8 +426,9 @@ class DiskRefsContainer(RefsContainer):
         """Return the disk path of a ref.
 
         """
-        if path_sep_bytes != b'/':
-            name = name.replace(b'/', path_sep_bytes)
+        name = name.decode('ascii')
+        if os.path.sep != "/":
+            name = name.replace("/", os.path.sep)
         return os.path.join(self.path, name)
 
     def get_packed_refs(self):
@@ -446,7 +445,7 @@ class DiskRefsContainer(RefsContainer):
             # None if and only if _packed_refs is also None.
             self._packed_refs = {}
             self._peeled_refs = {}
-            path = os.path.join(self.path, b'packed-refs')
+            path = os.path.join(self.path, 'packed-refs')
             try:
                 f = GitFile(path, 'rb')
             except IOError as e:
@@ -514,7 +513,7 @@ class DiskRefsContainer(RefsContainer):
     def _remove_packed_ref(self, name):
         if self._packed_refs is None:
             return
-        filename = os.path.join(self.path, b'packed-refs')
+        filename = os.path.join(self.path, 'packed-refs')
         # reread cached refs from disk, while holding the lock
         f = GitFile(filename, 'wb')
         try:

+ 38 - 56
dulwich/repo.py

@@ -82,19 +82,19 @@ from dulwich.refs import (
 import warnings
 
 
-OBJECTDIR = b'objects'
-REFSDIR = b'refs'
-REFSDIR_TAGS = b'tags'
-REFSDIR_HEADS = b'heads'
-INDEX_FILENAME = b'index'
+OBJECTDIR = 'objects'
+REFSDIR = 'refs'
+REFSDIR_TAGS = 'tags'
+REFSDIR_HEADS = 'heads'
+INDEX_FILENAME = "index"
 
 BASE_DIRECTORIES = [
-    [b'branches'],
+    ["branches"],
     [REFSDIR],
     [REFSDIR, REFSDIR_TAGS],
     [REFSDIR, REFSDIR_HEADS],
-    [b'hooks'],
-    [b'info']
+    ["hooks"],
+    ["info"]
     ]
 
 
@@ -176,7 +176,7 @@ class BaseRepo(object):
     def _init_files(self, bare):
         """Initialize a default set of named files."""
         from dulwich.config import ConfigFile
-        self._put_named_file(b'description', b"Unnamed repository")
+        self._put_named_file('description', b"Unnamed repository")
         f = BytesIO()
         cf = ConfigFile()
         cf.set(b"core", b"repositoryformatversion", b"0")
@@ -184,8 +184,8 @@ class BaseRepo(object):
         cf.set(b"core", b"bare", bare)
         cf.set(b"core", b"logallrefupdates", True)
         cf.write_to_file(f)
-        self._put_named_file(b'config', f.getvalue())
-        self._put_named_file(os.path.join(b'info', b'exclude'), b'')
+        self._put_named_file('config', f.getvalue())
+        self._put_named_file(os.path.join('info', 'exclude'), b'')
 
     def get_named_file(self, path):
         """Get a file from the control dir with a specific name.
@@ -627,7 +627,6 @@ class BaseRepo(object):
 
         return c.id
 
-path_sep_bytes = os.path.sep.encode(sys.getfilesystemencoding())
 
 class Repo(BaseRepo):
     """A git repository backed by local disk.
@@ -638,40 +637,36 @@ class Repo(BaseRepo):
     To create a new repository, use the Repo.init class method.
     """
 
-    def __init__(self, path):
-        self.path = path
-        if not isinstance(path, bytes):
-            self._path_bytes = path.encode(sys.getfilesystemencoding())
-        else:
-            self._path_bytes = path
-        if os.path.isdir(os.path.join(self._path_bytes, b'.git', OBJECTDIR)):
+    def __init__(self, root):
+        if os.path.isdir(os.path.join(root, ".git", OBJECTDIR)):
             self.bare = False
-            self._controldir = os.path.join(self._path_bytes, b'.git')
-        elif (os.path.isdir(os.path.join(self._path_bytes, OBJECTDIR)) and
-              os.path.isdir(os.path.join(self._path_bytes, REFSDIR))):
+            self._controldir = os.path.join(root, ".git")
+        elif (os.path.isdir(os.path.join(root, OBJECTDIR)) and
+              os.path.isdir(os.path.join(root, REFSDIR))):
             self.bare = True
-            self._controldir = self._path_bytes
-        elif (os.path.isfile(os.path.join(self._path_bytes, b'.git'))):
+            self._controldir = root
+        elif (os.path.isfile(os.path.join(root, ".git"))):
             import re
-            with open(os.path.join(self._path_bytes, b'.git'), 'rb') as f:
-                _, gitdir = re.match(b'(gitdir: )(.+$)', f.read()).groups()
+            with open(os.path.join(root, ".git"), 'r') as f:
+                _, path = re.match('(gitdir: )(.+$)', f.read()).groups()
             self.bare = False
-            self._controldir = os.path.join(self._path_bytes, gitdir)
+            self._controldir = os.path.join(root, path)
         else:
             raise NotGitRepository(
-                "No git repository was found at %(path)s" % dict(path=path)
+                "No git repository was found at %(path)s" % dict(path=root)
             )
+        self.path = root
         object_store = DiskObjectStore(os.path.join(self.controldir(),
                                                     OBJECTDIR))
         refs = DiskRefsContainer(self.controldir())
         BaseRepo.__init__(self, object_store, refs)
 
         self._graftpoints = {}
-        graft_file = self.get_named_file(os.path.join(b'info', b'grafts'))
+        graft_file = self.get_named_file(os.path.join("info", "grafts"))
         if graft_file:
             with graft_file:
                 self._graftpoints.update(parse_graftpoints(graft_file))
-        graft_file = self.get_named_file(b'shallow')
+        graft_file = self.get_named_file("shallow")
         if graft_file:
             with graft_file:
                 self._graftpoints.update(parse_graftpoints(graft_file))
@@ -690,7 +685,7 @@ class Repo(BaseRepo):
         :param path: The path to the file, relative to the control dir.
         :param contents: A string to write to the file.
         """
-        path = path.lstrip(path_sep_bytes)
+        path = path.lstrip(os.path.sep)
         with GitFile(os.path.join(self.controldir(), path), 'wb') as f:
             f.write(contents)
 
@@ -706,7 +701,7 @@ class Repo(BaseRepo):
         """
         # TODO(dborowitz): sanitize filenames, since this is used directly by
         # the dumb web serving code.
-        path = path.lstrip(path_sep_bytes)
+        path = path.lstrip(os.path.sep)
         try:
             return open(os.path.join(self.controldir(), path), 'rb')
         except (IOError, OSError) as e:
@@ -748,24 +743,19 @@ class Repo(BaseRepo):
             )
         index = self.open_index()
         for path in paths:
-            if not isinstance(path, bytes):
-                disk_path_bytes = path.encode(sys.getfilesystemencoding())
-                repo_path_bytes = path.encode(fsencoding)
-            else:
-                disk_path_bytes, repo_path_bytes = path, path
-            full_path = os.path.join(self._path_bytes, disk_path_bytes)
+            full_path = os.path.join(self.path, path)
             try:
                 st = os.lstat(full_path)
             except OSError:
                 # File no longer exists
                 try:
-                    del index[repo_path_bytes]
+                    del index[path.encode(fsencoding)]
                 except KeyError:
                     pass  # already removed
             else:
                 blob = blob_from_path_and_stat(full_path, st)
                 self.object_store.add_object(blob)
-                index[repo_path_bytes] = index_entry_from_stat(st, blob.id, 0)
+                index[path.encode(fsencoding)] = index_entry_from_stat(st, blob.id, 0)
         index.write()
 
     def clone(self, target_path, mkdir=True, bare=False,
@@ -825,7 +815,7 @@ class Repo(BaseRepo):
             validate_path_element = validate_path_element_ntfs
         else:
             validate_path_element = validate_path_element_default
-        return build_index_from_tree(self._path_bytes, self.index_path(),
+        return build_index_from_tree(self.path, self.index_path(),
                 self.object_store, tree, honor_filemode=honor_filemode,
                 validate_path_element=validate_path_element)
 
@@ -835,7 +825,7 @@ class Repo(BaseRepo):
         :return: `ConfigFile` object for the ``.git/config`` file.
         """
         from dulwich.config import ConfigFile
-        path = os.path.join(self._controldir, b'config')
+        path = os.path.join(self._controldir, 'config')
         try:
             return ConfigFile.from_path(path)
         except (IOError, OSError) as e:
@@ -850,7 +840,7 @@ class Repo(BaseRepo):
 
         :return: A string describing the repository or None.
         """
-        path = os.path.join(self._controldir, b'description')
+        path = os.path.join(self._controldir, 'description')
         try:
             with GitFile(path, 'rb') as f:
                 return f.read()
@@ -868,17 +858,13 @@ class Repo(BaseRepo):
         :param description: Text to set as description for this repository.
         """
 
-        self._put_named_file(b'description', description)
+        self._put_named_file('description', description)
 
     @classmethod
     def _init_maybe_bare(cls, path, bare):
-        if not isinstance(path, bytes):
-            path_bytes = path.encode(sys.getfilesystemencoding())
-        else:
-            path_bytes = path
         for d in BASE_DIRECTORIES:
-            os.mkdir(os.path.join(path_bytes, *d))
-        DiskObjectStore.init(os.path.join(path_bytes, OBJECTDIR))
+            os.mkdir(os.path.join(path, *d))
+        DiskObjectStore.init(os.path.join(path, OBJECTDIR))
         ret = cls(path)
         ret.refs.set_symbolic_ref(b'HEAD', b"refs/heads/master")
         ret._init_files(bare)
@@ -892,13 +878,9 @@ class Repo(BaseRepo):
         :param mkdir: Whether to create the directory
         :return: `Repo` instance
         """
-        if not isinstance(path, bytes):
-            path_bytes = path.encode(sys.getfilesystemencoding())
-        else:
-            path_bytes = path
         if mkdir:
-            os.mkdir(path_bytes)
-        controldir = os.path.join(path_bytes, b'.git')
+            os.mkdir(path)
+        controldir = os.path.join(path, ".git")
         os.mkdir(controldir)
         cls._init_maybe_bare(controldir, False)
         return cls(path)

+ 2 - 2
dulwich/server.py

@@ -991,10 +991,10 @@ def update_server_info(repo):
     This generates info/refs and objects/info/packs,
     similar to "git update-server-info".
     """
-    repo._put_named_file(os.path.join(b'info', b'refs'),
+    repo._put_named_file(os.path.join('info', 'refs'),
         b"".join(generate_info_refs(repo)))
 
-    repo._put_named_file(os.path.join(b'objects', b'info', b'packs'),
+    repo._put_named_file(os.path.join('objects', 'info', 'packs'),
         b"".join(generate_objects_info_packs(repo)))
 
 

+ 0 - 6
dulwich/tests/compat/server_utils.py

@@ -23,7 +23,6 @@ import errno
 import os
 import shutil
 import socket
-import sys
 import tempfile
 
 from dulwich.repo import Repo
@@ -46,11 +45,6 @@ class _StubRepo(object):
     def __init__(self, name):
         temp_dir = tempfile.mkdtemp()
         self.path = os.path.join(temp_dir, name)
-        if not isinstance(self.path, bytes):
-            self._path_bytes = self.path.encode(sys.getfilesystemencoding())
-        else:
-            self._path_bytes = self.path
-
         os.mkdir(self.path)
 
     def close(self):

+ 3 - 6
dulwich/tests/compat/test_pack.py

@@ -24,7 +24,6 @@ import binascii
 import os
 import re
 import shutil
-import sys
 import tempfile
 
 from dulwich.pack import (
@@ -67,14 +66,12 @@ class TestPack(PackTests):
         require_git_version((1, 5, 0))
         super(TestPack, self).setUp()
         self._tempdir = tempfile.mkdtemp()
-        if not isinstance(self._tempdir, bytes):
-            self._tempdir = self._tempdir.encode(sys.getfilesystemencoding())
         self.addCleanup(shutil.rmtree, self._tempdir)
 
     def test_copy(self):
         with self.get_pack(pack1_sha) as origpack:
             self.assertSucceeds(origpack.index.check)
-            pack_path = os.path.join(self._tempdir, b'Elch')
+            pack_path = os.path.join(self._tempdir, "Elch")
             write_pack(pack_path, origpack.pack_tuples())
             output = run_git_or_fail(['verify-pack', '-v', pack_path])
             orig_shas = set(o.id for o in origpack.iterobjects())
@@ -86,7 +83,7 @@ class TestPack(PackTests):
             new_blob = Blob()
             new_blob.data = orig_blob.data + b'x'
             all_to_pack = list(orig_pack.pack_tuples()) + [(new_blob, None)]
-        pack_path = os.path.join(self._tempdir, b'pack_with_deltas')
+        pack_path = os.path.join(self._tempdir, 'pack_with_deltas')
         write_pack(pack_path, all_to_pack, deltify=True)
         output = run_git_or_fail(['verify-pack', '-v', pack_path])
         self.assertEqual(set(x[0].id for x in all_to_pack),
@@ -110,7 +107,7 @@ class TestPack(PackTests):
             new_blob_2.data = new_blob.data + b'y'
             all_to_pack = list(orig_pack.pack_tuples()) + [(new_blob, None),
                                                            (new_blob_2, None)]
-        pack_path = os.path.join(self._tempdir, b'pack_with_deltas')
+        pack_path = os.path.join(self._tempdir, 'pack_with_deltas')
         write_pack(pack_path, all_to_pack, deltify=True)
         output = run_git_or_fail(['verify-pack', '-v', pack_path])
         self.assertEqual(set(x[0].id for x in all_to_pack),

+ 12 - 14
dulwich/tests/test_file.py

@@ -92,9 +92,7 @@ class GitFileTests(TestCase):
     def setUp(self):
         super(GitFileTests, self).setUp()
         self._tempdir = tempfile.mkdtemp()
-        if not isinstance(self._tempdir, bytes):
-            self._tempdir = self._tempdir.encode(sys.getfilesystemencoding())
-        f = open(self.path(b'foo'), 'wb')
+        f = open(self.path('foo'), 'wb')
         f.write(b'foo contents')
         f.close()
 
@@ -106,7 +104,7 @@ class GitFileTests(TestCase):
         return os.path.join(self._tempdir, filename)
 
     def test_invalid(self):
-        foo = self.path(b'foo')
+        foo = self.path('foo')
         self.assertRaises(IOError, GitFile, foo, mode='r')
         self.assertRaises(IOError, GitFile, foo, mode='ab')
         self.assertRaises(IOError, GitFile, foo, mode='r+b')
@@ -114,7 +112,7 @@ class GitFileTests(TestCase):
         self.assertRaises(IOError, GitFile, foo, mode='a+bU')
 
     def test_readonly(self):
-        f = GitFile(self.path(b'foo'), 'rb')
+        f = GitFile(self.path('foo'), 'rb')
         self.assertTrue(isinstance(f, io.IOBase))
         self.assertEqual(b'foo contents', f.read())
         self.assertEqual(b'', f.read())
@@ -123,13 +121,13 @@ class GitFileTests(TestCase):
         f.close()
 
     def test_default_mode(self):
-        f = GitFile(self.path(b'foo'))
+        f = GitFile(self.path('foo'))
         self.assertEqual(b'foo contents', f.read())
         f.close()
 
     def test_write(self):
-        foo = self.path(b'foo')
-        foo_lock = foo + b'.lock'
+        foo = self.path('foo')
+        foo_lock = '%s.lock' % foo
 
         orig_f = open(foo, 'rb')
         self.assertEqual(orig_f.read(), b'foo contents')
@@ -152,7 +150,7 @@ class GitFileTests(TestCase):
         new_f.close()
 
     def test_open_twice(self):
-        foo = self.path(b'foo')
+        foo = self.path('foo')
         f1 = GitFile(foo, 'wb')
         f1.write(b'new')
         try:
@@ -171,8 +169,8 @@ class GitFileTests(TestCase):
         f.close()
 
     def test_abort(self):
-        foo = self.path(b'foo')
-        foo_lock = foo + b'.lock'
+        foo = self.path('foo')
+        foo_lock = '%s.lock' % foo
 
         orig_f = open(foo, 'rb')
         self.assertEqual(orig_f.read(), b'foo contents')
@@ -189,7 +187,7 @@ class GitFileTests(TestCase):
         new_orig_f.close()
 
     def test_abort_close(self):
-        foo = self.path(b'foo')
+        foo = self.path('foo')
         f = GitFile(foo, 'wb')
         f.abort()
         try:
@@ -205,11 +203,11 @@ class GitFileTests(TestCase):
             self.fail()
 
     def test_abort_close_removed(self):
-        foo = self.path(b'foo')
+        foo = self.path('foo')
         f = GitFile(foo, 'wb')
 
         f._file.close()
-        os.remove(foo + b'.lock')
+        os.remove(foo+".lock")
 
         f.abort()
         self.assertTrue(f._closed)

+ 2 - 2
dulwich/tests/test_grafts.py

@@ -163,7 +163,7 @@ class GraftsInRepoTests(GraftsInRepositoryBase, TestCase):
 
     def test_init_with_empty_info_grafts(self):
         r = self._repo
-        r._put_named_file(os.path.join(b'info', b'grafts'), b'')
+        r._put_named_file(os.path.join('info', 'grafts'), b'')
 
         r = Repo(self._repo_dir)
         self.assertEqual({}, r._graftpoints)
@@ -171,7 +171,7 @@ class GraftsInRepoTests(GraftsInRepositoryBase, TestCase):
     def test_init_with_info_grafts(self):
         r = self._repo
         r._put_named_file(
-            os.path.join(b'info', b'grafts'),
+            os.path.join('info', 'grafts'),
             self._shas[-1] + b' ' + self._shas[0])
 
         r = Repo(self._repo_dir)

+ 7 - 16
dulwich/tests/test_hooks.py

@@ -50,14 +50,11 @@ exit 1
 exit 0
 """
 
-        repo_dir = tempfile.mkdtemp()
-        if not isinstance(repo_dir, bytes):
-            repo_dir = repo_dir.encode(sys.getfilesystemencoding())
-
-        os.mkdir(os.path.join(repo_dir, b'hooks'))
+        repo_dir = os.path.join(tempfile.mkdtemp())
+        os.mkdir(os.path.join(repo_dir, 'hooks'))
         self.addCleanup(shutil.rmtree, repo_dir)
 
-        pre_commit = os.path.join(repo_dir, b'hooks', b'pre-commit')
+        pre_commit = os.path.join(repo_dir, 'hooks', 'pre-commit')
         hook = PreCommitShellHook(repo_dir)
 
         with open(pre_commit, 'w') as f:
@@ -83,13 +80,10 @@ exit 0
 """
 
         repo_dir = os.path.join(tempfile.mkdtemp())
-        if not isinstance(repo_dir, bytes):
-            repo_dir = repo_dir.encode(sys.getfilesystemencoding())
-
-        os.mkdir(os.path.join(repo_dir, b'hooks'))
+        os.mkdir(os.path.join(repo_dir, 'hooks'))
         self.addCleanup(shutil.rmtree, repo_dir)
 
-        commit_msg = os.path.join(repo_dir, b'hooks', b'commit-msg')
+        commit_msg = os.path.join(repo_dir, 'hooks', 'commit-msg')
         hook = CommitMsgShellHook(repo_dir)
 
         with open(commit_msg, 'w') as f:
@@ -117,13 +111,10 @@ exit 1
 """
 
         repo_dir = os.path.join(tempfile.mkdtemp())
-        if not isinstance(repo_dir, bytes):
-            repo_dir = repo_dir.encode(sys.getfilesystemencoding())
-
-        os.mkdir(os.path.join(repo_dir, b'hooks'))
+        os.mkdir(os.path.join(repo_dir, 'hooks'))
         self.addCleanup(shutil.rmtree, repo_dir)
 
-        post_commit = os.path.join(repo_dir, b'hooks', b'post-commit')
+        post_commit = os.path.join(repo_dir, 'hooks', 'post-commit')
         hook = PostCommitShellHook(repo_dir)
 
         with open(post_commit, 'w') as f:

+ 5 - 12
dulwich/tests/test_object_store.py

@@ -23,7 +23,6 @@ from contextlib import closing
 from io import BytesIO
 import os
 import shutil
-import sys
 import tempfile
 
 from dulwich.index import (
@@ -264,8 +263,6 @@ class DiskObjectStoreTests(PackBasedObjectStoreTests, TestCase):
     def setUp(self):
         TestCase.setUp(self)
         self.store_dir = tempfile.mkdtemp()
-        if not isinstance(self.store_dir, bytes):
-            self.store_dir = self.store_dir.encode(sys.getfilesystemencoding())
         self.addCleanup(shutil.rmtree, self.store_dir)
         self.store = DiskObjectStore.init(self.store_dir)
 
@@ -275,8 +272,6 @@ class DiskObjectStoreTests(PackBasedObjectStoreTests, TestCase):
 
     def test_alternates(self):
         alternate_dir = tempfile.mkdtemp()
-        if not isinstance(alternate_dir, bytes):
-            alternate_dir = alternate_dir.encode(sys.getfilesystemencoding())
         self.addCleanup(shutil.rmtree, alternate_dir)
         alternate_store = DiskObjectStore(alternate_dir)
         b2 = make_object(Blob, data=b"yummy data")
@@ -290,17 +285,15 @@ class DiskObjectStoreTests(PackBasedObjectStoreTests, TestCase):
     def test_add_alternate_path(self):
         store = DiskObjectStore(self.store_dir)
         self.assertEqual([], list(store._read_alternate_paths()))
-        store.add_alternate_path(b'/foo/path')
-        self.assertEqual([b'/foo/path'], list(store._read_alternate_paths()))
-        store.add_alternate_path(b'/bar/path')
+        store.add_alternate_path("/foo/path")
+        self.assertEqual(["/foo/path"], list(store._read_alternate_paths()))
+        store.add_alternate_path("/bar/path")
         self.assertEqual(
-            [b'/foo/path', b'/bar/path'],
+            ["/foo/path", "/bar/path"],
             list(store._read_alternate_paths()))
 
     def test_rel_alternative_path(self):
         alternate_dir = tempfile.mkdtemp()
-        if not isinstance(alternate_dir, bytes):
-            alternate_dir = alternate_dir.encode(sys.getfilesystemencoding())
         self.addCleanup(shutil.rmtree, alternate_dir)
         alternate_store = DiskObjectStore(alternate_dir)
         b2 = make_object(Blob, data=b"yummy data")
@@ -314,7 +307,7 @@ class DiskObjectStoreTests(PackBasedObjectStoreTests, TestCase):
 
     def test_pack_dir(self):
         o = DiskObjectStore(self.store_dir)
-        self.assertEqual(os.path.join(self.store_dir, b'pack'), o.pack_dir)
+        self.assertEqual(os.path.join(self.store_dir, "pack"), o.pack_dir)
 
     def test_add_pack(self):
         o = DiskObjectStore(self.store_dir)

+ 6 - 11
dulwich/tests/test_objects.py

@@ -29,7 +29,6 @@ from itertools import (
     )
 import os
 import stat
-import sys
 import warnings
 from contextlib import contextmanager
 
@@ -86,23 +85,21 @@ class BlobReadTests(TestCase):
     """Test decompression of blobs"""
 
     def get_sha_file(self, cls, base, sha):
-        dir = os.path.join(
-            os.path.dirname(__file__.encode(sys.getfilesystemencoding())),
-            b'data', base)
+        dir = os.path.join(os.path.dirname(__file__), 'data', base)
         return cls.from_path(hex_to_filename(dir, sha))
 
     def get_blob(self, sha):
         """Return the blob named sha from the test data dir"""
-        return self.get_sha_file(Blob, b'blobs', sha)
+        return self.get_sha_file(Blob, 'blobs', sha)
 
     def get_tree(self, sha):
-        return self.get_sha_file(Tree, b'trees', sha)
+        return self.get_sha_file(Tree, 'trees', sha)
 
     def get_tag(self, sha):
-        return self.get_sha_file(Tag, b'tags', sha)
+        return self.get_sha_file(Tag, 'tags', sha)
 
     def commit(self, sha):
-        return self.get_sha_file(Commit, b'commits', sha)
+        return self.get_sha_file(Commit, 'commits', sha)
 
     def test_decompress_simple_blob(self):
         b = self.get_blob(a_sha)
@@ -705,9 +702,7 @@ class TreeTests(ShaFileCheckTests):
         self.assertEqual(_SORTED_TREE_ITEMS, x.items())
 
     def _do_test_parse_tree(self, parse_tree):
-        dir = os.path.join(
-            os.path.dirname(__file__.encode(sys.getfilesystemencoding())),
-            b'data', b'trees')
+        dir = os.path.join(os.path.dirname(__file__), 'data', 'trees')
         o = Tree.from_path(hex_to_filename(dir, tree_sha))
         self.assertEqual([(b'a', 0o100644, a_sha), (b'b', 0o100644, b_sha)],
                          list(parse_tree(o.as_raw_string())))

+ 18 - 26
dulwich/tests/test_pack.py

@@ -24,7 +24,6 @@ from io import BytesIO
 from hashlib import sha1
 import os
 import shutil
-import sys
 import tempfile
 import zlib
 
@@ -90,24 +89,21 @@ class PackTests(TestCase):
     def setUp(self):
         super(PackTests, self).setUp()
         self.tempdir = tempfile.mkdtemp()
-        if not isinstance(self.tempdir, bytes):
-            self.tempdir = self.tempdir.encode(sys.getfilesystemencoding())
         self.addCleanup(shutil.rmtree, self.tempdir)
 
-    datadir = os.path.abspath(
-        os.path.join(os.path.dirname(__file__.encode(sys.getfilesystemencoding())),
-        b'data/packs'))
+    datadir = os.path.abspath(os.path.join(os.path.dirname(__file__),
+        'data/packs'))
 
     def get_pack_index(self, sha):
         """Returns a PackIndex from the datadir with the given sha"""
-        return load_pack_index(os.path.join(self.datadir, b'pack-' + sha + b'.idx'))
+        return load_pack_index(os.path.join(self.datadir, 'pack-%s.idx' % sha.decode('ascii')))
 
     def get_pack_data(self, sha):
         """Returns a PackData object from the datadir with the given sha"""
-        return PackData(os.path.join(self.datadir, b'pack-' + sha + b'.pack'))
+        return PackData(os.path.join(self.datadir, 'pack-%s.pack' % sha.decode('ascii')))
 
     def get_pack(self, sha):
-        return Pack(os.path.join(self.datadir, b'pack-' + sha))
+        return Pack(os.path.join(self.datadir, 'pack-%s' % sha.decode('ascii')))
 
     def assertSucceeds(self, func, *args, **kwargs):
         try:
@@ -208,7 +204,7 @@ class TestPackData(PackTests):
         self.get_pack_data(pack1_sha).close()
 
     def test_from_file(self):
-        path = os.path.join(self.datadir, b'pack-' + pack1_sha + b'.pack')
+        path = os.path.join(self.datadir, 'pack-%s.pack' % pack1_sha.decode('ascii'))
         with open(path, 'rb') as f:
             PackData.from_file(f, os.path.getsize(path))
 
@@ -251,7 +247,7 @@ class TestPackData(PackTests):
 
     def test_create_index_v1(self):
         with self.get_pack_data(pack1_sha) as p:
-            filename = os.path.join(self.tempdir, b'v1test.idx')
+            filename = os.path.join(self.tempdir, 'v1test.idx')
             p.create_index_v1(filename)
             idx1 = load_pack_index(filename)
             idx2 = self.get_pack_index(pack1_sha)
@@ -259,7 +255,7 @@ class TestPackData(PackTests):
 
     def test_create_index_v2(self):
         with self.get_pack_data(pack1_sha) as p:
-            filename = os.path.join(self.tempdir, b'v2test.idx')
+            filename = os.path.join(self.tempdir, 'v2test.idx')
             p.create_index_v2(filename)
             idx1 = load_pack_index(filename)
             idx2 = self.get_pack_index(pack1_sha)
@@ -334,7 +330,7 @@ class TestPack(PackTests):
     def test_copy(self):
         with self.get_pack(pack1_sha) as origpack:
             self.assertSucceeds(origpack.index.check)
-            basename = os.path.join(self.tempdir, b'Elch')
+            basename = os.path.join(self.tempdir, 'Elch')
             write_pack(basename, origpack.pack_tuples())
 
             with Pack(basename) as newpack:
@@ -357,7 +353,7 @@ class TestPack(PackTests):
             self.assertEqual([], commit.parents)
 
     def _copy_pack(self, origpack):
-        basename = os.path.join(self.tempdir, b'somepack')
+        basename = os.path.join(self.tempdir, 'somepack')
         write_pack(basename, origpack.pack_tuples())
         return Pack(basename)
 
@@ -405,7 +401,7 @@ class TestPack(PackTests):
             write_pack_header(bad_file, 9999)
             bad_file.write(data._file.read())
             bad_file = BytesIO(bad_file.getvalue())
-            bad_data = PackData(b'', file=bad_file)
+            bad_data = PackData('', file=bad_file)
             bad_pack = Pack.from_lazy_objects(lambda: bad_data, lambda: index)
             self.assertRaises(AssertionError, lambda: bad_pack.data)
             self.assertRaises(AssertionError,
@@ -418,7 +414,7 @@ class TestPack(PackTests):
 
             data._file.seek(0)
             bad_file = BytesIO(data._file.read()[:-20] + (b'\xff' * 20))
-            bad_data = PackData(b'', file=bad_file)
+            bad_data = PackData('', file=bad_file)
             bad_pack = Pack.from_lazy_objects(lambda: bad_data, lambda: index)
             self.assertRaises(ChecksumMismatch, lambda: bad_pack.data)
             self.assertRaises(ChecksumMismatch, lambda:
@@ -448,12 +444,10 @@ class TestThinPack(PackTests):
         # Build a thin pack. 'foo' is as an external reference, 'bar' an
         # internal reference.
         self.pack_dir = tempfile.mkdtemp()
-        if not isinstance(self.pack_dir, bytes):
-            self.pack_dir = self.pack_dir.encode(sys.getfilesystemencoding())
         self.addCleanup(shutil.rmtree, self.pack_dir)
-        self.pack_prefix = os.path.join(self.pack_dir, b'pack')
+        self.pack_prefix = os.path.join(self.pack_dir, 'pack')
 
-        with open(self.pack_prefix + b'.pack', 'wb') as f:
+        with open(self.pack_prefix + '.pack', 'wb') as f:
             build_pack(f, [
                 (REF_DELTA, (self.blobs[b'foo'].id, b'foo1234')),
                 (Blob.type_num, b'bar'),
@@ -464,7 +458,7 @@ class TestThinPack(PackTests):
         with self.make_pack(True) as pack:
             with PackData(pack._data_path) as data:
                 data.pack = pack
-                data.create_index(self.pack_prefix + b'.idx')
+                data.create_index(self.pack_prefix + '.idx')
 
         del self.store[self.blobs[b'bar'].id]
 
@@ -543,7 +537,7 @@ class BaseTestPackIndexWriting(object):
         raise NotImplementedError(self.index)
 
     def test_empty(self):
-        idx = self.index(b'empty.idx', [], pack_checksum)
+        idx = self.index('empty.idx', [], pack_checksum)
         self.assertEqual(idx.get_pack_checksum(), pack_checksum)
         self.assertEqual(0, len(idx))
 
@@ -556,7 +550,7 @@ class BaseTestPackIndexWriting(object):
             self.assertRaises(TypeError, self.index, 'single.idx',
                 entries, pack_checksum)
             return
-        idx = self.index(b'single.idx', entries, pack_checksum)
+        idx = self.index('single.idx', entries, pack_checksum)
         self.assertEqual(idx.get_pack_checksum(), pack_checksum)
         self.assertEqual(2, len(idx))
         actual_entries = list(idx.iterentries())
@@ -574,7 +568,7 @@ class BaseTestPackIndexWriting(object):
     def test_single(self):
         entry_sha = hex_to_sha('6f670c0fb53f9463760b7295fbb814e965fb20c8')
         my_entries = [(entry_sha, 178, 42)]
-        idx = self.index(b'single.idx', my_entries, pack_checksum)
+        idx = self.index('single.idx', my_entries, pack_checksum)
         self.assertEqual(idx.get_pack_checksum(), pack_checksum)
         self.assertEqual(1, len(idx))
         actual_entries = list(idx.iterentries())
@@ -594,8 +588,6 @@ class BaseTestFilePackIndexWriting(BaseTestPackIndexWriting):
 
     def setUp(self):
         self.tempdir = tempfile.mkdtemp()
-        if not isinstance(self.tempdir, bytes):
-            self.tempdir = self.tempdir.encode(sys.getfilesystemencoding())
 
     def tearDown(self):
         shutil.rmtree(self.tempdir)

+ 3 - 3
dulwich/tests/test_porcelain.py

@@ -82,7 +82,7 @@ class UpdateServerInfoTests(PorcelainTestCase):
         self.repo.refs[b"refs/heads/foo"] = c3.id
         porcelain.update_server_info(self.repo.path)
         self.assertTrue(os.path.exists(os.path.join(self.repo.controldir(),
-            b'info', b'refs')))
+            'info', 'refs')))
 
 
 class CommitTests(PorcelainTestCase):
@@ -288,7 +288,7 @@ class SymbolicRefTests(PorcelainTestCase):
         porcelain.symbolic_ref(self.repo.path, b'force_foobar', force=True)
 
         #test if we actually changed the file
-        with self.repo.get_named_file(b'HEAD') as f:
+        with self.repo.get_named_file('HEAD') as f:
             new_ref = f.read()
         self.assertEqual(new_ref, b'ref: refs/heads/force_foobar\n')
 
@@ -308,7 +308,7 @@ class SymbolicRefTests(PorcelainTestCase):
         porcelain.symbolic_ref(self.repo.path, b'develop')
 
         #test if we actually changed the file
-        with self.repo.get_named_file(b'HEAD') as f:
+        with self.repo.get_named_file('HEAD') as f:
             new_ref = f.read()
         self.assertEqual(new_ref, b'ref: refs/heads/develop\n')
 

+ 10 - 10
dulwich/tests/test_refs.py

@@ -308,7 +308,7 @@ class DiskRefsContainerTests(RefsContainerTests, TestCase):
 
     def test_setitem(self):
         RefsContainerTests.test_setitem(self)
-        f = open(os.path.join(self._refs.path, b'refs', b'some', b'ref'), 'rb')
+        f = open(os.path.join(self._refs.path, 'refs', 'some', 'ref'), 'rb')
         self.assertEqual(b'42d06bd4b77fed026b154d16493e5deab78f02ec',
                          f.read()[:40])
         f.close()
@@ -319,12 +319,12 @@ class DiskRefsContainerTests(RefsContainerTests, TestCase):
         self.assertEqual(ones, self._refs[b'HEAD'])
 
         # ensure HEAD was not modified
-        f = open(os.path.join(self._refs.path, b'HEAD'), 'rb')
+        f = open(os.path.join(self._refs.path, 'HEAD'), 'rb')
         self.assertEqual(b'ref: refs/heads/master', next(iter(f)).rstrip(b'\n'))
         f.close()
 
         # ensure the symbolic link was written through
-        f = open(os.path.join(self._refs.path, b'refs', b'heads', b'master'), 'rb')
+        f = open(os.path.join(self._refs.path, 'refs', 'heads', 'master'), 'rb')
         self.assertEqual(ones, f.read()[:40])
         f.close()
 
@@ -336,9 +336,9 @@ class DiskRefsContainerTests(RefsContainerTests, TestCase):
 
         # ensure lockfile was deleted
         self.assertFalse(os.path.exists(
-            os.path.join(self._refs.path, b'refs', b'heads', b'master.lock')))
+            os.path.join(self._refs.path, 'refs', 'heads', 'master.lock')))
         self.assertFalse(os.path.exists(
-            os.path.join(self._refs.path, b'HEAD.lock')))
+            os.path.join(self._refs.path, 'HEAD.lock')))
 
     def test_add_if_new_packed(self):
         # don't overwrite packed ref
@@ -377,7 +377,7 @@ class DiskRefsContainerTests(RefsContainerTests, TestCase):
 
     def test_delitem(self):
         RefsContainerTests.test_delitem(self)
-        ref_file = os.path.join(self._refs.path, b'refs', b'heads', b'master')
+        ref_file = os.path.join(self._refs.path, 'refs', 'heads', 'master')
         self.assertFalse(os.path.exists(ref_file))
         self.assertFalse(b'refs/heads/master' in self._refs.get_packed_refs())
 
@@ -388,7 +388,7 @@ class DiskRefsContainerTests(RefsContainerTests, TestCase):
         self.assertRaises(KeyError, lambda: self._refs[b'HEAD'])
         self.assertEqual(b'42d06bd4b77fed026b154d16493e5deab78f02ec',
                          self._refs[b'refs/heads/master'])
-        self.assertFalse(os.path.exists(os.path.join(self._refs.path, b'HEAD')))
+        self.assertFalse(os.path.exists(os.path.join(self._refs.path, 'HEAD')))
 
     def test_remove_if_equals_symref(self):
         # HEAD is a symref, so shouldn't equal its dereferenced value
@@ -404,12 +404,12 @@ class DiskRefsContainerTests(RefsContainerTests, TestCase):
                          self._refs.read_loose_ref(b'HEAD'))
 
         self.assertFalse(os.path.exists(
-            os.path.join(self._refs.path, b'refs', b'heads', b'master.lock')))
+            os.path.join(self._refs.path, 'refs', 'heads', 'master.lock')))
         self.assertFalse(os.path.exists(
-            os.path.join(self._refs.path, b'HEAD.lock')))
+            os.path.join(self._refs.path, 'HEAD.lock')))
 
     def test_remove_packed_without_peeled(self):
-        refs_file = os.path.join(self._repo._controldir, b'packed-refs')
+        refs_file = os.path.join(self._repo.path, 'packed-refs')
         f = GitFile(refs_file)
         refs_data = f.read()
         f.close()

+ 38 - 91
dulwich/tests/test_repository.py

@@ -21,6 +21,7 @@
 """Tests for the repository."""
 
 from contextlib import closing
+import locale
 import os
 import stat
 import shutil
@@ -51,21 +52,9 @@ from dulwich.tests.utils import (
 missing_sha = b'b91fa4d900e17e99b433218e988c4eb4a3e9a097'
 
 
-def mkdtemp_bytes():
-    tmp_dir = tempfile.mkdtemp()
-    if sys.version_info[0] > 2:
-        tmp_dir = tmp_dir.encode(sys.getfilesystemencoding())
-    return tmp_dir
-
 def mkdtemp_unicode():
     suffix = u'déłwíçh'
-    if sys.version_info[0] == 2:
-        suffix = suffix.encode(sys.getfilesystemencoding())
-    tmp_dir = tempfile.mkdtemp(suffix=suffix)
-    if sys.version_info[0] == 2:
-        tmp_dir = tmp_dir.decode(sys.getfilesystemencoding())
-    return tmp_dir
-
+    return tempfile.mkdtemp(suffix=suffix)
 
 
 class CreateRepositoryTests(TestCase):
@@ -80,64 +69,46 @@ class CreateRepositoryTests(TestCase):
 
     def _check_repo_contents(self, repo, expect_bare):
         self.assertEqual(expect_bare, repo.bare)
-        self.assertFileContentsEqual(b'Unnamed repository', repo, b'description')
-        self.assertFileContentsEqual(b'', repo, os.path.join(b'info', b'exclude'))
-        self.assertFileContentsEqual(None, repo, b'nonexistent file')
+        self.assertFileContentsEqual(b'Unnamed repository', repo, 'description')
+        self.assertFileContentsEqual(b'', repo, os.path.join('info', 'exclude'))
+        self.assertFileContentsEqual(None, repo, 'nonexistent file')
         barestr = b'bare = ' + str(expect_bare).lower().encode('ascii')
-        with repo.get_named_file(b'config') as f:
+        with repo.get_named_file('config') as f:
             config_text = f.read()
             self.assertTrue(barestr in config_text, "%r" % config_text)
 
-
-class CreateMemoryRepositoryTests(CreateRepositoryTests):
-
     def test_create_memory(self):
         repo = MemoryRepo.init_bare([], {})
         self._check_repo_contents(repo, True)
 
-
-class CreateRepositoryBytesRootTests(CreateRepositoryTests):
-
-    def mkdtemp(self):
-        tmp_dir = mkdtemp_bytes()
-        return tmp_dir, tmp_dir
-
     def test_create_disk_bare(self):
-        tmp_dir, tmp_dir_bytes = self.mkdtemp()
+        tmp_dir = mkdtemp_unicode()
         self.addCleanup(shutil.rmtree, tmp_dir)
         repo = Repo.init_bare(tmp_dir)
-        self.assertEqual(tmp_dir_bytes, repo._controldir)
+        self.assertEqual(tmp_dir, repo._controldir)
         self._check_repo_contents(repo, True)
 
     def test_create_disk_non_bare(self):
-        tmp_dir, tmp_dir_bytes = self.mkdtemp()
+        tmp_dir = mkdtemp_unicode()
         self.addCleanup(shutil.rmtree, tmp_dir)
         repo = Repo.init(tmp_dir)
-        self.assertEqual(os.path.join(tmp_dir_bytes, b'.git'), repo._controldir)
+        self.assertEqual(os.path.join(tmp_dir, '.git'), repo._controldir)
         self._check_repo_contents(repo, False)
 
 
-class CreateRepositoryUnicodeRootTests(CreateRepositoryBytesRootTests):
-
-    def mktemp(self):
-        tmp_dir = mkdtemp_unicode()
-        tmp_dir_bytes = tmp_dir.encode(sys.getfilesystemencoding())
-        return tmp_dir, tmp_dir_bytes
-
-
-class RepositoryBytesRootTests(TestCase):
+class RepositoryRootTests(TestCase):
 
     def setUp(self):
-        super(RepositoryBytesRootTests, self).setUp()
+        super(RepositoryRootTests, self).setUp()
         self._repo = None
 
     def tearDown(self):
         if self._repo is not None:
             tear_down_repo(self._repo)
-        super(RepositoryBytesRootTests, self).tearDown()
+        super(RepositoryRootTests, self).tearDown()
 
     def mkdtemp(self):
-        return mkdtemp_bytes()
+        return mkdtemp_unicode()
 
     def open_repo(self, name):
         temp_dir = self.mkdtemp()
@@ -145,7 +116,7 @@ class RepositoryBytesRootTests(TestCase):
 
     def test_simple_props(self):
         r = self._repo = self.open_repo('a.git')
-        self.assertEqual(r.controldir(), r._path_bytes)
+        self.assertEqual(r.controldir(), r.path)
 
     def test_setitem(self):
         r = self._repo = self.open_repo('a.git')
@@ -413,11 +384,11 @@ class RepositoryBytesRootTests(TestCase):
         if os.name != 'posix':
             self.skipTest('shell hook tests requires POSIX shell')
 
-        pre_commit_fail = b"""#!/bin/sh
+        pre_commit_fail = """#!/bin/sh
 exit 1
 """
 
-        pre_commit_success = b"""#!/bin/sh
+        pre_commit_success = """#!/bin/sh
 exit 0
 """
 
@@ -425,9 +396,9 @@ exit 0
         r = Repo.init(repo_dir)
         self.addCleanup(shutil.rmtree, repo_dir)
 
-        pre_commit = os.path.join(r.controldir(), b'hooks', b'pre-commit')
+        pre_commit = os.path.join(r.controldir(), 'hooks', 'pre-commit')
 
-        with open(pre_commit, 'wb') as f:
+        with open(pre_commit, 'w') as f:
             f.write(pre_commit_fail)
         os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
@@ -437,7 +408,7 @@ exit 0
                           commit_timestamp=12345, commit_timezone=0,
                           author_timestamp=12345, author_timezone=0)
 
-        with open(pre_commit, 'wb') as f:
+        with open(pre_commit, 'w') as f:
             f.write(pre_commit_success)
         os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
@@ -453,11 +424,11 @@ exit 0
         if os.name != 'posix':
             self.skipTest('shell hook tests requires POSIX shell')
 
-        commit_msg_fail = b"""#!/bin/sh
+        commit_msg_fail = """#!/bin/sh
 exit 1
 """
 
-        commit_msg_success = b"""#!/bin/sh
+        commit_msg_success = """#!/bin/sh
 exit 0
 """
 
@@ -465,9 +436,9 @@ exit 0
         r = Repo.init(repo_dir)
         self.addCleanup(shutil.rmtree, repo_dir)
 
-        commit_msg = os.path.join(r.controldir(), b'hooks', b'commit-msg')
+        commit_msg = os.path.join(r.controldir(), 'hooks', 'commit-msg')
 
-        with open(commit_msg, 'wb') as f:
+        with open(commit_msg, 'w') as f:
             f.write(commit_msg_fail)
         os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
@@ -477,7 +448,7 @@ exit 0
                           commit_timestamp=12345, commit_timezone=0,
                           author_timestamp=12345, author_timezone=0)
 
-        with open(commit_msg, 'wb') as f:
+        with open(commit_msg, 'w') as f:
             f.write(commit_msg_success)
         os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
@@ -494,15 +465,11 @@ exit 0
             self.skipTest('shell hook tests requires POSIX shell')
 
         repo_dir = self.mkdtemp()
-        if isinstance(repo_dir, bytes):
-            repo_dir_str = repo_dir.decode(sys.getfilesystemencoding())
-        else:
-            repo_dir_str = repo_dir
 
         r = Repo.init(repo_dir)
         self.addCleanup(shutil.rmtree, repo_dir)
 
-        (fd, path) = tempfile.mkstemp(dir=repo_dir_str)
+        (fd, path) = tempfile.mkstemp(dir=repo_dir)
         os.close(fd)
         post_commit_msg = """#!/bin/sh
 rm """ + path + """
@@ -516,10 +483,10 @@ rm """ + path + """
             author_timestamp=12345, author_timezone=0)
         self.assertEqual([], r[root_sha].parents)
 
-        post_commit = os.path.join(r.controldir(), b'hooks', b'post-commit')
+        post_commit = os.path.join(r.controldir(), 'hooks', 'post-commit')
 
-        with open(post_commit, 'w') as f:
-            f.write(post_commit_msg)
+        with open(post_commit, 'wb') as f:
+            f.write(post_commit_msg.encode(locale.getpreferredencoding()))
         os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
 
         commit_sha = r.do_commit(
@@ -556,13 +523,7 @@ exit 1
         self.assertEqual([commit_sha], r[commit_sha2].parents)
 
 
-class RepositoryUnicodeRootTests(RepositoryBytesRootTests):
-
-    def mktemp(self):
-        return mkdtemp_unicode()
-
-
-class BuildRepoBytesRootTests(TestCase):
+class BuildRepoRootTests(TestCase):
     """Tests that build on-disk repos from scratch.
 
     Repos live in a temp dir and are torn down after each test. They start with
@@ -570,13 +531,10 @@ class BuildRepoBytesRootTests(TestCase):
     """
 
     def get_repo_dir(self):
-        return os.path.join(mkdtemp_bytes(), b'test')
-
-    def get_a_filename(self):
-        return b'a'
+        return os.path.join(mkdtemp_unicode(), 'test')
 
     def setUp(self):
-        super(BuildRepoBytesRootTests, self).setUp()
+        super(BuildRepoRootTests, self).setUp()
         self._repo_dir = self.get_repo_dir()
         os.makedirs(self._repo_dir)
         r = self._repo = Repo.init(self._repo_dir)
@@ -584,7 +542,7 @@ class BuildRepoBytesRootTests(TestCase):
         self.assertEqual(b'ref: refs/heads/master', r.refs.read_ref(b'HEAD'))
         self.assertRaises(KeyError, lambda: r.refs[b'refs/heads/master'])
 
-        with open(os.path.join(r._path_bytes, b'a'), 'wb') as f:
+        with open(os.path.join(r.path, 'a'), 'wb') as f:
             f.write(b'file contents')
         r.stage(['a'])
         commit_sha = r.do_commit(b'msg',
@@ -597,7 +555,7 @@ class BuildRepoBytesRootTests(TestCase):
 
     def tearDown(self):
         tear_down_repo(self._repo)
-        super(BuildRepoBytesRootTests, self).tearDown()
+        super(BuildRepoRootTests, self).tearDown()
 
     def test_build_repo(self):
         r = self._repo
@@ -610,7 +568,7 @@ class BuildRepoBytesRootTests(TestCase):
 
     def test_commit_modified(self):
         r = self._repo
-        with open(os.path.join(r._path_bytes, b'a'), 'wb') as f:
+        with open(os.path.join(r.path, 'a'), 'wb') as f:
             f.write(b'new contents')
         r.stage(['a'])
         commit_sha = r.do_commit(b'modified a',
@@ -626,7 +584,7 @@ class BuildRepoBytesRootTests(TestCase):
     @skipIf(sys.platform == 'win32', 'Requires symlink support')
     def test_commit_symlink(self):
         r = self._repo
-        os.symlink('a', os.path.join(r._path_bytes, b'b'))
+        os.symlink('a', os.path.join(r.path, 'b'))
         r.stage(['a', 'b'])
         commit_sha = r.do_commit(b'Symlink b',
                                  committer=b'Test Committer <test@nodomain.com>',
@@ -640,7 +598,7 @@ class BuildRepoBytesRootTests(TestCase):
 
     def test_commit_deleted(self):
         r = self._repo
-        os.remove(os.path.join(r._path_bytes, b'a'))
+        os.remove(os.path.join(r.path, 'a'))
         r.stage(['a'])
         commit_sha = r.do_commit(b'deleted a',
                                  committer=b'Test Committer <test@nodomain.com>',
@@ -802,17 +760,6 @@ class BuildRepoBytesRootTests(TestCase):
 
     def test_stage_deleted(self):
         r = self._repo
-        os.remove(os.path.join(r._path_bytes, b'a'))
+        os.remove(os.path.join(r.path, 'a'))
         r.stage(['a'])
         r.stage(['a'])  # double-stage a deleted path
-
-
-class BuildRepoUnicodeRootTests(TestCase):
-    """Tests that build on-disk repos from scratch.
-
-    Repos live in a temp dir and are torn down after each test. They start with
-    a single commit in master having single file named 'a'.
-    """
-
-    def get_repo_dir(self):
-        return os.path.join(mkdtemp_unicode(), 'test')

+ 1 - 1
dulwich/tests/utils.py

@@ -83,7 +83,7 @@ def open_repo(name, temp_dir=None):
 def tear_down_repo(repo):
     """Tear down a test repository."""
     repo.close()
-    temp_dir = os.path.dirname(repo._path_bytes.rstrip(os.sep.encode(sys.getfilesystemencoding())))
+    temp_dir = os.path.dirname(repo.path.rstrip(os.sep))
     shutil.rmtree(temp_dir)