Skip to content

Commit

Permalink
src, #519: collect all is_<platform>() calls
Browse files Browse the repository at this point in the history
  • Loading branch information
ankostis committed Sep 27, 2016
1 parent 29eb301 commit f495e94
Show file tree
Hide file tree
Showing 14 changed files with 66 additions and 47 deletions.
16 changes: 9 additions & 7 deletions git/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
# just to satisfy flake8 on py3
unicode,
safe_decode,
is_posix,
is_win,
)

execute_kwargs = ('istream', 'with_keep_cwd', 'with_extended_output',
Expand All @@ -50,9 +52,9 @@
log = logging.getLogger('git.cmd')
log.addHandler(logging.NullHandler())

__all__ = ('Git', )
__all__ = ('Git',)

if sys.platform != 'win32':
if is_win():
WindowsError = OSError

if PY3:
Expand Down Expand Up @@ -236,7 +238,7 @@ def dict_to_slots_and__excluded_are_none(self, d, excluded=()):
## CREATE_NEW_PROCESS_GROUP is needed to allow killing it afterwards,
# seehttps://docs.python.org/3/library/subprocess.html#subprocess.Popen.send_signal
PROC_CREATIONFLAGS = (CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP
if sys.platform == 'win32'
if is_win()
else 0)


Expand Down Expand Up @@ -628,7 +630,7 @@ def execute(self, command,
env["LC_ALL"] = "C"
env.update(self._environment)

if sys.platform == 'win32':
if is_win():
cmd_not_found_exception = WindowsError
if kill_after_timeout:
raise GitCommandError('"kill_after_timeout" feature is not supported on Windows.')
Expand All @@ -648,7 +650,7 @@ def execute(self, command,
stderr=PIPE,
stdout=PIPE if with_stdout else open(os.devnull, 'wb'),
shell=self.USE_SHELL,
close_fds=(os.name == 'posix'), # unsupported on windows
close_fds=(is_posix()), # unsupported on windows
universal_newlines=universal_newlines,
creationflags=PROC_CREATIONFLAGS,
**subprocess_kwargs
Expand Down Expand Up @@ -688,7 +690,7 @@ def _kill_process(pid):

if kill_after_timeout:
kill_check = threading.Event()
watchdog = threading.Timer(kill_after_timeout, _kill_process, args=(proc.pid, ))
watchdog = threading.Timer(kill_after_timeout, _kill_process, args=(proc.pid,))

# Wait for the process to return
status = 0
Expand Down Expand Up @@ -932,7 +934,7 @@ def make_call():
return call
# END utility to recreate call after changes

if sys.platform == 'win32':
if is_win():
try:
try:
return self.execute(make_call(), **_kwargs)
Expand Down
14 changes: 14 additions & 0 deletions git/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""utilities to help provide compatibility with python 3"""
# flake8: noqa

import os
import sys

from gitdb.utils.compat import (
Expand Down Expand Up @@ -79,3 +80,16 @@ def __new__(cls, name, nbases, d):
# end metaclass
return metaclass(meta.__name__ + 'Helper', None, {})
# end handle py2


def is_win():
return os.name == 'nt'


def is_posix():
return os.name == 'posix'


def is_darwin():
return os.name == 'darwin'

7 changes: 4 additions & 3 deletions git/index/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@
string_types,
force_bytes,
defenc,
mviter
mviter,
is_win
)

from git.util import (
Expand Down Expand Up @@ -136,7 +137,7 @@ def _set_cache_(self, attr):
# which happens during read-tree.
# In this case, we will just read the memory in directly.
# Its insanely bad ... I am disappointed !
allow_mmap = (os.name != 'nt' or sys.version_info[1] > 5)
allow_mmap = (is_win() or sys.version_info[1] > 5)
stream = file_contents_ro(fd, stream=True, allow_mmap=allow_mmap)

try:
Expand Down Expand Up @@ -1059,7 +1060,7 @@ def handle_stderr(proc, iter_checked_out_files):
# END for each possible ending
# END for each line
if unknown_lines:
raise GitCommandError(("git-checkout-index", ), 128, stderr)
raise GitCommandError(("git-checkout-index",), 128, stderr)
if failed_files:
valid_files = list(set(iter_checked_out_files) - set(failed_files))
raise CheckoutError(
Expand Down
5 changes: 3 additions & 2 deletions git/index/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
from git.compat import (
defenc,
force_text,
force_bytes
force_bytes,
is_posix,
)

S_IFGITLINK = S_IFLNK | S_IFDIR # a submodule
Expand Down Expand Up @@ -75,7 +76,7 @@ def run_commit_hook(name, index):
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=index.repo.working_dir,
close_fds=(os.name == 'posix'),
close_fds=(is_posix()),
universal_newlines=True,
creationflags=PROC_CREATIONFLAGS,)
stdout, stderr = cmd.communicate()
Expand Down
3 changes: 2 additions & 1 deletion git/index/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import struct
import tempfile
import os
from git.compat import is_win

__all__ = ('TemporaryFileSwap', 'post_clear_cache', 'default_index', 'git_working_dir')

Expand Down Expand Up @@ -29,7 +30,7 @@ def __init__(self, file_path):

def __del__(self):
if os.path.isfile(self.tmp_file_path):
if os.name == 'nt' and os.path.exists(self.file_path):
if is_win and os.path.exists(self.file_path):
os.remove(self.file_path)
os.rename(self.tmp_file_path, self.file_path)
# END temp file exists
Expand Down
19 changes: 9 additions & 10 deletions git/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

# Module implementing a remote object allowing easy access to git remotes
import re
import os

from .config import (
SectionConstraint,
Expand All @@ -32,7 +31,7 @@
)
from git.cmd import handle_process_output
from gitdb.util import join
from git.compat import (defenc, force_text)
from git.compat import (defenc, force_text, is_win)
import logging

log = logging.getLogger('git.remote')
Expand Down Expand Up @@ -113,7 +112,7 @@ def __init__(self, flags, local_ref, remote_ref_string, remote, old_commit=None,
self._remote = remote
self._old_commit_sha = old_commit
self.summary = summary

@property
def old_commit(self):
return self._old_commit_sha and self._remote.repo.commit(self._old_commit_sha) or None
Expand Down Expand Up @@ -377,7 +376,7 @@ def __init__(self, repo, name):
self.repo = repo
self.name = name

if os.name == 'nt':
if is_win():
# some oddity: on windows, python 2.5, it for some reason does not realize
# that it has the config_writer property, but instead calls __getattr__
# which will not yield the expected results. 'pinging' the members
Expand Down Expand Up @@ -635,7 +634,7 @@ def _get_fetch_info_from_stderr(self, proc, progress):
# end
if progress.error_lines():
stderr_text = '\n'.join(progress.error_lines())

finalize_process(proc, stderr=stderr_text)

# read head information
Expand All @@ -657,7 +656,7 @@ def _get_fetch_info_from_stderr(self, proc, progress):
fetch_info_lines = fetch_info_lines[:l_fhi]
# end truncate correct list
# end sanity check + sanitization

output.extend(FetchInfo._from_line(self.repo, err_line, fetch_line)
for err_line, fetch_line in zip(fetch_info_lines, fetch_head_info))
return output
Expand Down Expand Up @@ -769,17 +768,17 @@ def push(self, refspec=None, progress=None, **kwargs):
:param refspec: see 'fetch' method
:param progress:
Can take one of many value types:
* None to discard progress information
* A function (callable) that is called with the progress infomation.
Signature: ``progress(op_code, cur_count, max_count=None, message='')``.
`Click here <http://goo.gl/NPa7st>`_ for a description of all arguments
given to the function.
* An instance of a class derived from ``git.RemoteProgress`` that
overrides the ``update()`` function.
:note: No further progress information is returned after push returns.
:param kwargs: Additional arguments to be passed to git-push
:return:
Expand Down
7 changes: 4 additions & 3 deletions git/repo/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
PY3,
safe_decode,
range,
is_win,
)

import os
Expand All @@ -71,7 +72,7 @@
BlameEntry = namedtuple('BlameEntry', ['commit', 'linenos', 'orig_path', 'orig_linenos'])


__all__ = ('Repo', )
__all__ = ('Repo',)


def _expand_path(p):
Expand Down Expand Up @@ -369,7 +370,7 @@ def delete_remote(self, remote):
def _get_config_path(self, config_level):
# we do not support an absolute path of the gitconfig on windows ,
# use the global config instead
if sys.platform == "win32" and config_level == "system":
if is_win() and config_level == "system":
config_level = "global"

if config_level == "system":
Expand Down Expand Up @@ -883,7 +884,7 @@ def _clone(cls, git, url, path, odb_default_type, progress, **kwargs):
prev_cwd = None
prev_path = None
odbt = kwargs.pop('odbt', odb_default_type)
if os.name == 'nt':
if is_win():
if '~' in path:
raise OSError("Git cannot handle the ~ character in path %r correctly" % path)

Expand Down
8 changes: 4 additions & 4 deletions git/test/lib/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import logging

from git import Repo, Remote, GitCommandError, Git
from git.compat import string_types
from git.compat import string_types, is_win

osp = os.path.dirname

Expand Down Expand Up @@ -73,7 +73,7 @@ def _mktemp(*args):
prefixing /private/ will lead to incorrect paths on OSX."""
tdir = tempfile.mktemp(*args)
# See :note: above to learn why this is comented out.
# if sys.platform == 'darwin':
# if is_darwin():
# tdir = '/private' + tdir
return tdir

Expand All @@ -83,7 +83,7 @@ def _rmtree_onerror(osremove, fullpath, exec_info):
Handle the case on windows that read-only files cannot be deleted by
os.remove by setting it to mode 777, then retry deletion.
"""
if os.name != 'nt' or osremove is not os.remove:
if is_win() or osremove is not os.remove:
raise

os.chmod(fullpath, 0o777)
Expand Down Expand Up @@ -221,7 +221,7 @@ def remote_repo_creator(self):
if gd is not None:
gd.proc.terminate()
log.warning('git-ls-remote failed due to: %s(%s)', type(e), e)
if os.name == 'nt':
if is_win():
msg = "git-daemon needs to run this test, but windows does not have one. "
msg += 'Otherwise, run: git-daemon "%s"' % temp_dir
raise AssertionError(msg)
Expand Down
5 changes: 3 additions & 2 deletions git/test/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
)
from git.objects.util import get_object_type_by_name
from gitdb.util import hex_to_bin
from git.compat import is_win


class TestBase(TestBase):
Expand Down Expand Up @@ -117,7 +118,7 @@ def test_with_rw_remote_and_rw_repo(self, rw_repo, rw_remote_repo):
assert rw_remote_repo.config_reader("repository").getboolean("core", "bare")
assert os.path.isdir(os.path.join(rw_repo.working_tree_dir, 'lib'))

@skipIf(sys.version_info < (3, ) and os.name == 'nt',
@skipIf(sys.version_info < (3,) and is_win(),
"Unicode woes, see https://github.com/gitpython-developers/GitPython/pull/519")
@with_rw_repo('0.1.6')
def test_add_unicode(self, rw_repo):
Expand All @@ -134,7 +135,7 @@ def test_add_unicode(self, rw_repo):

open(file_path, "wb").write(b'something')

if os.name == 'nt':
if is_win():
# on windows, there is no way this works, see images on
# https://github.com/gitpython-developers/GitPython/issues/147#issuecomment-68881897
# Therefore, it must be added using the python implementation
Expand Down
4 changes: 2 additions & 2 deletions git/test/test_git.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
)
from gitdb.test.lib import with_rw_directory

from git.compat import PY3
from git.compat import PY3, is_darwin

try:
from unittest import mock
Expand Down Expand Up @@ -214,7 +214,7 @@ def test_environment(self, rw_dir):
try:
remote.fetch()
except GitCommandError as err:
if sys.version_info[0] < 3 and sys.platform == 'darwin':
if sys.version_info[0] < 3 and is_darwin():
assert 'ssh-origin' in str(err)
assert err.status == 128
else:
Expand Down
8 changes: 4 additions & 4 deletions git/test/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
GitCommandError,
CheckoutError,
)
from git.compat import string_types
from git.compat import string_types, is_win
from gitdb.util import hex_to_bin
import os
import sys
Expand Down Expand Up @@ -577,7 +577,7 @@ def mixed_iterator():
assert len(entries) == 1 and entries[0].hexsha != null_hex_sha

# add symlink
if sys.platform != "win32":
if not is_win():
for target in ('/etc/nonexisting', '/etc/passwd', '/etc'):
basename = "my_real_symlink"

Expand Down Expand Up @@ -630,7 +630,7 @@ def mixed_iterator():
index.checkout(fake_symlink_path)

# on windows we will never get symlinks
if os.name == 'nt':
if is_win():
# simlinks should contain the link as text ( which is what a
# symlink actually is )
open(fake_symlink_path, 'rb').read() == link_target
Expand Down Expand Up @@ -711,7 +711,7 @@ def make_paths():
assert fkey not in index.entries

index.add(files, write=True)
if os.name != 'nt':
if is_win():
hp = hook_path('pre-commit', index.repo.git_dir)
hpd = os.path.dirname(hp)
if not os.path.isdir(hpd):
Expand Down
4 changes: 2 additions & 2 deletions git/test/test_submodule.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from git.objects.submodule.base import Submodule
from git.objects.submodule.root import RootModule, RootUpdateProgress
from git.util import to_native_path_linux, join_path_native
from git.compat import string_types
from git.compat import string_types, is_win
from git.repo.fun import (
find_git_dir,
touch
Expand All @@ -26,7 +26,7 @@
# Change the configuration if possible to prevent the underlying memory manager
# to keep file handles open. On windows we get problems as they are not properly
# closed due to mmap bugs on windows (as it appears)
if sys.platform == 'win32':
if is_win():
try:
import smmap.util
smmap.util.MapRegion._test_read_into_memory = True
Expand Down
Loading

0 comments on commit f495e94

Please sign in to comment.