Skip to content

Commit 9bdf6bd

Browse files
authored
Support git's mnemonic diff prefixes in DiffParser (#245)
diff.mnemonicPrefix replaces the default "a/"/"b/" prefixes with context-specific ones ("c/", "i/", "o/", "w/"), which DiffParser's regexp didn't account for, causing a RuntimeException for tools like GrumPHP that enable it. Fixes #114
1 parent 0cbbf59 commit 9bdf6bd

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

src/Gitonomy/Git/Parser/DiffParser.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,10 @@ protected function doParse(): void
4545
$fileIndex = 0;
4646
while (!$this->isFinished()) {
4747
// 1. title
48-
$vars = $this->consumeRegexp("/diff --git \"?(a\\/.*?)\"? \"?(b\\/.*?)\"?\n/");
48+
// The prefix is normally "a" and "b", but git's diff.mnemonicPrefix option
49+
// (used by tools such as GrumPHP) can produce other single-letter prefixes
50+
// ("c"ommit, "i"ndex, "o"bject, "w"ork tree), or "1"/"2" with --no-index.
51+
$vars = $this->consumeRegexp("/diff --git \"?([^\\/\\s]\\/.*?)\"? \"?([^\\/\\s]\\/.*?)\"?\n/");
4952
$oldName = $vars[1];
5053
$newName = $vars[2];
5154
// Get indexes from raw if it exists

tests/Gitonomy/Git/Tests/DiffTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,26 @@ public function testThrowErrorOnBlobGetWithoutIndex(): void
273273
$this->assertSame('', $file->getNewIndex());
274274
}
275275

276+
public function testMnemonicPrefix(): void
277+
{
278+
$this->expectUserDeprecationMessage('Using Diff::parse without raw information is deprecated. See https://github.com/gitonomy/gitlib/issues/227.');
279+
280+
// With `diff.mnemonicPrefix` enabled, git replaces the default "a/" and "b/"
281+
// prefixes with context-specific ones, e.g. "c/" (commit) and "i/" (index)
282+
// for `git diff --cached`. See https://github.com/gitonomy/gitlib/issues/114.
283+
$diff = Diff::parse(<<<'DIFF'
284+
diff --git c/composer.json i/composer.json
285+
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644
286+
--- c/composer.json
287+
+++ i/composer.json
288+
289+
DIFF);
290+
$firstFile = $diff->getFiles()[0];
291+
292+
$this->assertSame('composer.json', $firstFile->getOldName());
293+
$this->assertSame('composer.json', $firstFile->getNewName());
294+
}
295+
276296
public function testEmptyNewFile(): void
277297
{
278298
$this->expectUserDeprecationMessage('Using Diff::parse without raw information is deprecated. See https://github.com/gitonomy/gitlib/issues/227.');

0 commit comments

Comments
 (0)