From 66ff4c177accfb4f21d3eb476381d248d99fd8b5 Mon Sep 17 00:00:00 2001 From: Eliah Kagan Date: Sun, 17 Dec 2023 06:08:57 -0500 Subject: [PATCH] Omit CWD in search for bash.exe to run hooks on Windows This uses the same NoDefaultCurrentDirectoryInExePath technique for the Popen call in git.index.fun.run_commit_hook on Windows as is already used in git.cmd.Git.execute. The code is simpler in run_commit_hook because a shell is never used to run bash.exe. (bash.exe is itself a shell, but we never run it *via* a shell by passing shell=True to Popen.) Nonetheless, it may make sense to extract out a helper function both can call. This commit does not do that, so there is some code duplication. --- git/index/fun.py | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/git/index/fun.py b/git/index/fun.py index 402f85d2b..303141bbe 100644 --- a/git/index/fun.py +++ b/git/index/fun.py @@ -3,6 +3,7 @@ """Standalone functions to accompany the index implementation and make it more versatile.""" +import contextlib from io import BytesIO import os import os.path as osp @@ -26,7 +27,7 @@ traverse_trees_recursive, tree_to_stream, ) -from git.util import IndexFileSHA1Writer, finalize_process +from git.util import IndexFileSHA1Writer, finalize_process, patch_env from gitdb.base import IStream from gitdb.typ import str_tree_type @@ -90,6 +91,10 @@ def run_commit_hook(name: str, index: "IndexFile", *args: str) -> None: env = os.environ.copy() env["GIT_INDEX_FILE"] = safe_decode(str(index.path)) env["GIT_EDITOR"] = ":" + if os.name == "nt": + maybe_patch_caller_env = patch_env("NoDefaultCurrentDirectoryInExePath", "1") + else: + maybe_patch_caller_env = contextlib.nullcontext() cmd = [hp] try: if os.name == "nt" and not _has_file_extension(hp): @@ -98,14 +103,15 @@ def run_commit_hook(name: str, index: "IndexFile", *args: str) -> None: relative_hp = Path(hp).relative_to(index.repo.working_dir).as_posix() cmd = ["bash.exe", relative_hp] - process = subprocess.Popen( - cmd + list(args), - env=env, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - cwd=index.repo.working_dir, - creationflags=PROC_CREATIONFLAGS, - ) + with maybe_patch_caller_env: + process = subprocess.Popen( + cmd + list(args), + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=index.repo.working_dir, + creationflags=PROC_CREATIONFLAGS, + ) except Exception as ex: raise HookExecutionError(hp, ex) from ex else: