0
# Diff Operations
1
2
Comprehensive diff functionality for comparing commits, trees, and working directory state. Supports unified diff generation, patch creation, and change detection.
3
4
## Capabilities
5
6
```python { .api }
7
class Diff:
8
def __init__(self, repo: "Repo", a_rawpath: bytes, b_rawpath: bytes, a_blob_id: str, b_blob_id: str, a_mode: int, b_mode: int, new_file: bool, deleted_file: bool, copied_file: bool, raw_rename_from: str, raw_rename_to: str, diff: str, change_type: str):
9
"""Initialize diff."""
10
11
@property
12
def a_path(self) -> str:
13
"""Path in A side."""
14
15
@property
16
def b_path(self) -> str:
17
"""Path in B side."""
18
19
@property
20
def change_type(self) -> str:
21
"""Change type (A/D/M/R/C/T/U)."""
22
23
@property
24
def diff(self) -> str:
25
"""Unified diff text."""
26
27
class DiffIndex(list):
28
def iter_change_type(self, change_type: str) -> Iterator["Diff"]:
29
"""Iterate diffs of specific change type."""
30
31
class Diffable:
32
def diff(self, other: Union["Diffable", str, None] = None, paths: Union[str, list] = None, create_patch: bool = False, **kwargs) -> "DiffIndex":
33
"""Create diff."""
34
35
NULL_TREE = object() # Represents empty tree
36
INDEX = object() # Represents index state
37
38
class DiffConstants:
39
"""Constants for diff operations."""
40
```
41
42
## Usage Examples
43
44
```python
45
from git import Repo
46
47
repo = Repo('/path/to/repo')
48
49
# Compare commits
50
commit1 = repo.commit('HEAD~1')
51
commit2 = repo.commit('HEAD')
52
diffs = commit1.diff(commit2)
53
54
for diff in diffs:
55
print(f"{diff.change_type}: {diff.a_path} -> {diff.b_path}")
56
if diff.diff:
57
print(diff.diff)
58
59
# Compare working tree to index
60
index_diffs = repo.index.diff(None)
61
62
# Compare specific files
63
file_diffs = commit1.diff(commit2, paths=['README.md'])
64
```