From 2a45dbd44f25f594b8f5721c4affe6552d072d9d Mon Sep 17 00:00:00 2001 From: Krzysztof Ciszewski Date: Fri, 10 May 2024 12:10:26 +0200 Subject: [PATCH] composer#11855 fix: detect git commands that need GIT_DIR --- src/Composer/Util/ProcessExecutor.php | 37 ++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/src/Composer/Util/ProcessExecutor.php b/src/Composer/Util/ProcessExecutor.php index 26738a53ee98..041c93886d35 100644 --- a/src/Composer/Util/ProcessExecutor.php +++ b/src/Composer/Util/ProcessExecutor.php @@ -33,6 +33,13 @@ class ProcessExecutor private const STATUS_FAILED = 4; private const STATUS_ABORTED = 5; + private const GIT_CMDS_NEED_GIT_DIR = [ + 'show', + 'log', + 'branch', + ['remote', 'seturl'] + ]; + /** @var int */ protected static $timeout = 300; @@ -108,11 +115,10 @@ private function doExecute($command, ?string $cwd, bool $tty, &$output = null): $env = null; - $cmdContainsGit = is_array($command) ? in_array('git', $command, true) : is_int(stripos($command, 'git')); + $requiresGitDirEnv = $this->requiresGitDirEnv($command); + $isBareRepository = !is_dir(sprintf('%s/.git', trim((string) $cwd, '/'))); - $dotGitDir = sprintf('%s/.git', trim((string) $cwd, '/')); - $hasGitDotDir = file_exists($dotGitDir); - if ($hasGitDotDir === false && $cmdContainsGit) { + if ($cwd !== null && $isBareRepository && $requiresGitDirEnv) { $env = ['GIT_DIR' => $cwd]; } @@ -488,4 +494,27 @@ private static function escapeArgument($argument): string return $argument; } + + /** + * @param string[]|string $command + */ + public function requiresGitDirEnv($command): bool + { + $cmd = ! is_array($command) ? explode(' ', $command) : $command; + if ($cmd[0] !== 'git') { + return false; + } + $requiresGitDirEnv = false; + foreach (self::GIT_CMDS_NEED_GIT_DIR as $gitCmd) { + if (is_string($gitCmd) && in_array($gitCmd, $cmd, true)) { + return true; + } + + if (is_array($gitCmd) && array_intersect($cmd, $gitCmd) === $gitCmd) { + return true; + } + } + + return $requiresGitDirEnv; + } }