diff --git a/git/diff.py b/git/diff.py index 969ee027e..e83b18f1f 100644 --- a/git/diff.py +++ b/git/diff.py @@ -413,10 +413,12 @@ class Diff: the version in the index or tree, and hence has been modified. """ - # Precompiled regex. + # Precompiled regex. It starts with the literal and checks the line start with a + # lookbehind, so the regex engine can skip to each "diff --git" instead of trying + # the pattern at every position of the patch. re_header = re.compile( rb""" - ^diff[ ]--git + diff[ ]--git(?<=^diff[ ]--git) [ ](?P(?P"?[ab]/.+?"?) [ ](?P"?[ab]/.+?"?))\n (?:^old[ ]mode[ ](?P\d+)\n diff --git a/test/test_diff.py b/test/test_diff.py index abe41ac72..76f31369b 100644 --- a/test/test_diff.py +++ b/test/test_diff.py @@ -336,6 +336,28 @@ def test_empty_diff(self): Diff._handle_diff_line(b"", None, res) self.assertEqual(res, []) + def test_patch_headers_start_only_at_line_starts(self): + blob_id, null_id = b"1" * 40, b"0" * 40 + output = StringProcessAdapter( + b"diff --git a/fix.patch b/fix.patch\n" + b"new file mode 100644\n" + b"index " + null_id + b".." + blob_id + b"\n" + b"--- /dev/null\n" + b"+++ b/fix.patch\n" + b"@@ -0,0 +1,2 @@\n" + b"+diff --git a/x b/x\n" + b"+see diff --git a/y b/y\n" + b"diff --git a/z b/z\n" + b"deleted file mode 100644\n" + b"index " + blob_id + b".." + null_id + b"\n" + ) + diffs = Diff._index_from_patch_format(None, output) + self.assertEqual( + [(d.a_path, d.b_path, d.new_file, d.deleted_file) for d in diffs], + [(None, "fix.patch", True, False), ("z", "z", False, True)], + ) + self.assertEqual(diffs[0].diff, b"@@ -0,0 +1,2 @@\n+diff --git a/x b/x\n+see diff --git a/y b/y\n") + def test_diff_initial_commit(self): initial_commit = self.rorepo.commit("root")