diff --git a/doc/source/changes.rst b/doc/source/changes.rst index 7ec23377e..81c9831e1 100644 --- a/doc/source/changes.rst +++ b/doc/source/changes.rst @@ -88,6 +88,10 @@ API changes undecodable bytes. Diff blob paths can be used for tree lookup, and renames between distinct byte names are detected correctly. Patch rename fields contain unquoted filename bytes. +* Patch diffs request the ``a/`` and ``b/`` header prefixes explicitly, so + ``diff.noprefix``, ``diff.srcPrefix`` and ``diff.dstPrefix`` no longer make + ``Diffable.diff(..., create_patch=True)`` return an empty ``DiffIndex`` for + index and working-tree changes. * Tree serialization now delegates construction to Git or the supported Gix backend. ``Tree.cache`` and ``TreeModifier`` edit one tree's in-memory entries; ``set_done()`` orders entries by filename bytes, including undecodable names. diff --git a/git/diff.py b/git/diff.py index 7a19ffe15..7f341f418 100644 --- a/git/diff.py +++ b/git/diff.py @@ -281,6 +281,12 @@ def diff( if create_patch: args.append("-p") args.append("--no-ext-diff") + # The patch parser only recognizes "a/"/"b/"-prefixed header names, and + # `git diff` (unlike `git diff-tree`) lets configuration such as + # diff.noprefix, diff.srcPrefix or diff.dstPrefix replace or drop them, + # which would otherwise yield an empty DiffIndex for a changed worktree. + args.append("--src-prefix=a/") + args.append("--dst-prefix=b/") else: args.append("--raw") args.append("-z") diff --git a/test/test_diff.py b/test/test_diff.py index 4339ad9d2..4c4b0a999 100644 --- a/test/test_diff.py +++ b/test/test_diff.py @@ -8,7 +8,7 @@ import ddt import pytest -from git import NULL_TREE, Diff, DiffIndex, Diffable, Repo +from git import NULL_TREE, Actor, Diff, DiffIndex, Diffable, Repo from git.compat import safe_encode from git.diff import decode_path from git.exc import UnsafeOptionError @@ -660,3 +660,26 @@ def test_beginning_space(self): b_path = d.b_path self.assertEqual(a_path, " file.txt") self.assertEqual(b_path, " file.txt") + + +@pytest.mark.parametrize( + ("option", "value"), + [("diff.noprefix", "true"), ("diff.srcPrefix", "x/"), ("diff.dstPrefix", "y/")], +) +def test_worktree_patch_diff_ignores_prefix_configuration(tmp_path, option, value): + author = Actor("Test Author", "author@example.invalid") + with Repo.init(tmp_path / "repo") as repo: + repo.git.config(option, value) + tracked = tmp_path / "repo" / "file.txt" + tracked.write_text("before\n") + repo.index.add(["file.txt"]) + repo.index.commit("initial", author=author, committer=author) + tracked.write_text("after\n") + + # The raw format reports the change regardless of the header prefixes. + assert len(repo.index.diff(None)) == 1 + + # Patch headers must keep the a/ and b/ names the parser recognizes. + (diff,) = repo.index.diff(None, create_patch=True) + assert diff.a_path == "file.txt" + assert diff.diff == b"@@ -1 +1 @@\n-before\n+after\n"