class DiffView(Vertical):
"""A ``diff`` tool call content item."""
DEFAULT_CSS = """
DiffView {
height: auto;
margin: 0 0 1 0;
.diff-header { height: auto; }
.diff-lines {
height: auto;
text-wrap: nowrap;
text-overflow: clip;
overflow-x: hidden;
}
Horizontal { height: auto; }
Horizontal > .diff-lines { width: 1fr; }
Horizontal > .diff-lines.left { border-right: vkey $panel; }
}
"""
mode: reactive[DiffViewMode] = reactive("auto")
split: reactive[bool] = reactive(False, recompose=True)
OPERATIONS: ClassVar[dict[str, str]] = {
"add": "Added",
"delete": "Deleted",
"modify": "Modified",
"move": "Moved",
"copy": "Copied",
}
def __init__(self, diff: Diff, cwd: str, mode: DiffViewMode = "auto") -> None:
super().__init__()
self.diff = diff
self.cwd = cwd
self.files: list[FileDiff] = []
self.raw_patch: str | None = None
if is_set(diff.patch) and diff.patch is not None:
if diff.patch.format == "git_patch":
self.files = parse_patch(diff.patch.text)
else: # a format acptui does not know: show the text as is
self.raw_patch = diff.patch.text
self.set_reactive(DiffView.mode, mode)
self.set_reactive(DiffView.split, mode == "split")
def compose(self) -> ComposeResult:
if not self.files:
for change in self.diff.changes:
operation = self.OPERATIONS.get(change.operation, change.operation.title())
old, new = change_paths(change)
path = relative_display(new or "?", self.cwd)
source = f"{relative_display(old, self.cwd)} → " if old else ""
file_type = (
change.file_type if is_set(change.file_type) and change.file_type else None
)
kind = f" ({file_type})" if file_type and file_type != "text" else ""
yield Static(
Content.assemble(
(f"{operation} ", "bold $accent"),
source,
(path, "bold"),
(kind, "$text-muted"),
),
classes="diff-header",
)
if self.raw_patch is not None:
yield Static(Content(self.raw_patch), classes="diff-lines")
return
operations = {change_paths(c)[1]: c.operation for c in self.diff.changes}
for file in self.files:
path = file.new_path or file.old_path or ""
op = operations.get(path) or (
"add" if file.old_path is None else "delete" if file.new_path is None else "modify"
)
yield Static(
file_header(file, self.OPERATIONS.get(op, op.title()), self.cwd),
classes="diff-header",
)
if file.binary:
yield Static("(binary file)", classes="diff-lines")
elif self.split:
left, right = split_lines(file)
with Horizontal():
yield Static(Content("\n").join(left), classes="diff-lines left")
yield Static(Content("\n").join(right), classes="diff-lines right")
else:
yield Static(Content("\n").join(unified_lines(file)), classes="diff-lines")
def watch_mode(self, mode: DiffViewMode) -> None:
self._update_split()
def on_resize(self, event: Resize) -> None:
self._update_split()
def _update_split(self) -> None:
if self.mode == "auto":
self.split = self.size.width >= SPLIT_MIN_WIDTH
else:
self.split = self.mode == "split"