Skip to content

Commit 02cda1b

Browse files
authored
Fix relative paths not resolving against the repository in Repository::run() (#249)
The git process spawned by Repository::run() never had its working directory set, so Symfony Process defaulted it to the calling PHP script's cwd. Commands such as "apply" resolve the paths referenced inside their arguments (e.g. the files listed in a patch) against the process cwd rather than --work-tree, so running them from outside the repository directory failed with errors like "No such file or directory" even though --git-dir/--work-tree were correctly set. Fixes #67
1 parent d7b9315 commit 02cda1b

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

src/Gitonomy/Git/Repository.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -615,6 +615,7 @@ private function getProcess(string $command, array $args = []): Process
615615
$base[] = $command;
616616

617617
$process = new Process(array_merge($base, $args));
618+
$process->setWorkingDirectory($this->getPath());
618619

619620
if ($this->inheritEnvironmentVariables) {
620621
$process->setEnv(array_replace($_SERVER, $this->environmentVariables));

tests/Gitonomy/Git/Tests/RepositoryTest.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,38 @@ public function testLoggerNOk(Repository $repository): void
137137

138138
$repository->run('not-work');
139139
}
140+
141+
/**
142+
* @see https://github.com/gitonomy/gitlib/issues/67
143+
*/
144+
public function testRunResolvesRelativePathsAgainstTheRepositoryRegardlessOfCwd(): void
145+
{
146+
$repository = self::createFoobarRepository(false);
147+
148+
$file = $repository->getWorkingDir().'/README.md';
149+
$original = file_get_contents($file);
150+
file_put_contents($file, $original."Applied line.\n");
151+
152+
$patch = $repository->run('diff', ['--', 'README.md']);
153+
file_put_contents($file, $original);
154+
155+
$patchFile = tempnam(sys_get_temp_dir(), 'gitlib_patch_');
156+
file_put_contents($patchFile, $patch);
157+
158+
$previousCwd = getcwd();
159+
$this->assertIsString($previousCwd);
160+
chdir(sys_get_temp_dir());
161+
162+
try {
163+
// "README.md" is relative to the repository work-tree, not to the
164+
// process cwd (which is an unrelated directory here). This only
165+
// works if the git process is run with its cwd set to the repository.
166+
$repository->run('apply', [$patchFile]);
167+
} finally {
168+
chdir($previousCwd);
169+
unlink($patchFile);
170+
}
171+
172+
$this->assertSame($original."Applied line.\n", file_get_contents($file));
173+
}
140174
}

0 commit comments

Comments
 (0)