Skip to content

Commit

Permalink
src: constify is_<platform>() calls
Browse files Browse the repository at this point in the history
+ TCs: unittest-asserts for git-tests.
  • Loading branch information
ankostis committed Sep 28, 2016
1 parent df2fb54 commit e61439b
Show file tree
Hide file tree
Showing 13 changed files with 45 additions and 52 deletions.
10 changes: 5 additions & 5 deletions git/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@

__all__ = ('Git',)

if is_win():
if is_win:
WindowsError = OSError

if PY3:
Expand Down Expand Up @@ -239,7 +239,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 is_win()
if is_win
else 0)


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

if is_win():
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 @@ -650,13 +650,13 @@ def execute(self, command,
stderr=PIPE,
stdout=PIPE if with_stdout else open(os.devnull, 'wb'),
shell=self.USE_SHELL,
close_fds=(is_posix()), # unsupported on windows
close_fds=(is_posix), # unsupported on windows
universal_newlines=universal_newlines,
creationflags=PROC_CREATIONFLAGS,
**subprocess_kwargs
)
except cmd_not_found_exception as err:
raise GitCommandNotFound(str(err))
raise GitCommandNotFound('%s: %s' % (command[0], err))

if as_process:
return self.AutoInterrupt(proc, command)
Expand Down
14 changes: 3 additions & 11 deletions git/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
)

PY3 = sys.version_info[0] >= 3
is_win = (os.name == 'nt')
is_posix = (os.name == 'posix')
is_darwin = (os.name == 'darwin')
defenc = sys.getdefaultencoding()

if PY3:
Expand Down Expand Up @@ -78,17 +81,6 @@ def __new__(cls, name, nbases, d):
return meta(name, bases, d)
return metaclass(meta.__name__ + 'Helper', None, {})

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


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


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


## From https://docs.python.org/3.3/howto/pyporting.html
class UnicodeMixin(object):
Expand Down
2 changes: 1 addition & 1 deletion git/index/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,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 = (is_win() 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
2 changes: 1 addition & 1 deletion git/index/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def run_commit_hook(name, index):
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=index.repo.working_dir,
close_fds=(is_posix()),
close_fds=(is_posix),
creationflags=PROC_CREATIONFLAGS,)
stdout, stderr = cmd.communicate()
cmd.stdout.close()
Expand Down
2 changes: 1 addition & 1 deletion git/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ def __init__(self, repo, name):
self.repo = repo
self.name = name

if is_win():
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
4 changes: 2 additions & 2 deletions git/repo/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,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 is_win() and config_level == "system":
if is_win and config_level == "system":
config_level = "global"

if config_level == "system":
Expand Down Expand Up @@ -884,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 is_win():
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 @@ -74,7 +74,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 is_darwin():
# if is_darwin:
# tdir = '/private' + tdir
return tdir

Expand All @@ -84,7 +84,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 is_win() or osremove is not os.remove:
if is_win or osremove is not os.remove:
raise

os.chmod(fullpath, 0o777)
Expand Down Expand Up @@ -141,7 +141,7 @@ def repo_creator(self):


