diff --git a/server/scripts/install_tcm_ancient_books.php b/server/scripts/install_tcm_ancient_books.php index 073f13053..4eed80678 100644 --- a/server/scripts/install_tcm_ancient_books.php +++ b/server/scripts/install_tcm_ancient_books.php @@ -18,37 +18,47 @@ $root = dirname(__DIR__) . '/knowledge/tcm-ancient-books'; $projectRoot = dirname(__DIR__, 2); $indexPath = TcmAncientBooksReference::indexPath(); -function runGit(array $arguments): string +function runGit(array $arguments, ?string $directory = null): string { - $command = 'git ' . implode(' ', array_map('escapeshellarg', $arguments)) . ' 2>&1'; - $lines = []; - $code = 0; - exec($command, $lines, $code); - if ($code !== 0) { - throw new RuntimeException('Git command failed: ' . implode("\n", $lines)); + $originalDirectory = getcwd(); + if ($directory !== null && ($originalDirectory === false || !chdir($directory))) { + throw new RuntimeException('Could not enter Git directory: ' . $directory); + } + try { + $command = 'git ' . implode(' ', array_map('escapeshellarg', $arguments)) . ' 2>&1'; + $lines = []; + $code = 0; + exec($command, $lines, $code); + if ($code !== 0) { + throw new RuntimeException('Git command failed: ' . implode("\n", $lines)); + } + return trim(implode("\n", $lines)); + } finally { + if ($directory !== null) { + chdir($originalDirectory); + } } - return trim(implode("\n", $lines)); } try { if (!is_dir($root . '/.git') && !is_file($root . '/.git')) { if (is_file($projectRoot . '/.gitmodules') && (is_dir($projectRoot . '/.git') || is_file($projectRoot . '/.git'))) { - runGit(['-C', $projectRoot, 'submodule', 'update', '--init', '--', 'server/knowledge/tcm-ancient-books']); + runGit(['submodule', 'update', '--init', '--', 'server/knowledge/tcm-ancient-books'], $projectRoot); } else { runGit(['clone', '--depth', '1', TcmAncientBooksReference::REPOSITORY_URL . '.git', $root]); } } - $checkoutRoot = runGit(['-C', $root, 'rev-parse', '--show-toplevel']); + $checkoutRoot = runGit(['rev-parse', '--show-toplevel'], $root); if (strtolower(str_replace('\\', '/', (string) realpath($checkoutRoot))) !== strtolower(str_replace('\\', '/', (string) realpath($root)))) { throw new RuntimeException('Corpus checkout is missing or points to the parent repository'); } - $head = runGit(['-C', $root, 'rev-parse', 'HEAD']); + $head = runGit(['rev-parse', 'HEAD'], $root); if ($head !== TcmAncientBooksReference::COMMIT) { - runGit(['-C', $root, 'fetch', '--depth', '1', 'origin', TcmAncientBooksReference::COMMIT]); - runGit(['-C', $root, 'checkout', '--detach', TcmAncientBooksReference::COMMIT]); - $head = runGit(['-C', $root, 'rev-parse', 'HEAD']); + runGit(['fetch', '--depth', '1', 'origin', TcmAncientBooksReference::COMMIT], $root); + runGit(['checkout', '--detach', TcmAncientBooksReference::COMMIT], $root); + $head = runGit(['rev-parse', 'HEAD'], $root); } if ($head !== TcmAncientBooksReference::COMMIT) { throw new RuntimeException('Corpus commit mismatch');