Skip to content

Commit 57a7865

Browse files
authored
Merge pull request #2349 from g4lb/perf-diff-header-literal
perf(diff): let the patch header regex skip to `diff --git` lines
2 parents d6337df + 6bf2cca commit 57a7865

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

‎git/diff.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -413,10 +413,12 @@ class Diff:
413413
the version in the index or tree, and hence has been modified.
414414
"""
415415

416-
# Precompiled regex.
416+
# Precompiled regex. It starts with the literal and checks the line start with a
417+
# lookbehind, so the regex engine can skip to each "diff --git" instead of trying
418+
# the pattern at every position of the patch.
417419
re_header = re.compile(
418420
rb"""
419-
^diff[ ]--git
421+
diff[ ]--git(?<=^diff[ ]--git)
420422
[ ](?P<header_names>(?P<a_path_fallback>"?[ab]/.+?"?)
421423
[ ](?P<b_path_fallback>"?[ab]/.+?"?))\n
422424
(?:^old[ ]mode[ ](?P<old_mode>\d+)\n

‎test/test_diff.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,28 @@ def test_empty_diff(self):
336336
Diff._handle_diff_line(b"", None, res)
337337
self.assertEqual(res, [])
338338

339+
def test_patch_headers_start_only_at_line_starts(self):
340+
blob_id, null_id = b"1" * 40, b"0" * 40
341+
output = StringProcessAdapter(
342+
b"diff --git a/fix.patch b/fix.patch\n"
343+
b"new file mode 100644\n"
344+
b"index " + null_id + b".." + blob_id + b"\n"
345+
b"--- /dev/null\n"
346+
b"+++ b/fix.patch\n"
347+
b"@@ -0,0 +1,2 @@\n"
348+
b"+diff --git a/x b/x\n"
349+
b"+see diff --git a/y b/y\n"
350+
b"diff --git a/z b/z\n"
351+
b"deleted file mode 100644\n"
352+
b"index " + blob_id + b".." + null_id + b"\n"
353+
)
354+
diffs = Diff._index_from_patch_format(None, output)
355+
self.assertEqual(
356+
[(d.a_path, d.b_path, d.new_file, d.deleted_file) for d in diffs],
357+
[(None, "fix.patch", True, False), ("z", "z", False, True)],
358+
)
359+
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")
360+
339361
def test_diff_initial_commit(self):
340362
initial_commit = self.rorepo.commit("root")
341363

0 commit comments

Comments
 (0)