diff options
Diffstat (limited to 'git')
| -rw-r--r-- | git/__init__.py | 7 | ||||
| -rw-r--r-- | git/config.py | 36 | ||||
| -rw-r--r-- | git/index/base.py | 74 | ||||
| -rw-r--r-- | git/index/fun.py | 34 | ||||
| -rw-r--r-- | git/index/util.py | 12 | ||||
| -rw-r--r-- | git/objects/submodule/base.py | 109 | ||||
| -rw-r--r-- | git/refs/symbolic.py | 14 | ||||
| -rw-r--r-- | git/repo/base.py | 49 | ||||
| -rw-r--r-- | git/repo/fun.py | 14 | ||||
| -rw-r--r-- | git/test/performance/lib.py | 18 | ||||
| -rw-r--r-- | git/test/performance/test_streams.py | 23 | ||||
| -rw-r--r-- | git/test/test_base.py | 26 | ||||
| -rw-r--r-- | git/test/test_commit.py | 42 | ||||
| -rw-r--r-- | git/test/test_config.py | 13 | ||||
| -rw-r--r-- | git/test/test_db.py | 9 | ||||
| -rw-r--r-- | git/test/test_diff.py | 24 | ||||
| -rw-r--r-- | git/test/test_docs.py | 26 | ||||
| -rw-r--r-- | git/test/test_git.py | 28 | ||||
| -rw-r--r-- | git/test/test_index.py | 50 | ||||
| -rw-r--r-- | git/test/test_reflog.py | 18 | ||||
| -rw-r--r-- | git/test/test_refs.py | 28 | ||||
| -rw-r--r-- | git/test/test_repo.py | 24 | ||||
| -rw-r--r-- | git/test/test_tree.py | 9 | ||||
| -rw-r--r-- | git/util.py | 6 | 
24 files changed, 361 insertions, 332 deletions
diff --git a/git/__init__.py b/git/__init__.py index 58e4e7b6..0514d545 100644 --- a/git/__init__.py +++ b/git/__init__.py @@ -5,9 +5,12 @@  # the BSD License: http://www.opensource.org/licenses/bsd-license.php  # flake8: noqa  #@PydevCodeAnalysisIgnore +import inspect  import os  import sys -import inspect + +import os.path as osp +  __version__ = 'git' @@ -16,7 +19,7 @@ __version__ = 'git'  def _init_externals():      """Initialize external projects by putting them into the path"""      if __version__ == 'git': -        sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'ext', 'gitdb')) +        sys.path.insert(0, osp.join(osp.dirname(__file__), 'ext', 'gitdb'))      try:          import gitdb diff --git a/git/config.py b/git/config.py index eddfac15..a0b25822 100644 --- a/git/config.py +++ b/git/config.py @@ -6,21 +6,13 @@  """Module containing module parser implementation able to properly read and write  configuration files""" -import re -try: -    import ConfigParser as cp -except ImportError: -    # PY3 -    import configparser as cp +import abc +from functools import wraps  import inspect  import logging -import abc  import os +import re -from functools import wraps - -from git.odict import OrderedDict -from git.util import LockFile  from git.compat import (      string_types,      FileType, @@ -29,6 +21,18 @@ from git.compat import (      with_metaclass,      PY3  ) +from git.odict import OrderedDict +from git.util import LockFile + +import os.path as osp + + +try: +    import ConfigParser as cp +except ImportError: +    # PY3 +    import configparser as cp +  __all__ = ('GitConfigParser', 'SectionConstraint') @@ -408,15 +412,15 @@ class GitConfigParser(with_metaclass(MetaParserBuilder, cp.RawConfigParser, obje              if self._has_includes():                  for _, include_path in self.items('include'):                      if include_path.startswith('~'): -                        include_path = os.path.expanduser(include_path) -                    if not os.path.isabs(include_path): +                        include_path = osp.expanduser(include_path) +                    if not osp.isabs(include_path):                          if not file_ok:                              continue                          # end ignore relative paths if we don't know the configuration file path -                        assert os.path.isabs(file_path), "Need absolute paths to be sure our cycle checks will work" -                        include_path = os.path.join(os.path.dirname(file_path), include_path) +                        assert osp.isabs(file_path), "Need absolute paths to be sure our cycle checks will work" +                        include_path = osp.join(osp.dirname(file_path), include_path)                      # end make include path absolute -                    include_path = os.path.normpath(include_path) +                    include_path = osp.normpath(include_path)                      if include_path in seen or not os.access(include_path, os.R_OK):                          continue                      seen.add(include_path) diff --git a/git/index/base.py b/git/index/base.py index ac2d3019..1e423df4 100644 --- a/git/index/base.py +++ b/git/index/base.py @@ -3,34 +3,28 @@  #  # This module is part of GitPython and is released under  # the BSD License: http://www.opensource.org/licenses/bsd-license.php -import tempfile -import os -import sys -import subprocess  import glob  from io import BytesIO - +import os  from stat import S_ISLNK +import subprocess +import sys +import tempfile -from .typ import ( -    BaseIndexEntry, -    IndexEntry, -) - -from .util import ( -    TemporaryFileSwap, -    post_clear_cache, -    default_index, -    git_working_dir +from git.compat import ( +    izip, +    xrange, +    string_types, +    force_bytes, +    defenc, +    mviter, +    is_win  ) - -import git.diff as diff  from git.exc import (      GitCommandError,      CheckoutError,      InvalidGitRepositoryError  ) -  from git.objects import (      Blob,      Submodule, @@ -38,18 +32,7 @@ from git.objects import (      Object,      Commit,  ) -  from git.objects.util import Serializable -from git.compat import ( -    izip, -    xrange, -    string_types, -    force_bytes, -    defenc, -    mviter, -    is_win -) -  from git.util import (      LazyMixin,      LockedFD, @@ -58,6 +41,12 @@ from git.util import (      to_native_path_linux,      unbare_repo  ) +from gitdb.base import IStream +from gitdb.db import MemoryDB +from gitdb.util import to_bin_sha + +import git.diff as diff +import os.path as osp  from .fun import (      entry_key, @@ -69,10 +58,17 @@ from .fun import (      S_IFGITLINK,      run_commit_hook  ) +from .typ import ( +    BaseIndexEntry, +    IndexEntry, +) +from .util import ( +    TemporaryFileSwap, +    post_clear_cache, +    default_index, +    git_working_dir +) -from gitdb.base import IStream -from gitdb.db import MemoryDB -from gitdb.util import to_bin_sha  __all__ = ('IndexFile', 'CheckoutError') @@ -354,7 +350,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable):              index.entries       # force it to read the file as we will delete the temp-file              del(index_handler)  # release as soon as possible          finally: -            if os.path.exists(tmp_index): +            if osp.exists(tmp_index):                  os.remove(tmp_index)          # END index merge handling @@ -374,8 +370,8 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable):          rs = r + os.sep          for path in paths:              abs_path = path -            if not os.path.isabs(abs_path): -                abs_path = os.path.join(r, path) +            if not osp.isabs(abs_path): +                abs_path = osp.join(r, path)              # END make absolute path              try: @@ -407,7 +403,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable):                  for root, dirs, files in os.walk(abs_path, onerror=raise_exc):  # @UnusedVariable                      for rela_file in files:                          # add relative paths only -                        yield os.path.join(root.replace(rs, ''), rela_file) +                        yield osp.join(root.replace(rs, ''), rela_file)                      # END for each file in subdir                  # END for each subdirectory              except OSError: @@ -569,7 +565,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable):      def _to_relative_path(self, path):          """:return: Version of path relative to our git directory or raise ValueError          if it is not within our git direcotory""" -        if not os.path.isabs(path): +        if not osp.isabs(path):              return path          if self.repo.bare:              raise InvalidGitRepositoryError("require non-bare repository") @@ -617,12 +613,12 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable):          entries_added = list()          if path_rewriter:              for path in paths: -                if os.path.isabs(path): +                if osp.isabs(path):                      abspath = path                      gitrelative_path = path[len(self.repo.working_tree_dir) + 1:]                  else:                      gitrelative_path = path -                    abspath = os.path.join(self.repo.working_tree_dir, gitrelative_path) +                    abspath = osp.join(self.repo.working_tree_dir, gitrelative_path)                  # end obtain relative and absolute paths                  blob = Blob(self.repo, Blob.NULL_BIN_SHA, diff --git a/git/index/fun.py b/git/index/fun.py index 7a7593fe..d9c0f215 100644 --- a/git/index/fun.py +++ b/git/index/fun.py @@ -1,6 +1,8 @@  # Contains standalone functions to accompany the index implementation and make it  # more versatile  # NOTE: Autodoc hates it if this is a docstring +from io import BytesIO +import os  from stat import (      S_IFDIR,      S_IFLNK, @@ -9,13 +11,18 @@ from stat import (      S_IFMT,      S_IFREG,  ) - -from io import BytesIO -import os  import subprocess -from git.util import IndexFileSHA1Writer, finalize_process  from git.cmd import PROC_CREATIONFLAGS, handle_process_output +from git.compat import ( +    PY3, +    defenc, +    force_text, +    force_bytes, +    is_posix, +    safe_encode, +    safe_decode, +)  from git.exc import (      UnmergedEntriesError,      HookExecutionError @@ -25,6 +32,11 @@ from git.objects.fun import (      traverse_tree_recursive,      traverse_trees_recursive  ) +from git.util import IndexFileSHA1Writer, finalize_process +from gitdb.base import IStream +from gitdb.typ import str_tree_type + +import os.path as osp  from .typ import (      BaseIndexEntry, @@ -32,23 +44,11 @@ from .typ import (      CE_NAMEMASK,      CE_STAGESHIFT  ) -  from .util import (      pack,      unpack  ) -from gitdb.base import IStream -from gitdb.typ import str_tree_type -from git.compat import ( -    PY3, -    defenc, -    force_text, -    force_bytes, -    is_posix, -    safe_encode, -    safe_decode, -)  S_IFGITLINK = S_IFLNK | S_IFDIR     # a submodule  CE_NAMEMASK_INV = ~CE_NAMEMASK @@ -59,7 +59,7 @@ __all__ = ('write_cache', 'read_cache', 'write_tree_from_cache', 'entry_key',  def hook_path(name, git_dir):      """:return: path to the given named hook in the given git repository directory""" -    return os.path.join(git_dir, 'hooks', name) +    return osp.join(git_dir, 'hooks', name)  def run_commit_hook(name, index): diff --git a/git/index/util.py b/git/index/util.py index ce798851..3c59b1d8 100644 --- a/git/index/util.py +++ b/git/index/util.py @@ -1,12 +1,14 @@  """Module containing index utilities""" +from functools import wraps +import os  import struct  import tempfile -import os - -from functools import wraps  from git.compat import is_win +import os.path as osp + +  __all__ = ('TemporaryFileSwap', 'post_clear_cache', 'default_index', 'git_working_dir')  #{ Aliases @@ -32,8 +34,8 @@ class TemporaryFileSwap(object):              pass      def __del__(self): -        if os.path.isfile(self.tmp_file_path): -            if is_win and os.path.exists(self.file_path): +        if osp.isfile(self.tmp_file_path): +            if is_win and osp.exists(self.file_path):                  os.remove(self.file_path)              os.rename(self.tmp_file_path, self.file_path)          # END temp file exists diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 9bb563d7..d2c6e020 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -1,21 +1,18 @@ -from .util import ( -    mkhead, -    sm_name, -    sm_section, -    SubmoduleConfigParser, -    find_first_remote_branch -) -from git.objects.util import Traversable -from io import BytesIO                   # need a dict to set bloody .name field -from git.util import ( -    Iterable, -    join_path_native, -    to_native_path_linux, -    RemoteProgress, -    rmtree, -    unbare_repo -) +# need a dict to set bloody .name field +from io import BytesIO +import logging +import os +import stat +from unittest.case import SkipTest +import uuid +import git +from git.cmd import Git +from git.compat import ( +    string_types, +    defenc, +    is_win, +)  from git.config import (      SectionConstraint,      GitConfigParser, @@ -26,22 +23,28 @@ from git.exc import (      NoSuchPathError,      RepositoryDirtyError  ) -from git.compat import ( -    string_types, -    defenc, -    is_win, +from git.objects.base import IndexObject, Object +from git.objects.util import Traversable +from git.util import ( +    Iterable, +    join_path_native, +    to_native_path_linux, +    RemoteProgress, +    rmtree, +    unbare_repo  ) +from git.util import HIDE_WINDOWS_KNOWN_ERRORS -import stat -import git +import os.path as osp + +from .util import ( +    mkhead, +    sm_name, +    sm_section, +    SubmoduleConfigParser, +    find_first_remote_branch +) -import os -import logging -import uuid -from unittest.case import SkipTest -from git.util import HIDE_WINDOWS_KNOWN_ERRORS -from git.objects.base import IndexObject, Object -from git.cmd import Git  __all__ = ["Submodule", "UpdateProgress"] @@ -120,7 +123,7 @@ class Submodule(IndexObject, Iterable, Traversable):                  self.path = reader.get_value('path')              except cp.NoSectionError:                  raise ValueError("This submodule instance does not exist anymore in '%s' file" -                                 % os.path.join(self.repo.working_tree_dir, '.gitmodules')) +                                 % osp.join(self.repo.working_tree_dir, '.gitmodules'))              # end              self._url = reader.get_value('url')              # git-python extension values - optional @@ -181,7 +184,7 @@ class Submodule(IndexObject, Iterable, Traversable):          # end hanlde parent_commit          if not repo.bare and parent_matches_head: -            fp_module = os.path.join(repo.working_tree_dir, cls.k_modules_file) +            fp_module = osp.join(repo.working_tree_dir, cls.k_modules_file)          else:              assert parent_commit is not None, "need valid parent_commit in bare repositories"              try: @@ -229,9 +232,9 @@ class Submodule(IndexObject, Iterable, Traversable):      @classmethod      def _module_abspath(cls, parent_repo, path, name):          if cls._need_gitfile_submodules(parent_repo.git): -            return os.path.join(parent_repo.git_dir, 'modules', name) +            return osp.join(parent_repo.git_dir, 'modules', name)          else: -            return os.path.join(parent_repo.working_tree_dir, path) +            return osp.join(parent_repo.working_tree_dir, path)          # end      @classmethod @@ -246,10 +249,10 @@ class Submodule(IndexObject, Iterable, Traversable):          module_checkout_path = module_abspath          if cls._need_gitfile_submodules(repo.git):              kwargs['separate_git_dir'] = module_abspath -            module_abspath_dir = os.path.dirname(module_abspath) -            if not os.path.isdir(module_abspath_dir): +            module_abspath_dir = osp.dirname(module_abspath) +            if not osp.isdir(module_abspath_dir):                  os.makedirs(module_abspath_dir) -            module_checkout_path = os.path.join(repo.working_tree_dir, path) +            module_checkout_path = osp.join(repo.working_tree_dir, path)          # end          clone = git.Repo.clone_from(url, module_checkout_path, **kwargs) @@ -267,7 +270,7 @@ class Submodule(IndexObject, Iterable, Traversable):              path = path[:-1]          # END handle trailing slash -        if os.path.isabs(path): +        if osp.isabs(path):              working_tree_linux = to_native_path_linux(parent_repo.working_tree_dir)              if not path.startswith(working_tree_linux):                  raise ValueError("Submodule checkout path '%s' needs to be within the parents repository at '%s'" @@ -291,18 +294,18 @@ class Submodule(IndexObject, Iterable, Traversable):          :param working_tree_dir: directory to write the .git file into          :param module_abspath: absolute path to the bare repository          """ -        git_file = os.path.join(working_tree_dir, '.git') -        rela_path = os.path.relpath(module_abspath, start=working_tree_dir) +        git_file = osp.join(working_tree_dir, '.git') +        rela_path = osp.relpath(module_abspath, start=working_tree_dir)          if is_win: -            if os.path.isfile(git_file): +            if osp.isfile(git_file):                  os.remove(git_file)          with open(git_file, 'wb') as fp:              fp.write(("gitdir: %s" % rela_path).encode(defenc)) -        with GitConfigParser(os.path.join(module_abspath, 'config'), +        with GitConfigParser(osp.join(module_abspath, 'config'),                               read_only=False, merge_includes=False) as writer:              writer.set_value('core', 'worktree', -                             to_native_path_linux(os.path.relpath(working_tree_dir, start=module_abspath))) +                             to_native_path_linux(osp.relpath(working_tree_dir, start=module_abspath)))      #{ Edit Interface @@ -501,7 +504,7 @@ class Submodule(IndexObject, Iterable, Traversable):                  # there is no git-repository yet - but delete empty paths                  checkout_module_abspath = self.abspath -                if not dry_run and os.path.isdir(checkout_module_abspath): +                if not dry_run and osp.isdir(checkout_module_abspath):                      try:                          os.rmdir(checkout_module_abspath)                      except OSError: @@ -671,7 +674,7 @@ class Submodule(IndexObject, Iterable, Traversable):          # END handle no change          module_checkout_abspath = join_path_native(self.repo.working_tree_dir, module_checkout_path) -        if os.path.isfile(module_checkout_abspath): +        if osp.isfile(module_checkout_abspath):              raise ValueError("Cannot move repository onto a file: %s" % module_checkout_abspath)          # END handle target files @@ -684,12 +687,12 @@ class Submodule(IndexObject, Iterable, Traversable):          # remove existing destination          if module: -            if os.path.exists(module_checkout_abspath): +            if osp.exists(module_checkout_abspath):                  if len(os.listdir(module_checkout_abspath)):                      raise ValueError("Destination module directory was not empty")                  # END handle non-emptiness -                if os.path.islink(module_checkout_abspath): +                if osp.islink(module_checkout_abspath):                      os.remove(module_checkout_abspath)                  else:                      os.rmdir(module_checkout_abspath) @@ -704,11 +707,11 @@ class Submodule(IndexObject, Iterable, Traversable):          # move the module into place if possible          cur_path = self.abspath          renamed_module = False -        if module and os.path.exists(cur_path): +        if module and osp.exists(cur_path):              os.renames(cur_path, module_checkout_abspath)              renamed_module = True -            if os.path.isfile(os.path.join(module_checkout_abspath, '.git')): +            if osp.isfile(osp.join(module_checkout_abspath, '.git')):                  module_abspath = self._module_abspath(self.repo, self.path, self.name)                  self._write_git_file_and_module_config(module_checkout_abspath, module_abspath)              # end handle git file rewrite @@ -804,11 +807,11 @@ class Submodule(IndexObject, Iterable, Traversable):                  # state. Delete the .git folders last, start with the submodules first                  mp = self.abspath                  method = None -                if os.path.islink(mp): +                if osp.islink(mp):                      method = os.remove -                elif os.path.isdir(mp): +                elif osp.isdir(mp):                      method = rmtree -                elif os.path.exists(mp): +                elif osp.exists(mp):                      raise AssertionError("Cannot forcibly delete repository as it was neither a link, nor a directory")                  # END handle brutal deletion                  if not dry_run: @@ -865,7 +868,7 @@ class Submodule(IndexObject, Iterable, Traversable):                  # END delete tree if possible              # END handle force -            if not dry_run and os.path.isdir(git_dir): +            if not dry_run and osp.isdir(git_dir):                  self._clear_cache()                  try:                      rmtree(git_dir) diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index ebaff8ca..d1c412c8 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -1,5 +1,9 @@  import os +from git.compat import ( +    string_types, +    defenc +)  from git.objects import Object, Commit  from git.util import (      join_path, @@ -7,7 +11,6 @@ from git.util import (      to_native_path_linux,      assure_directory_exists  ) -  from gitdb.exc import (      BadObject,      BadName @@ -22,13 +25,12 @@ from gitdb.util import (      hex_to_bin,      LockedFD  ) -from git.compat import ( -    string_types, -    defenc -) + +import os.path as osp  from .log import RefLog +  __all__ = ["SymbolicReference"] @@ -458,7 +460,7 @@ class SymbolicReference(object):          # delete the reflog          reflog_path = RefLog.path(cls(repo, full_ref_path)) -        if os.path.isfile(reflog_path): +        if osp.isfile(reflog_path):              os.remove(reflog_path)          # END remove reflog diff --git a/git/repo/base.py b/git/repo/base.py index 6355615e..af923bde 100644 --- a/git/repo/base.py +++ b/git/repo/base.py @@ -10,12 +10,6 @@ import os  import re  import sys -from gitdb.util import ( -    join, -    isfile, -    hex_to_bin -) -  from git.cmd import (      Git,      handle_process_output @@ -36,6 +30,13 @@ from git.objects import Submodule, RootModule, Commit  from git.refs import HEAD, Head, Reference, TagReference  from git.remote import Remote, add_progress, to_progress_instance  from git.util import Actor, finalize_process, decygpath +from gitdb.util import ( +    join, +    isfile, +    hex_to_bin +) + +import os.path as osp  from .fun import rev_parse, is_git_dir, find_git_dir, touch @@ -54,7 +55,7 @@ __all__ = ('Repo',)  def _expand_path(p): -    return os.path.abspath(os.path.expandvars(os.path.expanduser(p))) +    return osp.abspath(osp.expandvars(osp.expanduser(p)))  class Repo(object): @@ -100,7 +101,7 @@ class Repo(object):                  repo = Repo("$REPOSITORIES/Development/git-python.git")              In *Cygwin*, path may be a `'cygdrive/...'` prefixed path. -             +          :param odbt:              Object DataBase type - a type which is constructed by providing              the directory containing the database objects, i.e. .git/objects. It will @@ -118,7 +119,7 @@ class Repo(object):          epath = _expand_path(path or os.getcwd())          self.git = None  # should be set for __del__ not to fail in case we raise -        if not os.path.exists(epath): +        if not osp.exists(epath):              raise NoSuchPathError(epath)          self.working_dir = None @@ -128,24 +129,24 @@ class Repo(object):          # walk up the path to find the .git dir          while curpath: -            # ABOUT os.path.NORMPATH +            # ABOUT osp.NORMPATH              # It's important to normalize the paths, as submodules will otherwise initialize their              # repo instances with paths that depend on path-portions that will not exist after being              # removed. It's just cleaner.              if is_git_dir(curpath): -                self.git_dir = os.path.normpath(curpath) -                self._working_tree_dir = os.path.dirname(self.git_dir) +                self.git_dir = osp.normpath(curpath) +                self._working_tree_dir = osp.dirname(self.git_dir)                  break              gitpath = find_git_dir(join(curpath, '.git'))              if gitpath is not None: -                self.git_dir = os.path.normpath(gitpath) +                self.git_dir = osp.normpath(gitpath)                  self._working_tree_dir = curpath                  break              if not search_parent_directories:                  break -            curpath, dummy = os.path.split(curpath) +            curpath, dummy = osp.split(curpath)              if not dummy:                  break          # END while curpath @@ -361,12 +362,12 @@ class Repo(object):          if config_level == "system":              return "/etc/gitconfig"          elif config_level == "user": -            config_home = os.environ.get("XDG_CONFIG_HOME") or os.path.join(os.environ.get("HOME", '~'), ".config") -            return os.path.normpath(os.path.expanduser(join(config_home, "git", "config"))) +            config_home = os.environ.get("XDG_CONFIG_HOME") or osp.join(os.environ.get("HOME", '~'), ".config") +            return osp.normpath(osp.expanduser(join(config_home, "git", "config")))          elif config_level == "global": -            return os.path.normpath(os.path.expanduser("~/.gitconfig")) +            return osp.normpath(osp.expanduser("~/.gitconfig"))          elif config_level == "repository": -            return os.path.normpath(join(self.git_dir, "config")) +            return osp.normpath(join(self.git_dir, "config"))          raise ValueError("Invalid configuration level: %r" % config_level) @@ -511,11 +512,11 @@ class Repo(object):      def _get_daemon_export(self):          filename = join(self.git_dir, self.DAEMON_EXPORT_FILE) -        return os.path.exists(filename) +        return osp.exists(filename)      def _set_daemon_export(self, value):          filename = join(self.git_dir, self.DAEMON_EXPORT_FILE) -        fileexists = os.path.exists(filename) +        fileexists = osp.exists(filename)          if value and not fileexists:              touch(filename)          elif not value and fileexists: @@ -532,7 +533,7 @@ class Repo(object):          :return: list of strings being pathnames of alternates"""          alternates_path = join(self.git_dir, 'objects', 'info', 'alternates') -        if os.path.exists(alternates_path): +        if osp.exists(alternates_path):              with open(alternates_path, 'rb') as f:                  alts = f.read().decode(defenc)              return alts.strip().splitlines() @@ -841,7 +842,7 @@ class Repo(object):          :return: ``git.Repo`` (the newly created repo)"""          if path:              path = _expand_path(path) -        if mkdir and path and not os.path.exists(path): +        if mkdir and path and not osp.exists(path):              os.makedirs(path, 0o755)          # git command automatically chdir into the directory @@ -879,7 +880,7 @@ class Repo(object):          # our git command could have a different working dir than our actual          # environment, hence we prepend its working dir if required -        if not os.path.isabs(path) and git.working_dir: +        if not osp.isabs(path) and git.working_dir:              path = join(git._working_dir, path)          # adjust remotes - there may be operating systems which use backslashes, @@ -958,7 +959,7 @@ class Repo(object):          """          if self.bare:              return False -        return os.path.isfile(os.path.join(self.working_tree_dir, '.git')) +        return osp.isfile(osp.join(self.working_tree_dir, '.git'))      rev_parse = rev_parse diff --git a/git/repo/fun.py b/git/repo/fun.py index 320eb1c8..c770fd43 100644 --- a/git/repo/fun.py +++ b/git/repo/fun.py @@ -2,12 +2,14 @@  import os  from string import digits +from git.compat import xrange +from git.exc import WorkTreeRepositoryUnsupported +from git.objects import Object +from git.refs import SymbolicReference  from gitdb.exc import (      BadObject,      BadName,  ) -from git.refs import SymbolicReference -from git.objects import Object  from gitdb.util import (      join,      isdir, @@ -16,8 +18,8 @@ from gitdb.util import (      hex_to_bin,      bin_to_hex  ) -from git.exc import WorkTreeRepositoryUnsupported -from git.compat import xrange + +import os.path as osp  __all__ = ('rev_parse', 'is_git_dir', 'touch', 'find_git_dir', 'name_to_object', 'short_to_long', 'deref_tag', @@ -42,7 +44,7 @@ def is_git_dir(d):          if isdir(join(d, 'objects')) and isdir(join(d, 'refs')):              headref = join(d, 'HEAD')              return isfile(headref) or \ -                (os.path.islink(headref) and +                (osp.islink(headref) and                   os.readlink(headref).startswith('refs'))          elif isfile(join(d, 'gitdir')) and isfile(join(d, 'commondir')) and isfile(join(d, 'gitfile')):              raise WorkTreeRepositoryUnsupported(d) @@ -62,7 +64,7 @@ def find_git_dir(d):      else:          if content.startswith('gitdir: '):              path = content[8:] -            if not os.path.isabs(path): +            if not osp.isabs(path):                  path = join(dirname(d), path)              return find_git_dir(path)      # end handle exception diff --git a/git/test/performance/lib.py b/git/test/performance/lib.py index b57b9b71..700fee98 100644 --- a/git/test/performance/lib.py +++ b/git/test/performance/lib.py @@ -1,21 +1,23 @@  """Contains library functions""" +import logging  import os -from git.test.lib import ( -    TestBase -)  import tempfile -import logging +from git import ( +    Repo +)  from git.db import (      GitCmdObjectDB,      GitDB  ) - -from git import ( -    Repo +from git.test.lib import ( +    TestBase  )  from git.util import rmtree +import os.path as osp + +  #{ Invvariants  k_env_git_repo = "GIT_PYTHON_TEST_GIT_REPO_BASE" @@ -52,7 +54,7 @@ class TestBigRepoR(TestBase):              logging.info(                  ("You can set the %s environment variable to a .git repository of" % k_env_git_repo) +                  "your choice - defaulting to the gitpython repository") -            repo_path = os.path.dirname(__file__) +            repo_path = osp.dirname(__file__)          # end set some repo path          self.gitrorepo = Repo(repo_path, odbt=GitCmdObjectDB, search_parent_directories=True)          self.puregitrorepo = Repo(repo_path, odbt=GitDB, search_parent_directories=True) diff --git a/git/test/performance/test_streams.py b/git/test/performance/test_streams.py index 42cbade5..699aa25b 100644 --- a/git/test/performance/test_streams.py +++ b/git/test/performance/test_streams.py @@ -1,26 +1,27 @@  """Performance data streaming performance"""  from __future__ import print_function -from time import time  import os -import sys  import subprocess +import sys +from time import time  from git.test.lib import (      with_rw_repo  ) -from gitdb.util import bin_to_hex +from gitdb import ( +    LooseObjectDB, +    IStream +)  from gitdb.test.lib import make_memory_file +from gitdb.util import bin_to_hex + +import os.path as osp  from .lib import (      TestBigRepoR  ) -from gitdb import ( -    LooseObjectDB, -    IStream -) -  class TestObjDBPerformance(TestBigRepoR): @@ -31,7 +32,7 @@ class TestObjDBPerformance(TestBigRepoR):      def test_large_data_streaming(self, rwrepo):          # TODO: This part overlaps with the same file in gitdb.test.performance.test_stream          # It should be shared if possible -        ldb = LooseObjectDB(os.path.join(rwrepo.git_dir, 'objects')) +        ldb = LooseObjectDB(osp.join(rwrepo.git_dir, 'objects'))          for randomize in range(2):              desc = (randomize and 'random ') or '' @@ -47,7 +48,7 @@ class TestObjDBPerformance(TestBigRepoR):              elapsed_add = time() - st              assert ldb.has_object(binsha)              db_file = ldb.readable_db_object_path(bin_to_hex(binsha)) -            fsize_kib = os.path.getsize(db_file) / 1000 +            fsize_kib = osp.getsize(db_file) / 1000              size_kib = size / 1000              msg = "Added %i KiB (filesize = %i KiB) of %s data to loose odb in %f s ( %f Write KiB / s)" @@ -109,7 +110,7 @@ class TestObjDBPerformance(TestBigRepoR):              assert gitsha == bin_to_hex(binsha)     # we do it the same way, right ?              #  as its the same sha, we reuse our path -            fsize_kib = os.path.getsize(db_file) / 1000 +            fsize_kib = osp.getsize(db_file) / 1000              msg = "Added %i KiB (filesize = %i KiB) of %s data to using git-hash-object in %f s ( %f Write KiB / s)"              msg %= (size_kib, fsize_kib, desc, gelapsed_add, size_kib / gelapsed_add)              print(msg, file=sys.stderr) diff --git a/git/test/test_base.py b/git/test/test_base.py index 7fc3096f..576df961 100644 --- a/git/test/test_base.py +++ b/git/test/test_base.py @@ -9,22 +9,24 @@ import sys  import tempfile  from unittest import skipIf -import git.objects.base as base -from git.test.lib import ( -    TestBase, -    assert_raises, -    with_rw_repo, -    with_rw_and_rw_remote_repo -)  from git import (      Blob,      Tree,      Commit,      TagObject  ) +from git.compat import is_win  from git.objects.util import get_object_type_by_name +from git.test.lib import ( +    TestBase, +    assert_raises, +    with_rw_repo, +    with_rw_and_rw_remote_repo +)  from gitdb.util import hex_to_bin -from git.compat import is_win + +import git.objects.base as base +import os.path as osp  class TestBase(TestBase): @@ -103,19 +105,19 @@ class TestBase(TestBase):      @with_rw_repo('HEAD', bare=True)      def test_with_bare_rw_repo(self, bare_rw_repo):          assert bare_rw_repo.config_reader("repository").getboolean("core", "bare") -        assert os.path.isfile(os.path.join(bare_rw_repo.git_dir, 'HEAD')) +        assert osp.isfile(osp.join(bare_rw_repo.git_dir, 'HEAD'))      @with_rw_repo('0.1.6')      def test_with_rw_repo(self, rw_repo):          assert not rw_repo.config_reader("repository").getboolean("core", "bare") -        assert os.path.isdir(os.path.join(rw_repo.working_tree_dir, 'lib')) +        assert osp.isdir(osp.join(rw_repo.working_tree_dir, 'lib'))      #@skipIf(HIDE_WINDOWS_FREEZE_ERRORS, "FIXME: Freezes!  sometimes...")      @with_rw_and_rw_remote_repo('0.1.6')      def test_with_rw_remote_and_rw_repo(self, rw_repo, rw_remote_repo):          assert not rw_repo.config_reader("repository").getboolean("core", "bare")          assert rw_remote_repo.config_reader("repository").getboolean("core", "bare") -        assert os.path.isdir(os.path.join(rw_repo.working_tree_dir, 'lib')) +        assert osp.isdir(osp.join(rw_repo.working_tree_dir, 'lib'))      @skipIf(sys.version_info < (3,) and is_win,              "Unicode woes, see https://github.com/gitpython-developers/GitPython/pull/519") @@ -123,7 +125,7 @@ class TestBase(TestBase):      def test_add_unicode(self, rw_repo):          filename = u"שלום.txt" -        file_path = os.path.join(rw_repo.working_dir, filename) +        file_path = osp.join(rw_repo.working_dir, filename)          # verify first that we could encode file name in this environment          try: diff --git a/git/test/test_commit.py b/git/test/test_commit.py index fd9777fb..fbb1c244 100644 --- a/git/test/test_commit.py +++ b/git/test/test_commit.py @@ -6,34 +6,36 @@  # the BSD License: http://www.opensource.org/licenses/bsd-license.php  from __future__ import print_function -from git.test.lib import ( -    TestBase, -    assert_equal, -    assert_not_equal, -    with_rw_repo, -    fixture_path, -    StringProcessAdapter -) +from datetime import datetime +from io import BytesIO +import re +import sys +import time +  from git import (      Commit,      Actor,  ) -from gitdb import IStream -from git.test.lib import with_rw_directory +from git import Repo  from git.compat import (      string_types,      text_type  ) -from git import Repo +from git.objects.util import tzoffset, utc  from git.repo.fun import touch +from git.test.lib import ( +    TestBase, +    assert_equal, +    assert_not_equal, +    with_rw_repo, +    fixture_path, +    StringProcessAdapter +) +from git.test.lib import with_rw_directory +from gitdb import IStream + +import os.path as osp -from io import BytesIO -import time -import sys -import re -import os -from datetime import datetime -from git.objects.util import tzoffset, utc  try:      from unittest.mock import Mock @@ -232,8 +234,8 @@ class TestCommit(TestBase):      @with_rw_directory      def test_ambiguous_arg_iteration(self, rw_dir): -        rw_repo = Repo.init(os.path.join(rw_dir, 'test_ambiguous_arg')) -        path = os.path.join(rw_repo.working_tree_dir, 'master') +        rw_repo = Repo.init(osp.join(rw_dir, 'test_ambiguous_arg')) +        path = osp.join(rw_repo.working_tree_dir, 'master')          touch(path)          rw_repo.index.add([path])          rw_repo.index.commit('initial commit') diff --git a/git/test/test_config.py b/git/test/test_config.py index 32873f24..0dfadda6 100644 --- a/git/test/test_config.py +++ b/git/test/test_config.py @@ -6,7 +6,6 @@  import glob  import io -import os  from git import (      GitConfigParser @@ -91,7 +90,7 @@ class TestBase(TestCase):      @with_rw_directory      def test_lock_reentry(self, rw_dir): -        fpl = os.path.join(rw_dir, 'l') +        fpl = osp.join(rw_dir, 'l')          gcp = GitConfigParser(fpl, read_only=False)          with gcp as cw:              cw.set_value('include', 'some_value', 'a') @@ -103,7 +102,7 @@ class TestBase(TestCase):                  GitConfigParser(fpl, read_only=False)          # but work when the lock is removed          with GitConfigParser(fpl, read_only=False): -            assert os.path.exists(fpl) +            assert osp.exists(fpl)              # reentering with an existing lock must fail due to exclusive access              with self.assertRaises(IOError):                  gcp.__enter__() @@ -178,17 +177,17 @@ class TestBase(TestCase):          # end          # PREPARE CONFIG FILE A -        fpa = os.path.join(rw_dir, 'a') +        fpa = osp.join(rw_dir, 'a')          with GitConfigParser(fpa, read_only=False) as cw:              write_test_value(cw, 'a') -            fpb = os.path.join(rw_dir, 'b') -            fpc = os.path.join(rw_dir, 'c') +            fpb = osp.join(rw_dir, 'b') +            fpc = osp.join(rw_dir, 'c')              cw.set_value('include', 'relative_path_b', 'b')              cw.set_value('include', 'doesntexist', 'foobar')              cw.set_value('include', 'relative_cycle_a_a', 'a')              cw.set_value('include', 'absolute_cycle_a_a', fpa) -        assert os.path.exists(fpa) +        assert osp.exists(fpa)          # PREPARE CONFIG FILE B          with GitConfigParser(fpb, read_only=False) as cw: diff --git a/git/test/test_db.py b/git/test/test_db.py index 5dcf592a..1741e7b9 100644 --- a/git/test/test_db.py +++ b/git/test/test_db.py @@ -3,17 +3,18 @@  #  # This module is part of GitPython and is released under  # the BSD License: http://www.opensource.org/licenses/bsd-license.php -from git.test.lib import TestBase  from git.db import GitCmdObjectDB -from gitdb.util import bin_to_hex  from git.exc import BadObject -import os +from git.test.lib import TestBase +from gitdb.util import bin_to_hex + +import os.path as osp  class TestDB(TestBase):      def test_base(self): -        gdb = GitCmdObjectDB(os.path.join(self.rorepo.git_dir, 'objects'), self.rorepo.git) +        gdb = GitCmdObjectDB(osp.join(self.rorepo.git_dir, 'objects'), self.rorepo.git)          # partial to complete - works with everything          hexsha = bin_to_hex(gdb.partial_to_complete_sha_hex("0.1.6")) diff --git a/git/test/test_diff.py b/git/test/test_diff.py index d5f5b721..48a5a641 100644 --- a/git/test/test_diff.py +++ b/git/test/test_diff.py @@ -4,8 +4,15 @@  #  # This module is part of GitPython and is released under  # the BSD License: http://www.opensource.org/licenses/bsd-license.php -import os - +import ddt +from git import ( +    Repo, +    GitCommandError, +    Diff, +    DiffIndex, +    NULL_TREE, +) +from git.cmd import Git  from git.test.lib import (      TestBase,      StringProcessAdapter, @@ -14,18 +21,9 @@ from git.test.lib import (      assert_true,  ) -  from git.test.lib import with_rw_directory -from git import ( -    Repo, -    GitCommandError, -    Diff, -    DiffIndex, -    NULL_TREE, -) -import ddt -from git.cmd import Git +import os.path as osp  @ddt.ddt @@ -54,7 +52,7 @@ class TestDiff(TestBase):      def test_diff_with_staged_file(self, rw_dir):          # SETUP INDEX WITH MULTIPLE STAGES          r = Repo.init(rw_dir) -        fp = os.path.join(rw_dir, 'hello.txt') +        fp = osp.join(rw_dir, 'hello.txt')          with open(fp, 'w') as fs:              fs.write("hello world")          r.git.add(Git.polish_url(fp)) diff --git a/git/test/test_docs.py b/git/test/test_docs.py index f3c75f79..bb937d93 100644 --- a/git/test/test_docs.py +++ b/git/test/test_docs.py @@ -9,6 +9,8 @@ import os  from git.test.lib import TestBase  from git.test.lib.helper import with_rw_directory +import os.path as osp +  class Tutorials(TestBase): @@ -23,7 +25,7 @@ class Tutorials(TestBase):      def test_init_repo_object(self, rw_dir):          # [1-test_init_repo_object]          from git import Repo -        join = os.path.join +        join = osp.join          # rorepo is a Repo instance pointing to the git-python repository.          # For all you know, the first argument to Repo is a path to the repository @@ -62,7 +64,7 @@ class Tutorials(TestBase):          # repository paths          # [7-test_init_repo_object] -        assert os.path.isdir(cloned_repo.working_tree_dir)                   # directory with your work files +        assert osp.isdir(cloned_repo.working_tree_dir)                   # directory with your work files          assert cloned_repo.git_dir.startswith(cloned_repo.working_tree_dir)  # directory containing the git repository          assert bare_repo.working_tree_dir is None                            # bare repositories have no working tree          # ![7-test_init_repo_object] @@ -146,7 +148,7 @@ class Tutorials(TestBase):          self.assertEqual(new_branch.checkout(), cloned_repo.active_branch)     # checking out branch adjusts the wtree          self.assertEqual(new_branch.commit, past.commit)                       # Now the past is checked out -        new_file_path = os.path.join(cloned_repo.working_tree_dir, 'my-new-file') +        new_file_path = osp.join(cloned_repo.working_tree_dir, 'my-new-file')          open(new_file_path, 'wb').close()                             # create new file in working tree          cloned_repo.index.add([new_file_path])                        # add it to the index          # Commit the changes to deviate masters history @@ -162,7 +164,7 @@ class Tutorials(TestBase):          # now new_branch is ahead of master, which probably should be checked out and reset softly.          # note that all these operations didn't touch the working tree, as we managed it ourselves.          # This definitely requires you to know what you are doing :) ! -        assert os.path.basename(new_file_path) in new_branch.commit.tree  # new file is now in tree +        assert osp.basename(new_file_path) in new_branch.commit.tree  # new file is now in tree          master.commit = new_branch.commit            # let master point to most recent commit          cloned_repo.head.reference = master          # we adjusted just the reference, not the working tree or index          # ![13-test_init_repo_object] @@ -192,7 +194,7 @@ class Tutorials(TestBase):      def test_references_and_objects(self, rw_dir):          # [1-test_references_and_objects]          import git -        repo = git.Repo.clone_from(self._small_repo_url(), os.path.join(rw_dir, 'repo'), branch='master') +        repo = git.Repo.clone_from(self._small_repo_url(), osp.join(rw_dir, 'repo'), branch='master')          heads = repo.heads          master = heads.master       # lists can be accessed by name for convenience @@ -264,7 +266,7 @@ class Tutorials(TestBase):          # [11-test_references_and_objects]          hct.blobs[0].data_stream.read()        # stream object to read data from -        hct.blobs[0].stream_data(open(os.path.join(rw_dir, 'blob_data'), 'wb'))  # write data to given stream +        hct.blobs[0].stream_data(open(osp.join(rw_dir, 'blob_data'), 'wb'))  # write data to given stream          # ![11-test_references_and_objects]          # [12-test_references_and_objects] @@ -350,11 +352,11 @@ class Tutorials(TestBase):          # Access blob objects          for (path, stage), entry in index.entries.items():  # @UnusedVariable              pass -        new_file_path = os.path.join(repo.working_tree_dir, 'new-file-name') +        new_file_path = osp.join(repo.working_tree_dir, 'new-file-name')          open(new_file_path, 'w').close()          index.add([new_file_path])                                             # add a new file to the index          index.remove(['LICENSE'])                                              # remove an existing one -        assert os.path.isfile(os.path.join(repo.working_tree_dir, 'LICENSE'))  # working tree is untouched +        assert osp.isfile(osp.join(repo.working_tree_dir, 'LICENSE'))  # working tree is untouched          self.assertEqual(index.commit("my commit message").type, 'commit')              # commit changed index          repo.active_branch.commit = repo.commit('HEAD~1')                      # forget last commit @@ -373,11 +375,11 @@ class Tutorials(TestBase):          # merge two trees three-way into memory          merge_index = IndexFile.from_tree(repo, 'HEAD~10', 'HEAD', repo.merge_base('HEAD~10', 'HEAD'))          # and persist it -        merge_index.write(os.path.join(rw_dir, 'merged_index')) +        merge_index.write(osp.join(rw_dir, 'merged_index'))          # ![24-test_references_and_objects]          # [25-test_references_and_objects] -        empty_repo = git.Repo.init(os.path.join(rw_dir, 'empty')) +        empty_repo = git.Repo.init(osp.join(rw_dir, 'empty'))          origin = empty_repo.create_remote('origin', repo.remotes.origin.url)          assert origin.exists()          assert origin == empty_repo.remotes.origin == empty_repo.remotes['origin'] @@ -480,8 +482,8 @@ class Tutorials(TestBase):      def test_add_file_and_commit(self, rw_dir):          import git -        repo_dir = os.path.join(rw_dir, 'my-new-repo') -        file_name = os.path.join(repo_dir, 'new-file') +        repo_dir = osp.join(rw_dir, 'my-new-repo') +        file_name = osp.join(repo_dir, 'new-file')          r = git.Repo.init(repo_dir)          # This function just creates an empty file ... diff --git a/git/test/test_git.py b/git/test/test_git.py index bd8ebee2..7d713022 100644 --- a/git/test/test_git.py +++ b/git/test/test_git.py @@ -5,9 +5,17 @@  # This module is part of GitPython and is released under  # the BSD License: http://www.opensource.org/licenses/bsd-license.php  import os -import sys  import subprocess +import sys +from git import ( +    Git, +    GitCommandError, +    GitCommandNotFound, +    Repo, +    cmd +) +from git.compat import PY3, is_darwin  from git.test.lib import (      TestBase,      patch, @@ -17,18 +25,12 @@ from git.test.lib import (      assert_match,      fixture_path  ) -from git import ( -    Git, -    GitCommandError, -    GitCommandNotFound, -    Repo, -    cmd -)  from git.test.lib import with_rw_directory - -from git.compat import PY3, is_darwin  from git.util import finalize_process +import os.path as osp + +  try:      from unittest import mock  except ImportError: @@ -147,7 +149,7 @@ class TestGit(TestBase):          exc = GitCommandNotFound          try:              # set it to something that doens't exist, assure it raises -            type(self.git).GIT_PYTHON_GIT_EXECUTABLE = os.path.join( +            type(self.git).GIT_PYTHON_GIT_EXECUTABLE = osp.join(                  "some", "path", "which", "doesn't", "exist", "gitbinary")              self.failUnlessRaises(exc, self.git.version)          finally: @@ -198,13 +200,13 @@ class TestGit(TestBase):          self.assertEqual(new_env, {'VARKEY': 'VARVALUE'})          self.assertEqual(self.git.environment(), {}) -        path = os.path.join(rw_dir, 'failing-script.sh') +        path = osp.join(rw_dir, 'failing-script.sh')          with open(path, 'wt') as stream:              stream.write("#!/usr/bin/env sh\n"                           "echo FOO\n")          os.chmod(path, 0o777) -        rw_repo = Repo.init(os.path.join(rw_dir, 'repo')) +        rw_repo = Repo.init(osp.join(rw_dir, 'repo'))          remote = rw_repo.create_remote('ssh-origin', "ssh://git@server/foo")          with rw_repo.git.custom_environment(GIT_SSH=path): diff --git a/git/test/test_index.py b/git/test/test_index.py index d851743e..0fdc120c 100644 --- a/git/test/test_index.py +++ b/git/test/test_index.py @@ -43,12 +43,14 @@ from git.test.lib import (      fixture,      with_rw_repo  ) -from git.util import HIDE_WINDOWS_KNOWN_ERRORS  from git.test.lib import with_rw_directory  from git.util import Actor, rmtree +from git.util import HIDE_WINDOWS_KNOWN_ERRORS  from gitdb.base import IStream  from gitdb.util import hex_to_bin +import os.path as osp +  class TestIndex(TestBase): @@ -85,7 +87,7 @@ class TestIndex(TestBase):      def _assert_entries(self, entries):          for entry in entries:              assert isinstance(entry, BaseIndexEntry) -            assert not os.path.isabs(entry.path) +            assert not osp.isabs(entry.path)              assert "\\" not in entry.path          # END for each entry @@ -329,7 +331,7 @@ class TestIndex(TestBase):          # reset the working copy as well to current head,to pull 'back' as well          new_data = b"will be reverted" -        file_path = os.path.join(rw_repo.working_tree_dir, "CHANGES") +        file_path = osp.join(rw_repo.working_tree_dir, "CHANGES")          with open(file_path, "wb") as fp:              fp.write(new_data)          index.reset(rev_head_parent, working_tree=True) @@ -340,26 +342,26 @@ class TestIndex(TestBase):              assert fp.read() != new_data          # test full checkout -        test_file = os.path.join(rw_repo.working_tree_dir, "CHANGES") +        test_file = osp.join(rw_repo.working_tree_dir, "CHANGES")          with open(test_file, 'ab') as fd:              fd.write(b"some data")          rval = index.checkout(None, force=True, fprogress=self._fprogress)          assert 'CHANGES' in list(rval)          self._assert_fprogress([None]) -        assert os.path.isfile(test_file) +        assert osp.isfile(test_file)          os.remove(test_file)          rval = index.checkout(None, force=False, fprogress=self._fprogress)          assert 'CHANGES' in list(rval)          self._assert_fprogress([None]) -        assert os.path.isfile(test_file) +        assert osp.isfile(test_file)          # individual file          os.remove(test_file)          rval = index.checkout(test_file, fprogress=self._fprogress)          self.assertEqual(list(rval)[0], 'CHANGES')          self._assert_fprogress([test_file]) -        assert os.path.exists(test_file) +        assert osp.exists(test_file)          # checking out non-existing file throws          self.failUnlessRaises(CheckoutError, index.checkout, "doesnt_exist_ever.txt.that") @@ -373,7 +375,7 @@ class TestIndex(TestBase):              index.checkout(test_file)          except CheckoutError as e:              self.assertEqual(len(e.failed_files), 1) -            self.assertEqual(e.failed_files[0], os.path.basename(test_file)) +            self.assertEqual(e.failed_files[0], osp.basename(test_file))              self.assertEqual(len(e.failed_files), len(e.failed_reasons))              self.assertIsInstance(e.failed_reasons[0], string_types)              self.assertEqual(len(e.valid_files), 0) @@ -388,7 +390,7 @@ class TestIndex(TestBase):          assert not open(test_file, 'rb').read().endswith(append_data)          # checkout directory -        rmtree(os.path.join(rw_repo.working_tree_dir, "lib")) +        rmtree(osp.join(rw_repo.working_tree_dir, "lib"))          rval = index.checkout('lib')          assert len(list(rval)) > 1 @@ -399,7 +401,7 @@ class TestIndex(TestBase):          existing = 0          basedir = repo.working_tree_dir          for f in files: -            existing += os.path.isfile(os.path.join(basedir, f)) +            existing += osp.isfile(osp.join(basedir, f))          # END for each deleted file          return existing      # END num existing helper @@ -458,7 +460,7 @@ class TestIndex(TestBase):          self.failUnlessRaises(TypeError, index.remove, [1])          # absolute path -        deleted_files = index.remove([os.path.join(rw_repo.working_tree_dir, "lib")], r=True) +        deleted_files = index.remove([osp.join(rw_repo.working_tree_dir, "lib")], r=True)          assert len(deleted_files) > 1          self.failUnlessRaises(ValueError, index.remove, ["/doesnt/exists"]) @@ -525,9 +527,9 @@ class TestIndex(TestBase):          # re-add all files in lib          # get the lib folder back on disk, but get an index without it          index.reset(new_commit.parents[0], working_tree=True).reset(new_commit, working_tree=False) -        lib_file_path = os.path.join("lib", "git", "__init__.py") +        lib_file_path = osp.join("lib", "git", "__init__.py")          assert (lib_file_path, 0) not in index.entries -        assert os.path.isfile(os.path.join(rw_repo.working_tree_dir, lib_file_path)) +        assert osp.isfile(osp.join(rw_repo.working_tree_dir, lib_file_path))          # directory          entries = index.add(['lib'], fprogress=self._fprogress_add) @@ -536,14 +538,14 @@ class TestIndex(TestBase):          assert len(entries) > 1          # glob -        entries = index.reset(new_commit).add([os.path.join('lib', 'git', '*.py')], fprogress=self._fprogress_add) +        entries = index.reset(new_commit).add([osp.join('lib', 'git', '*.py')], fprogress=self._fprogress_add)          self._assert_entries(entries)          self._assert_fprogress(entries)          self.assertEqual(len(entries), 14)          # same file          entries = index.reset(new_commit).add( -            [os.path.join(rw_repo.working_tree_dir, 'lib', 'git', 'head.py')] * 2, fprogress=self._fprogress_add) +            [osp.join(rw_repo.working_tree_dir, 'lib', 'git', 'head.py')] * 2, fprogress=self._fprogress_add)          self._assert_entries(entries)          self.assertEqual(entries[0].mode & 0o644, 0o644)          # would fail, test is too primitive to handle this case @@ -583,7 +585,7 @@ class TestIndex(TestBase):              for target in ('/etc/nonexisting', '/etc/passwd', '/etc'):                  basename = "my_real_symlink" -                link_file = os.path.join(rw_repo.working_tree_dir, basename) +                link_file = osp.join(rw_repo.working_tree_dir, basename)                  os.symlink(target, link_file)                  entries = index.reset(new_commit).add([link_file], fprogress=self._fprogress_add)                  self._assert_entries(entries) @@ -645,7 +647,7 @@ class TestIndex(TestBase):          # TEST RENAMING          def assert_mv_rval(rval):              for source, dest in rval: -                assert not os.path.exists(source) and os.path.exists(dest) +                assert not osp.exists(source) and osp.exists(dest)              # END for each renamed item          # END move assertion utility @@ -661,7 +663,7 @@ class TestIndex(TestBase):          paths = ['LICENSE', 'VERSION', 'doc']          rval = index.move(paths, dry_run=True)          self.assertEqual(len(rval), 2) -        assert os.path.exists(paths[0]) +        assert osp.exists(paths[0])          # again, no dry run          rval = index.move(paths) @@ -719,8 +721,8 @@ class TestIndex(TestBase):          index.add(files, write=True)          if is_win:              hp = hook_path('pre-commit', index.repo.git_dir) -            hpd = os.path.dirname(hp) -            if not os.path.isdir(hpd): +            hpd = osp.dirname(hp) +            if not osp.isdir(hpd):                  os.mkdir(hpd)              with open(hp, "wt") as fp:                  fp.write("#!/usr/bin/env sh\necho stdout; echo stderr 1>&2; exit 1") @@ -766,7 +768,7 @@ class TestIndex(TestBase):          for fkey in keys:              assert fkey in index.entries          for absfile in absfiles: -            assert os.path.isfile(absfile) +            assert osp.isfile(absfile)      @with_rw_repo('HEAD')      def test_compare_write_tree(self, rw_repo): @@ -815,7 +817,7 @@ class TestIndex(TestBase):          # Adding using a path should still require a non-bare repository.          asserted = False -        path = os.path.join('git', 'test', 'test_index.py') +        path = osp.join('git', 'test', 'test_index.py')          try:              rw_bare_repo.index.add([path])          except InvalidGitRepositoryError: @@ -829,7 +831,7 @@ class TestIndex(TestBase):      @with_rw_directory      def test_add_utf8P_path(self, rw_dir):          # NOTE: fp is not a Unicode object in python 2 (which is the source of the problem) -        fp = os.path.join(rw_dir, 'ø.txt') +        fp = osp.join(rw_dir, 'ø.txt')          with open(fp, 'wb') as fs:              fs.write(u'content of ø'.encode('utf-8')) @@ -840,7 +842,7 @@ class TestIndex(TestBase):      @with_rw_directory      def test_add_a_file_with_wildcard_chars(self, rw_dir):          # see issue #407 -        fp = os.path.join(rw_dir, '[.exe') +        fp = osp.join(rw_dir, '[.exe')          with open(fp, "wb") as f:              f.write(b'something') diff --git a/git/test/test_reflog.py b/git/test/test_reflog.py index dffedf3b..e43a1dc0 100644 --- a/git/test/test_reflog.py +++ b/git/test/test_reflog.py @@ -1,17 +1,19 @@ -from git.test.lib import ( -    TestBase, -    fixture_path -) +import os +import tempfile +  from git.objects import IndexObject  from git.refs import (      RefLogEntry,      RefLog  ) +from git.test.lib import ( +    TestBase, +    fixture_path +)  from git.util import Actor, rmtree  from gitdb.util import hex_to_bin -import tempfile -import os +import os.path as osp  class TestRefLog(TestBase): @@ -42,7 +44,7 @@ class TestRefLog(TestBase):          os.mkdir(tdir)          rlp_master_ro = RefLog.path(self.rorepo.head) -        assert os.path.isfile(rlp_master_ro) +        assert osp.isfile(rlp_master_ro)          # simple read          reflog = RefLog.from_file(rlp_master_ro) @@ -70,7 +72,7 @@ class TestRefLog(TestBase):          cr = self.rorepo.config_reader()          for rlp in (rlp_head, rlp_master):              reflog = RefLog.from_file(rlp) -            tfile = os.path.join(tdir, os.path.basename(rlp)) +            tfile = osp.join(tdir, osp.basename(rlp))              reflog.to_file(tfile)              assert reflog.write() is reflog diff --git a/git/test/test_refs.py b/git/test/test_refs.py index 43f1dcc7..fd0be108 100644 --- a/git/test/test_refs.py +++ b/git/test/test_refs.py @@ -4,10 +4,8 @@  # This module is part of GitPython and is released under  # the BSD License: http://www.opensource.org/licenses/bsd-license.php -from git.test.lib import ( -    TestBase, -    with_rw_repo -) +from itertools import chain +  from git import (      Reference,      Head, @@ -18,11 +16,15 @@ from git import (      GitCommandError,      RefLog  ) -import git.refs as refs -from git.util import Actor  from git.objects.tag import TagObject -from itertools import chain -import os +from git.test.lib import ( +    TestBase, +    with_rw_repo +) +from git.util import Actor + +import git.refs as refs +import os.path as osp  class TestRefs(TestBase): @@ -268,10 +270,10 @@ class TestRefs(TestBase):              assert tmp_head == new_head and tmp_head.object == new_head.object              logfile = RefLog.path(tmp_head) -            assert os.path.isfile(logfile) +            assert osp.isfile(logfile)              Head.delete(rw_repo, tmp_head)              # deletion removes the log as well -            assert not os.path.isfile(logfile) +            assert not osp.isfile(logfile)              heads = rw_repo.heads              assert tmp_head not in heads and new_head not in heads              # force on deletion testing would be missing here, code looks okay though ;) @@ -450,12 +452,12 @@ class TestRefs(TestBase):          symbol_ref_path = "refs/symbol_ref"          symref = SymbolicReference(rw_repo, symbol_ref_path)          assert symref.path == symbol_ref_path -        symbol_ref_abspath = os.path.join(rw_repo.git_dir, symref.path) +        symbol_ref_abspath = osp.join(rw_repo.git_dir, symref.path)          # set it          symref.reference = new_head          assert symref.reference == new_head -        assert os.path.isfile(symbol_ref_abspath) +        assert osp.isfile(symbol_ref_abspath)          assert symref.commit == new_head.commit          for name in ('absname', 'folder/rela_name'): @@ -507,7 +509,7 @@ class TestRefs(TestBase):          rw_repo.head.reference = Head.create(rw_repo, "master")          # At least the head should still exist -        assert os.path.isfile(os.path.join(rw_repo.git_dir, 'HEAD')) +        assert osp.isfile(osp.join(rw_repo.git_dir, 'HEAD'))          refs = list(SymbolicReference.iter_items(rw_repo))          assert len(refs) == 1 diff --git a/git/test/test_repo.py b/git/test/test_repo.py index 314201ea..4b21db4b 100644 --- a/git/test/test_repo.py +++ b/git/test/test_repo.py @@ -203,8 +203,8 @@ class TestRepo(TestBase):          prev_cwd = os.getcwd()          os.chdir(tempfile.gettempdir())          git_dir_rela = "repos/foo/bar.git" -        del_dir_abs = os.path.abspath("repos") -        git_dir_abs = os.path.abspath(git_dir_rela) +        del_dir_abs = osp.abspath("repos") +        git_dir_abs = osp.abspath(git_dir_rela)          try:              # with specific path              for path in (git_dir_rela, git_dir_abs): @@ -212,7 +212,7 @@ class TestRepo(TestBase):                  self.assertIsInstance(r, Repo)                  assert r.bare is True                  assert not r.has_separate_working_tree() -                assert os.path.isdir(r.git_dir) +                assert osp.isdir(r.git_dir)                  self._assert_empty_repo(r) @@ -306,16 +306,16 @@ class TestRepo(TestBase):      def test_is_dirty_with_path(self, rwrepo):          assert rwrepo.is_dirty(path="git") is False -        with open(os.path.join(rwrepo.working_dir, "git", "util.py"), "at") as f: +        with open(osp.join(rwrepo.working_dir, "git", "util.py"), "at") as f:              f.write("junk")          assert rwrepo.is_dirty(path="git") is True          assert rwrepo.is_dirty(path="doc") is False -        rwrepo.git.add(os.path.join("git", "util.py")) +        rwrepo.git.add(osp.join("git", "util.py"))          assert rwrepo.is_dirty(index=False, path="git") is False          assert rwrepo.is_dirty(path="git") is True -        with open(os.path.join(rwrepo.working_dir, "doc", "no-such-file.txt"), "wt") as f: +        with open(osp.join(rwrepo.working_dir, "doc", "no-such-file.txt"), "wt") as f:              f.write("junk")          assert rwrepo.is_dirty(path="doc") is False          assert rwrepo.is_dirty(untracked_files=True, path="doc") is True @@ -494,10 +494,10 @@ class TestRepo(TestBase):          ph = os.environ.get('HOME')          try:              os.environ['HOME'] = rw_dir -            Repo.init(os.path.join('~', 'test.git'), bare=True) +            Repo.init(osp.join('~', 'test.git'), bare=True)              os.environ['FOO'] = rw_dir -            Repo.init(os.path.join('$FOO', 'test.git'), bare=True) +            Repo.init(osp.join('$FOO', 'test.git'), bare=True)          finally:              if ph:                  os.environ['HOME'] = ph @@ -785,7 +785,7 @@ class TestRepo(TestBase):      @with_rw_repo('HEAD')      def test_git_file(self, rwrepo):          # Move the .git directory to another location and create the .git file. -        real_path_abs = os.path.abspath(join_path_native(rwrepo.working_tree_dir, '.real')) +        real_path_abs = osp.abspath(join_path_native(rwrepo.working_tree_dir, '.real'))          os.rename(rwrepo.git_dir, real_path_abs)          git_file_path = join_path_native(rwrepo.working_tree_dir, '.git')          with open(git_file_path, 'wb') as fp: @@ -793,13 +793,13 @@ class TestRepo(TestBase):          # Create a repo and make sure it's pointing to the relocated .git directory.          git_file_repo = Repo(rwrepo.working_tree_dir) -        self.assertEqual(os.path.abspath(git_file_repo.git_dir), real_path_abs) +        self.assertEqual(osp.abspath(git_file_repo.git_dir), real_path_abs)          # Test using an absolute gitdir path in the .git file.          with open(git_file_path, 'wb') as fp:              fp.write(('gitdir: %s\n' % real_path_abs).encode('ascii'))          git_file_repo = Repo(rwrepo.working_tree_dir) -        self.assertEqual(os.path.abspath(git_file_repo.git_dir), real_path_abs) +        self.assertEqual(osp.abspath(git_file_repo.git_dir), real_path_abs)      @skipIf(HIDE_WINDOWS_KNOWN_ERRORS and PY3,              "FIXME: smmp fails with: TypeError: Can't convert 'bytes' object to str implicitly") @@ -840,7 +840,7 @@ class TestRepo(TestBase):          # It's expected to not be able to access a tree          self.failUnlessRaises(ValueError, r.tree) -        new_file_path = os.path.join(rw_dir, "new_file.ext") +        new_file_path = osp.join(rw_dir, "new_file.ext")          touch(new_file_path)          r.index.add([new_file_path])          r.index.commit("initial commit\nBAD MESSAGE 1\n") diff --git a/git/test/test_tree.py b/git/test/test_tree.py index f36c4337..f9259874 100644 --- a/git/test/test_tree.py +++ b/git/test/test_tree.py @@ -5,7 +5,6 @@  # the BSD License: http://www.opensource.org/licenses/bsd-license.php  from io import BytesIO -import os  import sys  from unittest.case import skipIf @@ -13,8 +12,10 @@ from git import (      Tree,      Blob  ) -from git.util import HIDE_WINDOWS_KNOWN_ERRORS  from git.test.lib import TestBase +from git.util import HIDE_WINDOWS_KNOWN_ERRORS + +import os.path as osp  class TestTree(TestBase): @@ -90,12 +91,12 @@ class TestTree(TestBase):          assert len(set(b for b in root if isinstance(b, Blob)) | set(root.blobs)) == len(root.blobs)          subitem = trees[0][0]          assert "/" in subitem.path -        assert subitem.name == os.path.basename(subitem.path) +        assert subitem.name == osp.basename(subitem.path)          # assure that at some point the traversed paths have a slash in them          found_slash = False          for item in root.traverse(): -            assert os.path.isabs(item.abspath) +            assert osp.isabs(item.abspath)              if '/' in item.path:                  found_slash = True              # END check for slash diff --git a/git/util.py b/git/util.py index 992937fb..9658baa9 100644 --- a/git/util.py +++ b/git/util.py @@ -128,7 +128,7 @@ def stream_copy(source, destination, chunk_size=512 * 1024):  def join_path(a, *p): -    """Join path tokens together similar to os.path.join, but always use +    """Join path tokens together similar to osp.join, but always use      '/' instead of possibly '\' on windows."""      path = a      for b in p: @@ -206,7 +206,7 @@ def py_where(program, path=None):      progs = []      if not path:          path = os.environ["PATH"] -    for folder in path.split(osp.pathsep): +    for folder in path.split(os.pathsep):          folder = folder.strip('"')          if folder:              exe_path = osp.join(folder, program) @@ -222,7 +222,7 @@ def _cygexpath(drive, path):          #  It's an error, leave it alone just slashes)          p = path      else: -        p = path and osp.normpath(osp.expandvars(os.path.expanduser(path))) +        p = path and osp.normpath(osp.expandvars(osp.expanduser(path)))          if osp.isabs(p):              if drive:                  # Confusing, maybe a remote system should expand vars.  | 
