local-diff-san 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- local_diff_san/__init__.py +27 -0
- local_diff_san/__main__.py +7 -0
- local_diff_san/core.py +587 -0
- local_diff_san/server.py +209 -0
- local_diff_san/templates/local_diff.html +465 -0
- local_diff_san-0.1.0.dist-info/METADATA +60 -0
- local_diff_san-0.1.0.dist-info/RECORD +11 -0
- local_diff_san-0.1.0.dist-info/WHEEL +5 -0
- local_diff_san-0.1.0.dist-info/entry_points.txt +3 -0
- local_diff_san-0.1.0.dist-info/licenses/LICENSE +21 -0
- local_diff_san-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Sanskrit/Indic local file and Git HEAD single-pane & character-level diff viewer."""
|
|
2
|
+
|
|
3
|
+
from local_diff_san.core import (
|
|
4
|
+
DEFAULT_REV,
|
|
5
|
+
LocalDiffItem,
|
|
6
|
+
LocalDiffSpec,
|
|
7
|
+
build_diff_workspace,
|
|
8
|
+
compare_file_with_head,
|
|
9
|
+
compare_two_files,
|
|
10
|
+
discover_git_dir_entries,
|
|
11
|
+
find_git_root,
|
|
12
|
+
read_git_blob,
|
|
13
|
+
resolve_spec_from_paths,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"DEFAULT_REV",
|
|
18
|
+
"LocalDiffItem",
|
|
19
|
+
"LocalDiffSpec",
|
|
20
|
+
"build_diff_workspace",
|
|
21
|
+
"compare_file_with_head",
|
|
22
|
+
"compare_two_files",
|
|
23
|
+
"discover_git_dir_entries",
|
|
24
|
+
"find_git_root",
|
|
25
|
+
"read_git_blob",
|
|
26
|
+
"resolve_spec_from_paths",
|
|
27
|
+
]
|
local_diff_san/core.py
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
"""Local file and Git HEAD diff computation built on pull_requests_san.diff."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass, field
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import subprocess
|
|
8
|
+
from typing import Any, Sequence
|
|
9
|
+
|
|
10
|
+
from pull_requests_san.diff import (
|
|
11
|
+
DiffHunk,
|
|
12
|
+
VALID_DIFF_MODES,
|
|
13
|
+
VALID_NORMALIZATIONS,
|
|
14
|
+
build_full_file_hunk,
|
|
15
|
+
build_unified_patch_from_texts,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
DEFAULT_REV = "HEAD"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class LocalDiffSpec:
|
|
24
|
+
"""Target specification describing which local files or git diffs to view."""
|
|
25
|
+
|
|
26
|
+
mode: str = "git_dir" # "file_pair" | "git_head" | "git_dir"
|
|
27
|
+
left_path: str | None = None
|
|
28
|
+
right_path: str | None = None
|
|
29
|
+
paths: list[str] = field(default_factory=list)
|
|
30
|
+
rev: str = DEFAULT_REV
|
|
31
|
+
|
|
32
|
+
def to_dict(self) -> dict[str, Any]:
|
|
33
|
+
return asdict(self)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class LocalDiffItem:
|
|
38
|
+
"""Single compared item (pair of local files or local file vs Git revision)."""
|
|
39
|
+
|
|
40
|
+
id: str
|
|
41
|
+
title: str
|
|
42
|
+
mode: str
|
|
43
|
+
status: str
|
|
44
|
+
left_label: str
|
|
45
|
+
right_label: str
|
|
46
|
+
left_path: str | None = None
|
|
47
|
+
right_path: str | None = None
|
|
48
|
+
repo_root: str | None = None
|
|
49
|
+
rel_path: str | None = None
|
|
50
|
+
rev: str = DEFAULT_REV
|
|
51
|
+
additions: int = 0
|
|
52
|
+
deletions: int = 0
|
|
53
|
+
is_binary: bool = False
|
|
54
|
+
patch: str = ""
|
|
55
|
+
hunks: list[DiffHunk] = field(default_factory=list)
|
|
56
|
+
|
|
57
|
+
def to_dict(self, *, include_hunks: bool = True) -> dict[str, Any]:
|
|
58
|
+
out = {
|
|
59
|
+
"id": self.id,
|
|
60
|
+
"title": self.title,
|
|
61
|
+
"mode": self.mode,
|
|
62
|
+
"status": self.status,
|
|
63
|
+
"left_label": self.left_label,
|
|
64
|
+
"right_label": self.right_label,
|
|
65
|
+
"left_path": self.left_path,
|
|
66
|
+
"right_path": self.right_path,
|
|
67
|
+
"repo_root": self.repo_root,
|
|
68
|
+
"rel_path": self.rel_path,
|
|
69
|
+
"rev": self.rev,
|
|
70
|
+
"additions": self.additions,
|
|
71
|
+
"deletions": self.deletions,
|
|
72
|
+
"is_binary": self.is_binary,
|
|
73
|
+
"patch": self.patch if include_hunks else "",
|
|
74
|
+
"hunks": [h.to_dict() for h in self.hunks] if include_hunks else [],
|
|
75
|
+
}
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _validate_diff_options(char_diff_mode: str, normalize: str) -> tuple[str, str]:
|
|
80
|
+
mode = (char_diff_mode or "word").strip().lower()
|
|
81
|
+
if mode not in VALID_DIFF_MODES:
|
|
82
|
+
raise ValueError(f"Invalid diff_mode {char_diff_mode!r}; expected one of {VALID_DIFF_MODES}")
|
|
83
|
+
norm = (normalize or "none").strip().lower()
|
|
84
|
+
if norm not in VALID_NORMALIZATIONS:
|
|
85
|
+
raise ValueError(f"Invalid normalize {normalize!r}; expected one of {VALID_NORMALIZATIONS}")
|
|
86
|
+
return mode, norm
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _run_git_bytes(repo_or_dir: Path, args: Sequence[str]) -> subprocess.CompletedProcess[bytes]:
|
|
90
|
+
return subprocess.run(
|
|
91
|
+
["git", "-c", "core.quotePath=false", "-C", str(repo_or_dir), *args],
|
|
92
|
+
capture_output=True,
|
|
93
|
+
check=False,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def find_git_root(path: str | Path) -> Path | None:
|
|
98
|
+
"""Locate the enclosing Git repository root for ``path`` (works even if leaf does not exist)."""
|
|
99
|
+
cur = Path(path).expanduser()
|
|
100
|
+
try:
|
|
101
|
+
cur = cur.resolve()
|
|
102
|
+
except OSError:
|
|
103
|
+
cur = cur.absolute()
|
|
104
|
+
while not cur.is_dir():
|
|
105
|
+
parent = cur.parent
|
|
106
|
+
if parent == cur:
|
|
107
|
+
return None
|
|
108
|
+
cur = parent
|
|
109
|
+
proc = _run_git_bytes(cur, ["rev-parse", "--show-toplevel"])
|
|
110
|
+
if proc.returncode != 0:
|
|
111
|
+
return None
|
|
112
|
+
root_str = proc.stdout.decode("utf-8", errors="replace").strip()
|
|
113
|
+
return Path(root_str).resolve() if root_str else None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _git_has_rev(repo_root: Path, rev: str) -> bool:
|
|
117
|
+
proc = _run_git_bytes(repo_root, ["rev-parse", "--verify", "--quiet", f"{rev}^{{tree}}"])
|
|
118
|
+
return proc.returncode == 0
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def read_git_blob(repo_root: Path, rel_path: str, rev: str = DEFAULT_REV) -> bytes | None:
|
|
122
|
+
"""Read raw bytes of ``rel_path`` at ``rev`` inside ``repo_root``, or None if absent."""
|
|
123
|
+
clean_rel = Path(rel_path).as_posix().lstrip("/")
|
|
124
|
+
proc = _run_git_bytes(repo_root, ["show", f"{rev}:{clean_rel}"])
|
|
125
|
+
if proc.returncode != 0:
|
|
126
|
+
return None
|
|
127
|
+
return proc.stdout
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _is_tracked_in_index(repo_root: Path, rel_path: str) -> bool:
|
|
131
|
+
clean_rel = Path(rel_path).as_posix().lstrip("/")
|
|
132
|
+
proc = _run_git_bytes(repo_root, ["ls-files", "--error-unmatch", "--", clean_rel])
|
|
133
|
+
return proc.returncode == 0
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _decode_text_or_binary(raw: bytes | None) -> tuple[str | None, bool]:
|
|
137
|
+
if raw is None:
|
|
138
|
+
return None, False
|
|
139
|
+
if b"\x00" in raw[:8192]:
|
|
140
|
+
return None, True
|
|
141
|
+
return raw.decode("utf-8", errors="replace"), False
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _count_patch_stats(patch: str) -> tuple[int, int]:
|
|
145
|
+
adds = 0
|
|
146
|
+
dels = 0
|
|
147
|
+
for ln in (patch or "").splitlines():
|
|
148
|
+
if ln.startswith("+++") or ln.startswith("---"):
|
|
149
|
+
continue
|
|
150
|
+
if ln.startswith("+"):
|
|
151
|
+
adds += 1
|
|
152
|
+
elif ln.startswith("-"):
|
|
153
|
+
dels += 1
|
|
154
|
+
return adds, dels
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _compute_item_from_bytes(
|
|
158
|
+
*,
|
|
159
|
+
item_id: str,
|
|
160
|
+
title: str,
|
|
161
|
+
mode: str,
|
|
162
|
+
status: str,
|
|
163
|
+
left_label: str,
|
|
164
|
+
right_label: str,
|
|
165
|
+
left_bytes: bytes | None,
|
|
166
|
+
right_bytes: bytes | None,
|
|
167
|
+
left_path: str | None = None,
|
|
168
|
+
right_path: str | None = None,
|
|
169
|
+
repo_root: str | None = None,
|
|
170
|
+
rel_path: str | None = None,
|
|
171
|
+
rev: str = DEFAULT_REV,
|
|
172
|
+
display_name: str = "file",
|
|
173
|
+
previous_name: str | None = None,
|
|
174
|
+
char_diff_mode: str = "word",
|
|
175
|
+
normalize: str = "none",
|
|
176
|
+
ignore_punct: bool = False,
|
|
177
|
+
) -> LocalDiffItem:
|
|
178
|
+
left_text, left_bin = _decode_text_or_binary(left_bytes)
|
|
179
|
+
right_text, right_bin = _decode_text_or_binary(right_bytes)
|
|
180
|
+
is_binary = left_bin or right_bin
|
|
181
|
+
if is_binary:
|
|
182
|
+
return LocalDiffItem(
|
|
183
|
+
id=item_id,
|
|
184
|
+
title=title,
|
|
185
|
+
mode=mode,
|
|
186
|
+
status=status,
|
|
187
|
+
left_label=left_label,
|
|
188
|
+
right_label=right_label,
|
|
189
|
+
left_path=left_path,
|
|
190
|
+
right_path=right_path,
|
|
191
|
+
repo_root=repo_root,
|
|
192
|
+
rel_path=rel_path,
|
|
193
|
+
rev=rev,
|
|
194
|
+
is_binary=True,
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
patch = build_unified_patch_from_texts(
|
|
198
|
+
left_text,
|
|
199
|
+
right_text,
|
|
200
|
+
display_name,
|
|
201
|
+
previous_filename=previous_name,
|
|
202
|
+
)
|
|
203
|
+
adds, dels = _count_patch_stats(patch)
|
|
204
|
+
hunk = build_full_file_hunk(
|
|
205
|
+
left_text,
|
|
206
|
+
right_text,
|
|
207
|
+
existing_patch=patch or None,
|
|
208
|
+
char_diff_mode=char_diff_mode,
|
|
209
|
+
normalize=normalize,
|
|
210
|
+
ignore_punct=ignore_punct,
|
|
211
|
+
)
|
|
212
|
+
return LocalDiffItem(
|
|
213
|
+
id=item_id,
|
|
214
|
+
title=title,
|
|
215
|
+
mode=mode,
|
|
216
|
+
status=status,
|
|
217
|
+
left_label=left_label,
|
|
218
|
+
right_label=right_label,
|
|
219
|
+
left_path=left_path,
|
|
220
|
+
right_path=right_path,
|
|
221
|
+
repo_root=repo_root,
|
|
222
|
+
rel_path=rel_path,
|
|
223
|
+
rev=rev,
|
|
224
|
+
additions=adds,
|
|
225
|
+
deletions=dels,
|
|
226
|
+
is_binary=False,
|
|
227
|
+
patch=patch,
|
|
228
|
+
hunks=[hunk],
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def compare_two_files(
|
|
233
|
+
left_path: str | Path,
|
|
234
|
+
right_path: str | Path,
|
|
235
|
+
*,
|
|
236
|
+
char_diff_mode: str = "word",
|
|
237
|
+
normalize: str = "none",
|
|
238
|
+
ignore_punct: bool = False,
|
|
239
|
+
) -> LocalDiffItem:
|
|
240
|
+
"""Compare two local files on disk using ``pull_requests_san.diff``."""
|
|
241
|
+
diff_mode, norm_form = _validate_diff_options(char_diff_mode, normalize)
|
|
242
|
+
lp = Path(left_path).expanduser().resolve()
|
|
243
|
+
rp = Path(right_path).expanduser().resolve()
|
|
244
|
+
if not lp.is_file():
|
|
245
|
+
raise FileNotFoundError(f"Left file not found: {lp}")
|
|
246
|
+
if not rp.is_file():
|
|
247
|
+
raise FileNotFoundError(f"Right file not found: {rp}")
|
|
248
|
+
l_bytes = lp.read_bytes()
|
|
249
|
+
r_bytes = rp.read_bytes()
|
|
250
|
+
status = "unchanged" if l_bytes == r_bytes else "modified"
|
|
251
|
+
title = f"{lp.name} ↔ {rp.name}" if lp.name != rp.name else f"{lp} ↔ {rp}"
|
|
252
|
+
return _compute_item_from_bytes(
|
|
253
|
+
item_id="pair:0",
|
|
254
|
+
title=title,
|
|
255
|
+
mode="file_pair",
|
|
256
|
+
status=status,
|
|
257
|
+
left_label=str(lp),
|
|
258
|
+
right_label=str(rp),
|
|
259
|
+
left_bytes=l_bytes,
|
|
260
|
+
right_bytes=r_bytes,
|
|
261
|
+
left_path=str(lp),
|
|
262
|
+
right_path=str(rp),
|
|
263
|
+
rev="",
|
|
264
|
+
display_name=rp.name,
|
|
265
|
+
previous_name=lp.name,
|
|
266
|
+
char_diff_mode=diff_mode,
|
|
267
|
+
normalize=norm_form,
|
|
268
|
+
ignore_punct=bool(ignore_punct),
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def compare_file_with_head(
|
|
273
|
+
file_path: str | Path,
|
|
274
|
+
*,
|
|
275
|
+
rev: str = DEFAULT_REV,
|
|
276
|
+
old_rel_path: str | None = None,
|
|
277
|
+
item_id: str | None = None,
|
|
278
|
+
char_diff_mode: str = "word",
|
|
279
|
+
normalize: str = "none",
|
|
280
|
+
ignore_punct: bool = False,
|
|
281
|
+
) -> LocalDiffItem:
|
|
282
|
+
"""Compare a local file on disk against its committed version at ``rev`` (default ``HEAD``)."""
|
|
283
|
+
diff_mode, norm_form = _validate_diff_options(char_diff_mode, normalize)
|
|
284
|
+
clean_rev = (rev or DEFAULT_REV).strip() or DEFAULT_REV
|
|
285
|
+
target = Path(file_path).expanduser()
|
|
286
|
+
try:
|
|
287
|
+
target = target.resolve()
|
|
288
|
+
except OSError:
|
|
289
|
+
target = target.absolute()
|
|
290
|
+
if target.is_dir():
|
|
291
|
+
raise ValueError(f"Expected file path, got directory: {target}")
|
|
292
|
+
|
|
293
|
+
repo_root = find_git_root(target)
|
|
294
|
+
if repo_root is None:
|
|
295
|
+
raise ValueError(f"Not inside a git repository: {target}")
|
|
296
|
+
|
|
297
|
+
try:
|
|
298
|
+
rel_path = target.relative_to(repo_root).as_posix()
|
|
299
|
+
except ValueError as exc:
|
|
300
|
+
raise ValueError(f"File {target} is outside git repository {repo_root}") from exc
|
|
301
|
+
|
|
302
|
+
blob_rel = old_rel_path or rel_path
|
|
303
|
+
has_rev = _git_has_rev(repo_root, clean_rev)
|
|
304
|
+
head_bytes = read_git_blob(repo_root, blob_rel, rev=clean_rev) if has_rev else None
|
|
305
|
+
work_bytes = target.read_bytes() if target.is_file() else None
|
|
306
|
+
|
|
307
|
+
if head_bytes is None and work_bytes is None:
|
|
308
|
+
raise FileNotFoundError(f"File not found on disk or at {clean_rev}: {target}")
|
|
309
|
+
|
|
310
|
+
if old_rel_path and old_rel_path != rel_path:
|
|
311
|
+
status = "renamed"
|
|
312
|
+
elif head_bytes is None and work_bytes is not None:
|
|
313
|
+
status = "added" if _is_tracked_in_index(repo_root, rel_path) else "untracked"
|
|
314
|
+
elif head_bytes is not None and work_bytes is None:
|
|
315
|
+
status = "deleted"
|
|
316
|
+
elif head_bytes == work_bytes:
|
|
317
|
+
status = "unchanged"
|
|
318
|
+
else:
|
|
319
|
+
status = "modified"
|
|
320
|
+
|
|
321
|
+
return _compute_item_from_bytes(
|
|
322
|
+
item_id=item_id or f"head:{rel_path}",
|
|
323
|
+
title=rel_path,
|
|
324
|
+
mode="git_head",
|
|
325
|
+
status=status,
|
|
326
|
+
left_label=f"{clean_rev}:{blob_rel}" if head_bytes is not None else f"(absent in {clean_rev})",
|
|
327
|
+
right_label=f"WORKING:{rel_path}" if work_bytes is not None else f"(deleted on disk)",
|
|
328
|
+
left_bytes=head_bytes,
|
|
329
|
+
right_bytes=work_bytes,
|
|
330
|
+
left_path=None,
|
|
331
|
+
right_path=str(target) if work_bytes is not None else None,
|
|
332
|
+
repo_root=str(repo_root),
|
|
333
|
+
rel_path=rel_path,
|
|
334
|
+
rev=clean_rev,
|
|
335
|
+
display_name=rel_path,
|
|
336
|
+
previous_name=old_rel_path,
|
|
337
|
+
char_diff_mode=diff_mode,
|
|
338
|
+
normalize=norm_form,
|
|
339
|
+
ignore_punct=bool(ignore_punct),
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _parse_numstat_z(raw: bytes) -> dict[str, tuple[int, int]]:
|
|
344
|
+
stats: dict[str, tuple[int, int]] = {}
|
|
345
|
+
parts = raw.split(b"\x00")
|
|
346
|
+
i = 0
|
|
347
|
+
while i < len(parts):
|
|
348
|
+
tok = parts[i]
|
|
349
|
+
i += 1
|
|
350
|
+
if not tok:
|
|
351
|
+
continue
|
|
352
|
+
fields = tok.decode("utf-8", errors="replace").split("\t", 2)
|
|
353
|
+
if len(fields) != 3:
|
|
354
|
+
continue
|
|
355
|
+
add_s, del_s, path_s = fields
|
|
356
|
+
adds = int(add_s) if add_s.isdigit() else 0
|
|
357
|
+
dels = int(del_s) if del_s.isdigit() else 0
|
|
358
|
+
if path_s == "" and i + 1 < len(parts):
|
|
359
|
+
# Rename entry in numstat -z: empty path, then old_path\0, new_path\0
|
|
360
|
+
_old_p = parts[i].decode("utf-8", errors="replace")
|
|
361
|
+
new_p = parts[i + 1].decode("utf-8", errors="replace")
|
|
362
|
+
i += 2
|
|
363
|
+
stats[new_p] = (adds, dels)
|
|
364
|
+
else:
|
|
365
|
+
stats[path_s] = (adds, dels)
|
|
366
|
+
return stats
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _parse_name_status_z(raw: bytes) -> list[dict[str, Any]]:
|
|
370
|
+
entries: list[dict[str, Any]] = []
|
|
371
|
+
parts = [p.decode("utf-8", errors="replace") for p in raw.split(b"\x00")]
|
|
372
|
+
i = 0
|
|
373
|
+
status_names = {
|
|
374
|
+
"M": "modified",
|
|
375
|
+
"A": "added",
|
|
376
|
+
"D": "deleted",
|
|
377
|
+
"T": "typechange",
|
|
378
|
+
"U": "unmerged",
|
|
379
|
+
}
|
|
380
|
+
while i < len(parts):
|
|
381
|
+
st_code = parts[i]
|
|
382
|
+
i += 1
|
|
383
|
+
if not st_code:
|
|
384
|
+
continue
|
|
385
|
+
kind = st_code[0]
|
|
386
|
+
if kind in ("R", "C"):
|
|
387
|
+
if i + 1 >= len(parts):
|
|
388
|
+
break
|
|
389
|
+
old_p = parts[i]
|
|
390
|
+
new_p = parts[i + 1]
|
|
391
|
+
i += 2
|
|
392
|
+
entries.append({"rel_path": new_p, "old_rel_path": old_p, "status": "renamed" if kind == "R" else "copied"})
|
|
393
|
+
else:
|
|
394
|
+
if i >= len(parts):
|
|
395
|
+
break
|
|
396
|
+
rel_p = parts[i]
|
|
397
|
+
i += 1
|
|
398
|
+
entries.append({"rel_path": rel_p, "old_rel_path": None, "status": status_names.get(kind, "modified")})
|
|
399
|
+
return entries
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def discover_git_dir_entries(target_dir: str | Path, *, rev: str = DEFAULT_REV) -> tuple[Path | None, list[dict[str, Any]]]:
|
|
403
|
+
"""Discover modified/added/deleted/untracked files under ``target_dir`` relative to ``rev``."""
|
|
404
|
+
clean_rev = (rev or DEFAULT_REV).strip() or DEFAULT_REV
|
|
405
|
+
target = Path(target_dir).expanduser().resolve()
|
|
406
|
+
repo_root = find_git_root(target)
|
|
407
|
+
if repo_root is None:
|
|
408
|
+
return None, []
|
|
409
|
+
|
|
410
|
+
rel_scope = target.relative_to(repo_root).as_posix()
|
|
411
|
+
scope_args = ["--", rel_scope] if rel_scope and rel_scope != "." else []
|
|
412
|
+
|
|
413
|
+
entries: list[dict[str, Any]] = []
|
|
414
|
+
seen: set[str] = set()
|
|
415
|
+
if _git_has_rev(repo_root, clean_rev):
|
|
416
|
+
ns_proc = _run_git_bytes(repo_root, ["diff", "--name-status", "-z", clean_rev, *scope_args])
|
|
417
|
+
num_proc = _run_git_bytes(repo_root, ["diff", "--numstat", "-z", clean_rev, *scope_args])
|
|
418
|
+
numstat = _parse_numstat_z(num_proc.stdout) if num_proc.returncode == 0 else {}
|
|
419
|
+
if ns_proc.returncode == 0:
|
|
420
|
+
for ent in _parse_name_status_z(ns_proc.stdout):
|
|
421
|
+
rp = ent["rel_path"]
|
|
422
|
+
seen.add(rp)
|
|
423
|
+
adds, dels = numstat.get(rp, (0, 0))
|
|
424
|
+
entries.append({**ent, "additions": adds, "deletions": dels})
|
|
425
|
+
|
|
426
|
+
ut_proc = _run_git_bytes(repo_root, ["ls-files", "--others", "--exclude-standard", "-z", *scope_args])
|
|
427
|
+
if ut_proc.returncode == 0:
|
|
428
|
+
for raw_p in ut_proc.stdout.split(b"\x00"):
|
|
429
|
+
rp = raw_p.decode("utf-8", errors="replace")
|
|
430
|
+
if not rp or rp in seen:
|
|
431
|
+
continue
|
|
432
|
+
seen.add(rp)
|
|
433
|
+
disk_file = repo_root / rp
|
|
434
|
+
line_cnt = 0
|
|
435
|
+
if disk_file.is_file():
|
|
436
|
+
try:
|
|
437
|
+
b = disk_file.read_bytes()
|
|
438
|
+
if b"\x00" not in b[:8192]:
|
|
439
|
+
line_cnt = len(b.decode("utf-8", errors="replace").splitlines())
|
|
440
|
+
except OSError:
|
|
441
|
+
pass
|
|
442
|
+
entries.append({"rel_path": rp, "old_rel_path": None, "status": "untracked", "additions": line_cnt, "deletions": 0})
|
|
443
|
+
|
|
444
|
+
entries.sort(key=lambda e: e["rel_path"])
|
|
445
|
+
return repo_root, entries
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def resolve_spec_from_paths(
|
|
449
|
+
paths: Sequence[str] = (),
|
|
450
|
+
*,
|
|
451
|
+
rev: str = DEFAULT_REV,
|
|
452
|
+
force_head: bool = False,
|
|
453
|
+
) -> LocalDiffSpec:
|
|
454
|
+
"""Build a ``LocalDiffSpec`` from CLI path arguments."""
|
|
455
|
+
clean_rev = (rev or DEFAULT_REV).strip() or DEFAULT_REV
|
|
456
|
+
raw_paths = [str(p) for p in paths if str(p).strip()]
|
|
457
|
+
if len(raw_paths) == 0:
|
|
458
|
+
return LocalDiffSpec(mode="git_dir", paths=[str(Path.cwd().resolve())], rev=clean_rev)
|
|
459
|
+
if len(raw_paths) == 2 and not force_head:
|
|
460
|
+
p0 = Path(raw_paths[0]).expanduser().resolve()
|
|
461
|
+
p1 = Path(raw_paths[1]).expanduser().resolve()
|
|
462
|
+
if not p0.is_dir() and not p1.is_dir():
|
|
463
|
+
return LocalDiffSpec(mode="file_pair", left_path=str(p0), right_path=str(p1), rev=clean_rev)
|
|
464
|
+
if len(raw_paths) == 1:
|
|
465
|
+
p0 = Path(raw_paths[0]).expanduser()
|
|
466
|
+
resolved = p0.resolve() if p0.exists() else p0.absolute()
|
|
467
|
+
if resolved.is_dir():
|
|
468
|
+
return LocalDiffSpec(mode="git_dir", paths=[str(resolved)], rev=clean_rev)
|
|
469
|
+
return LocalDiffSpec(mode="git_head", paths=[str(resolved)], rev=clean_rev)
|
|
470
|
+
resolved_list = [str((Path(x).expanduser().resolve() if Path(x).expanduser().exists() else Path(x).expanduser().absolute())) for x in raw_paths]
|
|
471
|
+
return LocalDiffSpec(mode="git_head", paths=resolved_list, rev=clean_rev)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def build_diff_workspace(
|
|
475
|
+
spec: LocalDiffSpec,
|
|
476
|
+
*,
|
|
477
|
+
active_id: str | None = None,
|
|
478
|
+
char_diff_mode: str = "word",
|
|
479
|
+
normalize: str = "none",
|
|
480
|
+
ignore_punct: bool = False,
|
|
481
|
+
) -> dict[str, Any]:
|
|
482
|
+
"""Compute sidebar items and the active file diff payload for ``spec``."""
|
|
483
|
+
diff_mode, norm_form = _validate_diff_options(char_diff_mode, normalize)
|
|
484
|
+
clean_rev = (spec.rev or DEFAULT_REV).strip() or DEFAULT_REV
|
|
485
|
+
|
|
486
|
+
if spec.mode == "file_pair":
|
|
487
|
+
if not spec.left_path or not spec.right_path:
|
|
488
|
+
raise ValueError("Both left_path and right_path are required in 2-file mode")
|
|
489
|
+
item = compare_two_files(
|
|
490
|
+
spec.left_path,
|
|
491
|
+
spec.right_path,
|
|
492
|
+
char_diff_mode=diff_mode,
|
|
493
|
+
normalize=norm_form,
|
|
494
|
+
ignore_punct=bool(ignore_punct),
|
|
495
|
+
)
|
|
496
|
+
payload = item.to_dict(include_hunks=True)
|
|
497
|
+
return {
|
|
498
|
+
"spec": spec.to_dict(),
|
|
499
|
+
"repo_root": None,
|
|
500
|
+
"items": [payload],
|
|
501
|
+
"active_item": payload,
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
if spec.mode == "git_head":
|
|
505
|
+
if not spec.paths:
|
|
506
|
+
raise ValueError("At least one file path is required in Git vs revision mode")
|
|
507
|
+
built_items: list[LocalDiffItem] = []
|
|
508
|
+
for idx, p in enumerate(spec.paths):
|
|
509
|
+
built_items.append(
|
|
510
|
+
compare_file_with_head(
|
|
511
|
+
p,
|
|
512
|
+
rev=clean_rev,
|
|
513
|
+
item_id=f"head:{idx}:{Path(p).name}",
|
|
514
|
+
char_diff_mode=diff_mode,
|
|
515
|
+
normalize=norm_form,
|
|
516
|
+
ignore_punct=bool(ignore_punct),
|
|
517
|
+
)
|
|
518
|
+
)
|
|
519
|
+
chosen = next((it for it in built_items if it.id == active_id), built_items[0])
|
|
520
|
+
chosen_dict = chosen.to_dict(include_hunks=True)
|
|
521
|
+
item_summaries = [
|
|
522
|
+
chosen_dict if it.id == chosen.id else it.to_dict(include_hunks=False)
|
|
523
|
+
for it in built_items
|
|
524
|
+
]
|
|
525
|
+
return {
|
|
526
|
+
"spec": spec.to_dict(),
|
|
527
|
+
"repo_root": chosen.repo_root,
|
|
528
|
+
"items": item_summaries,
|
|
529
|
+
"active_item": chosen_dict,
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
# spec.mode == "git_dir"
|
|
533
|
+
dir_path = Path(spec.paths[0] if spec.paths else Path.cwd()).expanduser().resolve()
|
|
534
|
+
if not dir_path.is_dir():
|
|
535
|
+
raise FileNotFoundError(f"Directory not found: {dir_path}")
|
|
536
|
+
repo_root, entries = discover_git_dir_entries(dir_path, rev=clean_rev)
|
|
537
|
+
if repo_root is None or not entries:
|
|
538
|
+
return {
|
|
539
|
+
"spec": spec.to_dict(),
|
|
540
|
+
"repo_root": str(repo_root) if repo_root else None,
|
|
541
|
+
"items": [],
|
|
542
|
+
"active_item": None,
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
summary_items: list[dict[str, Any]] = []
|
|
546
|
+
by_id: dict[str, dict[str, Any]] = {}
|
|
547
|
+
for ent in entries:
|
|
548
|
+
rel_p = ent["rel_path"]
|
|
549
|
+
old_rp = ent.get("old_rel_path")
|
|
550
|
+
iid = f"head:{rel_p}"
|
|
551
|
+
disk_p = repo_root / rel_p
|
|
552
|
+
summary = LocalDiffItem(
|
|
553
|
+
id=iid,
|
|
554
|
+
title=rel_p,
|
|
555
|
+
mode="git_head",
|
|
556
|
+
status=ent["status"],
|
|
557
|
+
left_label=f"{clean_rev}:{old_rp or rel_p}" if ent["status"] != "untracked" else f"(absent in {clean_rev})",
|
|
558
|
+
right_label=f"WORKING:{rel_p}" if disk_p.is_file() else "(deleted on disk)",
|
|
559
|
+
left_path=None,
|
|
560
|
+
right_path=str(disk_p) if disk_p.is_file() else None,
|
|
561
|
+
repo_root=str(repo_root),
|
|
562
|
+
rel_path=rel_p,
|
|
563
|
+
rev=clean_rev,
|
|
564
|
+
additions=ent["additions"],
|
|
565
|
+
deletions=ent["deletions"],
|
|
566
|
+
).to_dict(include_hunks=False)
|
|
567
|
+
summary_items.append(summary)
|
|
568
|
+
by_id[iid] = ent
|
|
569
|
+
|
|
570
|
+
target_id = active_id if (active_id and active_id in by_id) else summary_items[0]["id"]
|
|
571
|
+
chosen_ent = by_id[target_id]
|
|
572
|
+
active_obj = compare_file_with_head(
|
|
573
|
+
repo_root / chosen_ent["rel_path"],
|
|
574
|
+
rev=clean_rev,
|
|
575
|
+
old_rel_path=chosen_ent.get("old_rel_path"),
|
|
576
|
+
item_id=target_id,
|
|
577
|
+
char_diff_mode=diff_mode,
|
|
578
|
+
normalize=norm_form,
|
|
579
|
+
ignore_punct=bool(ignore_punct),
|
|
580
|
+
).to_dict(include_hunks=True)
|
|
581
|
+
items_out = [active_obj if s["id"] == target_id else s for s in summary_items]
|
|
582
|
+
return {
|
|
583
|
+
"spec": spec.to_dict(),
|
|
584
|
+
"repo_root": str(repo_root),
|
|
585
|
+
"items": items_out,
|
|
586
|
+
"active_item": active_obj,
|
|
587
|
+
}
|