Add Commit.patch property to expose commit-to-parent diff text#2118
Conversation
Signed-off-by: Nguyen Huy Hoang <181364121+huyhoang171106@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
Adds a Commit.patch property to GitPython’s Commit object to expose the unified diff text for a commit relative to its first parent (and handles root commits), addressing the API gap noted in #1413.
Changes:
- Introduces
Commit.patchas a new property returning textual patch output. - Uses
git difffor typical commits andgit diff-tree --rootfor root commits.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| def patch(self) -> str: | ||
| """Textual patch comparing this commit against its first parent.""" | ||
| if not self.parents: | ||
| return self.repo.git.diff_tree(self.hexsha, root=True, p=True) |
There was a problem hiding this comment.
For root commits, git diff-tree -p includes a leading commit <sha> header line (as evidenced by stats slicing off the first line). Returning that raw output here makes Commit.patch inconsistent with the non-root case (which resembles git diff and has no commit header). Consider suppressing the commit header (e.g., --no-commit-id) or trimming the first line so patch is consistently unified-diff text.
| return self.repo.git.diff_tree(self.hexsha, root=True, p=True) | |
| return self.repo.git.diff_tree(self.hexsha, root=True, p=True, no_commit_id=True) |
| @property | ||
| def patch(self) -> str: | ||
| """Textual patch comparing this commit against its first parent.""" | ||
| if not self.parents: | ||
| return self.repo.git.diff_tree(self.hexsha, root=True, p=True) | ||
| return self.repo.git.diff("%s..%s" % (self.parents[0].hexsha, self.hexsha), p=True) |
There was a problem hiding this comment.
This new Commit.patch API doesn’t appear to have test coverage. There are existing tests for commit.stats in test/test_commit.py; adding analogous assertions for commit.patch (including root commits and merge commits/first-parent behavior) would help prevent regressions and clarify the intended output format.
Summary
The issue is a missing API feature, not a runtime defect:
Commitexposes structured diff stats (commit.stats) but does not expose the raw patch text for the same comparison. Users currently must manually call lower-level git commands for each commit. TheCommitclass should be extended with apatchproperty (or method) that returns unified diff text against its parent, with correct handling for merge/root commits.Files changed
git/objects/commit.py(modified)Testing
Closes #1413