def launch_git_daemon(temp_dir, ip, port):
if is_win():
if is_win:
## On MINGW-git, daemon exists in .\Git\mingw64\libexec\git-core\,
# but if invoked as 'git daemon', it detaches from parent `git` cmd,
# and then CANNOT DIE!
Expand Down Expand Up @@ -242,7 +242,7 @@ def remote_repo_creator(self):
gd.proc.terminate()
log.warning('git(%s) ls-remote failed due to:%s',
rw_repo.git_dir, e)
if is_win():
if is_win:
msg = textwrap.dedent("""
MINGW yet has problems with paths, and `git-daemon.exe` must be in PATH
(look into .\Git\mingw64\libexec\git-core\);
Expand Down
4 changes: 2 additions & 2 deletions git/test/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,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 is_win(),
@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 @@ -135,7 +135,7 @@ def test_add_unicode(self, rw_repo):

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

if is_win():
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
37 changes: 19 additions & 18 deletions git/test/test_git.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def test_it_transforms_kwargs_into_git_command_arguments(self):

# order is undefined
res = self.git.transform_kwargs(**{'s': True, 't': True})
assert ['-s', '-t'] == res or ['-t', '-s'] == res
self.assertEqual(set(['-s', '-t']), set(res))

def test_it_executes_git_to_shell_and_returns_result(self):
assert_match('^git version [\d\.]{2}.*$', self.git.execute(["git", "version"]))
Expand Down Expand Up @@ -117,7 +117,7 @@ def test_persistent_cat_file_command(self):
g.stdin.write(b"b2339455342180c7cc1e9bba3e9f181f7baa5167\n")
g.stdin.flush()
obj_info_two = g.stdout.readline()
assert obj_info == obj_info_two
self.assertEqual(obj_info, obj_info_two)

# read data - have to read it in one large chunk
size = int(obj_info.split()[2])
Expand All @@ -127,18 +127,19 @@ def test_persistent_cat_file_command(self):
# now we should be able to read a new object
g.stdin.write(b"b2339455342180c7cc1e9bba3e9f181f7baa5167\n")
g.stdin.flush()
assert g.stdout.readline() == obj_info
self.assertEqual(g.stdout.readline(), obj_info)

# same can be achived using the respective command functions
hexsha, typename, size = self.git.get_object_header(hexsha)
hexsha, typename_two, size_two, data = self.git.get_object_data(hexsha)
assert typename == typename_two and size == size_two
self.assertEqual(typename, typename_two)
self.assertEqual(size, size_two)

def test_version(self):
v = self.git.version_info
assert isinstance(v, tuple)
self.assertIsInstance(v, tuple)
for n in v:
assert isinstance(n, int)
self.assertIsInstance(n, int)
# END verify number types

def test_cmd_override(self):
Expand Down Expand Up @@ -174,28 +175,28 @@ def test_insert_after_kwarg_raises(self):
def test_env_vars_passed_to_git(self):
editor = 'non_existant_editor'
with mock.patch.dict('os.environ', {'GIT_EDITOR': editor}):
assert self.git.var("GIT_EDITOR") == editor
self.assertEqual(self.git.var("GIT_EDITOR"), editor)

@with_rw_directory
def test_environment(self, rw_dir):
# sanity check
assert self.git.environment() == {}
self.assertEqual(self.git.environment(), {})

# make sure the context manager works and cleans up after itself
with self.git.custom_environment(PWD='/tmp'):
assert self.git.environment() == {'PWD': '/tmp'}
self.assertEqual(self.git.environment(), {'PWD': '/tmp'})

assert self.git.environment() == {}
self.assertEqual(self.git.environment(), {})

old_env = self.git.update_environment(VARKEY='VARVALUE')
# The returned dict can be used to revert the change, hence why it has
# an entry with value 'None'.
assert old_env == {'VARKEY': None}
assert self.git.environment() == {'VARKEY': 'VARVALUE'}
self.assertEqual(old_env, {'VARKEY': None})
self.assertEqual(self.git.environment(), {'VARKEY': 'VARVALUE'})

new_env = self.git.update_environment(**old_env)
assert new_env == {'VARKEY': 'VARVALUE'}
assert self.git.environment() == {}
self.assertEqual(new_env, {'VARKEY': 'VARVALUE'})
self.assertEqual(self.git.environment(), {})

path = os.path.join(rw_dir, 'failing-script.sh')
stream = open(path, 'wt')
Expand All @@ -214,11 +215,11 @@ def test_environment(self, rw_dir):
try:
remote.fetch()
except GitCommandError as err:
if sys.version_info[0] < 3 and is_darwin():
assert 'ssh-origin' in str(err)
assert err.status == 128
if sys.version_info[0] < 3 and is_darwin:
self.assertIn('ssh-orig, ' in str(err))
self.assertEqual(err.status, 128)
else:
assert 'FOO' in str(err)
self.assertIn('FOO', str(err))
# end
# end
# end if select.poll exists
Expand Down
6 changes: 3 additions & 3 deletions git/test/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,7 @@ def mixed_iterator():
assert len(entries) == 1 and entries[0].hexsha != null_hex_sha

# add symlink
if not is_win():
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 is_win():
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 is_win():
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
2 changes: 1 addition & 1 deletion git/test/test_submodule.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 is_win():
if is_win:
try:
import smmap.util
smmap.util.MapRegion._test_read_into_memory = True
Expand Down
2 changes: 1 addition & 1 deletion git/test/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def test_blocking_lock_file(self):
elapsed = time.time() - start
# More extra time costs, but...
extra_time = 0.2
if is_win():
if is_win:
extra_time *= 4
self.assertLess(elapsed, wait_time + 0.02)

Expand Down
4 changes: 2 additions & 2 deletions git/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def join_path(a, *p):
return path


if is_win():
if is_win:
def to_native_path_windows(path):
return path.replace('/', '\\')

Expand Down Expand Up @@ -587,7 +587,7 @@ def _release_lock(self):
try:
# on bloody windows, the file needs write permissions to be removable.
# Why ...
if is_win():
if is_win:
os.chmod(lfp, 0o777)
# END handle win32
os.remove(lfp)
Expand Down

0 comments on commit e61439b

Please sign in to comment.