Skip to content

Commit

Permalink
Fix problem with Win10 shell
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianWilhelm committed Dec 30, 2021
1 parent bfcbde3 commit 894bfb8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 10 deletions.
8 changes: 2 additions & 6 deletions src/pyscaffold/file_system.py
Expand Up @@ -11,14 +11,14 @@
import os
import shutil
import stat
import sys
from contextlib import contextmanager
from functools import partial
from pathlib import Path
from tempfile import mkstemp
from typing import Callable, Optional, Union

from .log import logger
from .shell import IS_WINDOWS

PathLike = Union[str, os.PathLike]

Expand Down Expand Up @@ -216,11 +216,7 @@ def is_pathname_valid(pathname: str) -> bool:
# Directory guaranteed to exist. If the current OS is Windows, this is
# the drive to which Windows was installed (e.g., the "%HOMEDRIVE%"
# environment variable); else, the typical root directory.
root_dirname = (
os.environ.get("HOMEDRIVE", "C:")
if sys.platform == "win32"
else os.path.sep
)
root_dirname = os.environ.get("HOMEDRIVE", "C:") if IS_WINDOWS else os.path.sep
assert os.path.isdir(root_dirname) # ...Murphy and her ironclad Law

# Append a path separator to this directory if needed.
Expand Down
35 changes: 31 additions & 4 deletions src/pyscaffold/shell.py
Expand Up @@ -8,6 +8,7 @@
import shutil
import subprocess
import sys
from itertools import product
from pathlib import Path
from typing import Callable, Dict, Iterable, Iterator, List, Optional, Union

Expand All @@ -17,6 +18,7 @@
PathLike = Union[str, os.PathLike]

IS_POSIX = os.name == "posix"
IS_WINDOWS = sys.platform == "win32"

# The following default flags were borrowed from Github's docs:
# https://docs.github.com/en/github/getting-started-with-github/associating-text-editors-with-git
Expand Down Expand Up @@ -65,6 +67,23 @@ def __init__(self, command: str, shell: bool = True, cwd: Optional[str] = None):
self._shell = shell
self._cwd = cwd

def _no_git_env(self, env: Dict[str, str]) -> Dict[str, str]:
# adapted from pre-commit & taken from setuptools-scm
# Too many bugs dealing with environment variables and GIT:
# https://github.com/pre-commit/pre-commit/issues/300
# In git 2.6.3 (maybe others), git exports GIT_WORK_TREE while running
# pre-commit hooks
# In git 1.9.1 (maybe others), git exports GIT_DIR and GIT_INDEX_FILE
# while running pre-commit hooks in submodules.
# GIT_DIR: Causes git clone to clone wrong thing
# GIT_INDEX_FILE: Causes 'error invalid object ...' during commit
return {
k: v
for k, v in env.items()
if not k.startswith("GIT_")
or k in ("GIT_EXEC_PATH", "GIT_SSH", "GIT_SSH_COMMAND")
}

def run(self, *args, **kwargs) -> subprocess.CompletedProcess:
"""Execute command with the given arguments via :obj:`subprocess.run`."""
command = f"{self._command} {join(args)}".strip()
Expand All @@ -86,6 +105,14 @@ def run(self, *args, **kwargs) -> subprocess.CompletedProcess:
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"universal_newlines": True,
"env": dict(
self._no_git_env(dict(os.environ)),
# os.environ,
# try to disable i18n
LC_ALL="C",
LANGUAGE="",
HGPLAIN="1",
),
**kwargs, # allow overwriting defaults
}
if self._shell:
Expand Down Expand Up @@ -131,10 +158,10 @@ def get_git_cmd(**args):
Args:
**args: additional keyword arguments to :obj:`~.ShellCommand`
"""
if sys.platform == "win32": # pragma: no cover
if IS_WINDOWS: # pragma: no cover
# ^ CI setup does not aggregate Windows coverage
for cmd in ["git.cmd", "git.exe"]:
git = ShellCommand(cmd, **args)
for shell, cmd in product([True, False], ["git.cmd", "git.exe"]):
git = ShellCommand(cmd, shell=shell, **args)
try:
git("--version")
except ShellCommandException:
Expand Down Expand Up @@ -237,7 +264,7 @@ def edit(file: PathLike, *args, **kwargs) -> Path:

def join(parts: Iterable[Union[str, PathLike]]) -> str:
"""Join different parts of a shell command into a string, quoting whitespaces."""
if sys.platform == "win32": # pragma: no cover
if IS_WINDOWS: # pragma: no cover
# ^ CI setup does not aggregate Windows coverage
return subprocess.list2cmdline(map(str, parts))

Expand Down

0 comments on commit 894bfb8

Please sign in to comment.