diffguard-ai 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.
Files changed (49) hide show
  1. diffguard/__init__.py +39 -0
  2. diffguard/__main__.py +4 -0
  3. diffguard/baselines/__init__.py +0 -0
  4. diffguard/baselines/manager.py +97 -0
  5. diffguard/cli/__init__.py +1 -0
  6. diffguard/cli/main.py +323 -0
  7. diffguard/core/__init__.py +0 -0
  8. diffguard/core/enums.py +103 -0
  9. diffguard/core/exceptions.py +57 -0
  10. diffguard/core/interfaces.py +20 -0
  11. diffguard/core/models.py +301 -0
  12. diffguard/engine/__init__.py +0 -0
  13. diffguard/engine/evaluator.py +42 -0
  14. diffguard/engine/orchestrator.py +74 -0
  15. diffguard/engine/registry.py +142 -0
  16. diffguard/engine/scanner.py +141 -0
  17. diffguard/git/__init__.py +0 -0
  18. diffguard/git/client.py +179 -0
  19. diffguard/git/diff_parser.py +298 -0
  20. diffguard/git/repository.py +174 -0
  21. diffguard/policies/__init__.py +0 -0
  22. diffguard/policies/loader.py +75 -0
  23. diffguard/policies/schema.py +292 -0
  24. diffguard/py.typed +0 -0
  25. diffguard/reporting/__init__.py +0 -0
  26. diffguard/reporting/json_report.py +104 -0
  27. diffguard/reporting/markdown_report.py +96 -0
  28. diffguard/reporting/text_report.py +43 -0
  29. diffguard/rules/__init__.py +0 -0
  30. diffguard/rules/base.py +248 -0
  31. diffguard/rules/configuration.py +98 -0
  32. diffguard/rules/dangerous_patterns.py +290 -0
  33. diffguard/rules/dependencies.py +375 -0
  34. diffguard/rules/filetypes.py +49 -0
  35. diffguard/rules/scope.py +108 -0
  36. diffguard/rules/secret_patterns.py +195 -0
  37. diffguard/rules/secrets.py +118 -0
  38. diffguard/rules/test_removal.py +253 -0
  39. diffguard/suppressions/__init__.py +0 -0
  40. diffguard/suppressions/manager.py +81 -0
  41. diffguard/utils/__init__.py +0 -0
  42. diffguard/utils/logging.py +23 -0
  43. diffguard/utils/paths.py +131 -0
  44. diffguard/version.py +1 -0
  45. diffguard_ai-0.1.0.dist-info/METADATA +141 -0
  46. diffguard_ai-0.1.0.dist-info/RECORD +49 -0
  47. diffguard_ai-0.1.0.dist-info/WHEEL +4 -0
  48. diffguard_ai-0.1.0.dist-info/entry_points.txt +2 -0
  49. diffguard_ai-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,179 @@
1
+ """Thin, safe wrapper around the ``git`` executable.
2
+
3
+ * Never uses a shell; arguments are passed as a list.
4
+ * Every call has a timeout and an output-size limit.
5
+ * Revisions are validated (no option injection, no control characters).
6
+ * Repository-controlled execution hooks are disabled where Git allows it
7
+ (``core.fsmonitor`` on every call; external diff drivers and textconv on diffs).
8
+ Filter drivers (clean/smudge) are not disabled: do not scan repositories whose
9
+ ``.git/config`` you do not trust.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import shutil
16
+ import subprocess
17
+ from collections.abc import Sequence
18
+ from pathlib import Path
19
+
20
+ from diffguard.core.exceptions import (
21
+ GitCommandError,
22
+ GitUnavailableError,
23
+ ScanInputError,
24
+ )
25
+ from diffguard.utils.logging import get_logger
26
+
27
+ log = get_logger("git")
28
+
29
+ DEFAULT_TIMEOUT = 60.0
30
+ MAX_OUTPUT_BYTES = 64 * 1024 * 1024
31
+ MAX_FILE_BYTES = 5 * 1024 * 1024
32
+
33
+ _DIFF_ARGS = (
34
+ "diff", "--no-color", "--no-ext-diff", "--no-textconv",
35
+ "--src-prefix=a/", "--dst-prefix=b/", "--find-renames", "--find-copies", "--unified=3",
36
+ ) # fmt: skip
37
+
38
+
39
+ def validate_revision(rev: str) -> str:
40
+ if not isinstance(rev, str) or not rev.strip():
41
+ raise ScanInputError("revision must be a non-empty string")
42
+ if rev.startswith("-"):
43
+ raise ScanInputError(f"invalid revision {rev!r}: must not start with '-'")
44
+ if any(ord(c) < 32 or ord(c) == 127 for c in rev):
45
+ raise ScanInputError("invalid revision: control characters are not allowed")
46
+ return rev
47
+
48
+
49
+ class GitClient:
50
+ def __init__(
51
+ self,
52
+ executable: str | None = None,
53
+ timeout: float = DEFAULT_TIMEOUT,
54
+ max_output_bytes: int = MAX_OUTPUT_BYTES,
55
+ ) -> None:
56
+ self._executable = executable
57
+ self._timeout = timeout
58
+ self._max_output = max_output_bytes
59
+
60
+ def _git(self) -> str:
61
+ found = self._executable or shutil.which("git")
62
+ if not found:
63
+ raise GitUnavailableError("git executable not found on PATH; install Git to scan")
64
+ return found
65
+
66
+ def _run(self, args: Sequence[str], cwd: Path, ok_codes: Sequence[int] = (0,)) -> tuple[int, bytes, str]:
67
+ cmd = [self._git(), "-c", "core.fsmonitor=false", *args]
68
+ env = dict(os.environ)
69
+ env.update({"GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C", "GIT_PAGER": "cat"})
70
+ log.debug("running: %s (cwd=%s)", " ".join(cmd), cwd)
71
+ try:
72
+ proc = subprocess.run( # noqa: S603 - fixed argv, no shell
73
+ cmd,
74
+ cwd=cwd,
75
+ capture_output=True,
76
+ stdin=subprocess.DEVNULL,
77
+ timeout=self._timeout,
78
+ env=env,
79
+ check=False,
80
+ )
81
+ except subprocess.TimeoutExpired as exc:
82
+ raise GitUnavailableError(
83
+ f"git timed out after {self._timeout:.0f}s running 'git {args[0]}'"
84
+ ) from exc
85
+ except OSError as exc:
86
+ raise GitUnavailableError(f"could not execute git: {exc}") from exc
87
+ stderr = proc.stderr.decode("utf-8", errors="replace").strip()
88
+ if proc.returncode not in ok_codes:
89
+ return proc.returncode, b"", stderr
90
+ if len(proc.stdout) > self._max_output:
91
+ raise ScanInputError(
92
+ f"git output exceeds {self._max_output // (1024 * 1024)} MiB; "
93
+ "scan a smaller range or exclude generated files"
94
+ )
95
+ return proc.returncode, proc.stdout, stderr
96
+
97
+ def _must(self, args: Sequence[str], cwd: Path, ok_codes: Sequence[int] = (0,)) -> bytes:
98
+ code, out, err = self._run(args, cwd, ok_codes)
99
+ if code not in ok_codes:
100
+ raise GitCommandError(f"'git {args[0]}' failed (exit {code}): {err}")
101
+ return out
102
+
103
+ # ------------------------------------------------------------ repository info
104
+ def repo_root(self, path: Path) -> Path:
105
+ code, out, err = self._run(["rev-parse", "--show-toplevel"], path)
106
+ if code != 0:
107
+ if "not a git repository" in err.lower():
108
+ raise ScanInputError(f"{path} is not inside a Git repository")
109
+ raise GitCommandError(f"could not determine repository root: {err}")
110
+ return Path(out.decode("utf-8", errors="replace").strip())
111
+
112
+ def resolve_commit(self, root: Path, rev: str) -> str:
113
+ validate_revision(rev)
114
+ code, out, _ = self._run(["rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}"], root)
115
+ if code != 0:
116
+ raise ScanInputError(f"unknown revision {rev!r}")
117
+ return out.decode().strip()
118
+
119
+ def head_commit(self, root: Path) -> str | None:
120
+ code, out, _ = self._run(["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], root)
121
+ return out.decode().strip() if code == 0 else None
122
+
123
+ def current_branch(self, root: Path) -> str | None:
124
+ code, out, _ = self._run(["symbolic-ref", "--short", "-q", "HEAD"], root)
125
+ return out.decode().strip() if code == 0 else None
126
+
127
+ def merge_base(self, root: Path, a: str, b: str) -> str:
128
+ code, out, err = self._run(["merge-base", a, b], root)
129
+ if code != 0:
130
+ raise ScanInputError(
131
+ f"no merge base between {a[:12]} and {b[:12]}. In CI, fetch full history "
132
+ "(for example actions/checkout with fetch-depth: 0). " + err
133
+ )
134
+ return out.decode().strip()
135
+
136
+ # ------------------------------------------------------------------ diffs
137
+ def diff_commits(self, root: Path, base_sha: str, head_sha: str) -> str:
138
+ out = self._must([*_DIFF_ARGS, base_sha, head_sha, "--"], root)
139
+ return out.decode("utf-8", errors="replace")
140
+
141
+ def diff_staged(self, root: Path) -> str:
142
+ args = [*_DIFF_ARGS, "--cached"]
143
+ if self.head_commit(root) is not None:
144
+ args.append("HEAD")
145
+ return self._must([*args, "--"], root).decode("utf-8", errors="replace")
146
+
147
+ def diff_worktree(self, root: Path) -> str:
148
+ if self.head_commit(root) is None:
149
+ raise ScanInputError("repository has no commits yet; use --staged or --diff-file instead")
150
+ out = self._must([*_DIFF_ARGS, "HEAD", "--"], root)
151
+ return out.decode("utf-8", errors="replace")
152
+
153
+ def untracked_files(self, root: Path) -> list[str]:
154
+ out = self._must(["ls-files", "--others", "--exclude-standard", "-z"], root)
155
+ return [p.decode("utf-8", errors="replace") for p in out.split(b"\x00") if p]
156
+
157
+ def diff_untracked(self, root: Path, relative: str) -> str:
158
+ """Diff of one untracked file as a new file (does not touch the index)."""
159
+ target = root / relative
160
+ try:
161
+ size = target.lstat().st_size
162
+ except OSError as exc:
163
+ raise ScanInputError(f"cannot read untracked file {relative!r}: {exc}") from exc
164
+ if size > MAX_FILE_BYTES:
165
+ quoted = relative.replace("\\", "\\\\").replace('"', '\\"')
166
+ header = f'diff --git "a/{quoted}" "b/{quoted}"'
167
+ return f'{header}\nnew file mode 100644\nBinary files /dev/null and "b/{quoted}" differ\n'
168
+ # Git treats the literal "/dev/null" specially on every platform, including Windows.
169
+ args = [*_DIFF_ARGS, "--no-index", "--", "/dev/null", relative] # fmt: skip
170
+ out = self._must(args, root, ok_codes=(0, 1))
171
+ return out.decode("utf-8", errors="replace")
172
+
173
+ # ----------------------------------------------------------------- contents
174
+ def show(self, root: Path, spec: str) -> bytes | None:
175
+ """Bytes of ``<rev>:<path>`` (or ``:<path>`` for the index); ``None`` if absent."""
176
+ code, out, _ = self._run(["show", spec], root)
177
+ if code != 0 or len(out) > MAX_FILE_BYTES:
178
+ return None
179
+ return out
@@ -0,0 +1,298 @@
1
+ """Parser for Git-style unified diffs.
2
+
3
+ Supported: added/modified/deleted/renamed/copied files, mode changes, binary
4
+ files, empty files, multiple hunks, quoted paths, paths with spaces and unicode.
5
+
6
+ Not supported (rejected with :class:`DiffParseError`, never guessed at): combined
7
+ diffs (``diff --cc``), plain ``diff -u`` output without ``diff --git`` headers,
8
+ and ``diff --git`` headers lacking the ``a/``/``b/`` prefixes. Text before the first
9
+ ``diff --git`` header (for example a commit message from ``git show``) is ignored.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+
16
+ from diffguard.core.enums import ChangeType, LineKind
17
+ from diffguard.core.exceptions import DiffParseError
18
+ from diffguard.core.models import ChangedLine, DiffDocument, DiffHunk, FileChange
19
+
20
+ _GIT_HEADER = "diff --git "
21
+ _HUNK_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?: ?(.*))?$")
22
+ _ESCAPES = {
23
+ "a": 7, "b": 8, "f": 12, "n": 10, "r": 13, "t": 9, "v": 11, '"': 34, "\\": 92,
24
+ } # fmt: skip
25
+ _NULL_PATH = "/dev/null"
26
+
27
+
28
+ def _read_quoted(text: str, start: int, lineno: int) -> tuple[str, int]:
29
+ """Decode a C-style quoted string starting at ``text[start] == '"'``."""
30
+ assert text[start] == '"'
31
+ out = bytearray()
32
+ i = start + 1
33
+ n = len(text)
34
+ while i < n:
35
+ c = text[i]
36
+ if c == '"':
37
+ return out.decode("utf-8", errors="replace"), i + 1
38
+ if c == "\\":
39
+ i += 1
40
+ if i >= n:
41
+ break
42
+ e = text[i]
43
+ if e in "01234567":
44
+ digits = e
45
+ while len(digits) < 3 and i + 1 < n and text[i + 1] in "01234567":
46
+ i += 1
47
+ digits += text[i]
48
+ out.append(int(digits, 8) & 0xFF)
49
+ elif e in _ESCAPES:
50
+ out.append(_ESCAPES[e])
51
+ else:
52
+ raise DiffParseError(f"line {lineno}: unknown escape '\\{e}' in quoted path")
53
+ else:
54
+ out.extend(c.encode("utf-8"))
55
+ i += 1
56
+ raise DiffParseError(f"line {lineno}: unterminated quoted path")
57
+
58
+
59
+ def _decode_path(text: str, lineno: int) -> str:
60
+ """A path that is either a bare string or entirely C-quoted."""
61
+ if text.startswith('"'):
62
+ value, end = _read_quoted(text, 0, lineno)
63
+ if end != len(text):
64
+ raise DiffParseError(f"line {lineno}: unexpected text after quoted path")
65
+ return value
66
+ return text
67
+
68
+
69
+ def _strip_prefix(path: str, prefix: str, lineno: int) -> str:
70
+ if not path.startswith(prefix):
71
+ raise DiffParseError(
72
+ f"line {lineno}: expected path prefix {prefix!r} in {path!r}; "
73
+ "diffguard requires standard a/ and b/ prefixes (do not use --no-prefix)"
74
+ )
75
+ return path[len(prefix) :]
76
+
77
+
78
+ def _parse_git_header(rest: str, lineno: int) -> tuple[str, str]:
79
+ """Extract ``(old_path, new_path)`` from the text after ``diff --git ``."""
80
+ if rest.startswith('"'):
81
+ first, idx = _read_quoted(rest, 0, lineno)
82
+ if idx >= len(rest) or rest[idx] != " ":
83
+ raise DiffParseError(f"line {lineno}: malformed diff header")
84
+ second = _decode_path(rest[idx + 1 :], lineno)
85
+ return _strip_prefix(first, "a/", lineno), _strip_prefix(second, "b/", lineno)
86
+ if not rest.startswith("a/"):
87
+ raise DiffParseError(f"line {lineno}: malformed diff header: {rest!r}")
88
+ quoted_second = rest.find(' "b/')
89
+ if quoted_second != -1 and rest.endswith('"'):
90
+ first = rest[:quoted_second]
91
+ second = _decode_path(rest[quoted_second + 1 :], lineno)
92
+ return _strip_prefix(first, "a/", lineno), _strip_prefix(second, "b/", lineno)
93
+ candidates = [m.start() for m in re.finditer(r" b/", rest)]
94
+ if not candidates:
95
+ raise DiffParseError(f"line {lineno}: malformed diff header: {rest!r}")
96
+ for k in candidates:
97
+ left, right = rest[2:k], rest[k + 3 :]
98
+ if left == right:
99
+ return left, right
100
+ # Differing names (rename/copy). Extended headers carry the exact paths and
101
+ # override these; this best guess is only used if they are absent.
102
+ k = candidates[0]
103
+ return rest[2:k], rest[k + 3 :]
104
+
105
+
106
+ def _parse_marker_path(text: str, lineno: int) -> str:
107
+ """Value of a ``---``/``+++`` line, minus the optional trailing tab."""
108
+ text = text.split("\t", 1)[0] if not text.startswith('"') else text
109
+ return _decode_path(text.rstrip(), lineno)
110
+
111
+
112
+ def parse_diff(text: str) -> DiffDocument:
113
+ """Parse ``text`` into a :class:`DiffDocument`. Raises :class:`DiffParseError`."""
114
+ if "\x00" in text:
115
+ raise DiffParseError("diff contains NUL bytes")
116
+ if not text.strip():
117
+ return DiffDocument(())
118
+ lines = text.split("\n")
119
+ if lines and lines[-1] == "":
120
+ lines.pop()
121
+ n = len(lines)
122
+ i = 0
123
+ while i < n and not lines[i].startswith(_GIT_HEADER):
124
+ if lines[i].startswith(("diff --cc ", "diff --combined ")):
125
+ raise DiffParseError(f"line {i + 1}: combined diffs are not supported")
126
+ i += 1
127
+ if i >= n:
128
+ raise DiffParseError("no 'diff --git' header found; only Git-style unified diffs are supported")
129
+ files: list[FileChange] = []
130
+ while i < n:
131
+ if lines[i].startswith(("diff --cc ", "diff --combined ")):
132
+ raise DiffParseError(f"line {i + 1}: combined diffs are not supported")
133
+ if lines[i] == "-- " and n - i <= 3: # `git format-patch` signature
134
+ break
135
+ if not lines[i].startswith(_GIT_HEADER):
136
+ raise DiffParseError(f"line {i + 1}: unexpected content outside any diff block")
137
+ change, i = _parse_file(lines, i)
138
+ files.append(change)
139
+ return DiffDocument(tuple(files))
140
+
141
+
142
+ def _parse_file(lines: list[str], start: int) -> tuple[FileChange, int]:
143
+ n = len(lines)
144
+ header_no = start + 1
145
+ old_path, new_path = _parse_git_header(lines[start][len(_GIT_HEADER) :].rstrip("\r"), header_no)
146
+ old_mode = new_mode = None
147
+ new_file = deleted_file = False
148
+ rename_from = rename_to = copy_from = copy_to = None
149
+ similarity: int | None = None
150
+ is_binary = False
151
+ minus_null = plus_null = False
152
+ hunks: tuple[DiffHunk, ...] = ()
153
+ i = start + 1
154
+ while i < n:
155
+ line = lines[i].rstrip("\r")
156
+ lineno = i + 1
157
+ if line.startswith(_GIT_HEADER):
158
+ break
159
+ if line.startswith("old mode "):
160
+ old_mode = line[9:].strip()
161
+ elif line.startswith("new mode "):
162
+ new_mode = line[9:].strip()
163
+ elif line.startswith("deleted file mode "):
164
+ deleted_file, old_mode = True, line[18:].strip()
165
+ elif line.startswith("new file mode "):
166
+ new_file, new_mode = True, line[14:].strip()
167
+ elif line.startswith("similarity index "):
168
+ digits = line[17:].strip().rstrip("%")
169
+ similarity = int(digits) if digits.isdigit() else None
170
+ elif line.startswith("dissimilarity index "):
171
+ pass
172
+ elif line.startswith("rename from "):
173
+ rename_from = _decode_path(line[12:], lineno)
174
+ elif line.startswith("rename to "):
175
+ rename_to = _decode_path(line[10:], lineno)
176
+ elif line.startswith("copy from "):
177
+ copy_from = _decode_path(line[10:], lineno)
178
+ elif line.startswith("copy to "):
179
+ copy_to = _decode_path(line[8:], lineno)
180
+ elif line.startswith("index "):
181
+ pass
182
+ elif line.startswith("Binary files "):
183
+ is_binary = True
184
+ elif line.startswith("GIT binary patch"):
185
+ is_binary = True
186
+ i += 1
187
+ while i < n and not lines[i].startswith(_GIT_HEADER):
188
+ i += 1
189
+ break
190
+ elif line.startswith("--- "):
191
+ if i + 1 >= n or not lines[i + 1].startswith("+++ "):
192
+ raise DiffParseError(f"line {lineno}: '---' line is not followed by '+++'")
193
+ minus_null = _parse_marker_path(line[4:], lineno) == _NULL_PATH
194
+ plus_null = _parse_marker_path(lines[i + 1][4:].rstrip("\r"), lineno + 1) == _NULL_PATH
195
+ hunks, i = _parse_hunks(lines, i + 2)
196
+ break
197
+ elif line.startswith("@@"):
198
+ raise DiffParseError(f"line {lineno}: hunk without '---'/'+++' file header")
199
+ else:
200
+ raise DiffParseError(f"line {lineno}: unrecognized diff header line: {line[:80]!r}")
201
+ i += 1
202
+
203
+ if rename_from is not None or rename_to is not None:
204
+ if rename_from is None or rename_to is None:
205
+ raise DiffParseError(f"line {header_no}: incomplete rename headers")
206
+ old_path, new_path = rename_from, rename_to
207
+ change_type = ChangeType.RENAMED
208
+ elif copy_from is not None or copy_to is not None:
209
+ if copy_from is None or copy_to is None:
210
+ raise DiffParseError(f"line {header_no}: incomplete copy headers")
211
+ old_path, new_path = copy_from, copy_to
212
+ change_type = ChangeType.COPIED
213
+ elif new_file or (minus_null and not deleted_file):
214
+ change_type = ChangeType.ADDED
215
+ elif deleted_file or plus_null:
216
+ change_type = ChangeType.DELETED
217
+ elif old_mode and new_mode and old_mode != new_mode and not hunks and not is_binary:
218
+ change_type = ChangeType.MODE_CHANGED
219
+ else:
220
+ change_type = ChangeType.MODIFIED
221
+
222
+ final_old: str | None = None if change_type is ChangeType.ADDED else old_path
223
+ final_new: str | None = None if change_type is ChangeType.DELETED else new_path
224
+ if change_type not in (ChangeType.RENAMED, ChangeType.COPIED) and (
225
+ final_old is not None and final_new is not None and final_old != final_new
226
+ ):
227
+ raise DiffParseError(f"line {header_no}: source and destination paths differ without rename headers")
228
+ return (
229
+ FileChange(
230
+ change_type=change_type,
231
+ old_path=final_old,
232
+ new_path=final_new,
233
+ hunks=hunks,
234
+ is_binary=is_binary,
235
+ old_mode=old_mode,
236
+ new_mode=new_mode,
237
+ similarity=similarity,
238
+ ),
239
+ i,
240
+ )
241
+
242
+
243
+ def _parse_hunks(lines: list[str], start: int) -> tuple[tuple[DiffHunk, ...], int]:
244
+ n = len(lines)
245
+ i = start
246
+ hunks: list[DiffHunk] = []
247
+ while i < n:
248
+ match = _HUNK_RE.match(lines[i].rstrip("\r"))
249
+ if match is None:
250
+ break
251
+ old_start = int(match.group(1))
252
+ old_count = int(match.group(2)) if match.group(2) is not None else 1
253
+ new_start = int(match.group(3))
254
+ new_count = int(match.group(4)) if match.group(4) is not None else 1
255
+ section = match.group(5) or ""
256
+ i += 1
257
+ old_ln, new_ln = old_start, new_start
258
+ old_left, new_left = old_count, new_count
259
+ collected: list[ChangedLine] = []
260
+ while old_left > 0 or new_left > 0:
261
+ if i >= n:
262
+ raise DiffParseError(f"line {i + 1}: truncated hunk (diff ended early)")
263
+ raw = lines[i]
264
+ if raw.startswith("\\"):
265
+ i += 1
266
+ continue
267
+ tag, content = raw[:1], raw[1:]
268
+ if content.endswith("\r"):
269
+ content = content[:-1]
270
+ if tag == "+":
271
+ if new_left <= 0:
272
+ raise DiffParseError(f"line {i + 1}: hunk has more added lines than declared")
273
+ collected.append(ChangedLine(LineKind.ADDED, content, None, new_ln))
274
+ new_ln += 1
275
+ new_left -= 1
276
+ elif tag == "-":
277
+ if old_left <= 0:
278
+ raise DiffParseError(f"line {i + 1}: hunk has more removed lines than declared")
279
+ collected.append(ChangedLine(LineKind.REMOVED, content, old_ln, None))
280
+ old_ln += 1
281
+ old_left -= 1
282
+ elif tag == " " or raw == "":
283
+ if old_left <= 0 or new_left <= 0:
284
+ raise DiffParseError(f"line {i + 1}: hunk has more context lines than declared")
285
+ collected.append(ChangedLine(LineKind.CONTEXT, content, old_ln, new_ln))
286
+ old_ln += 1
287
+ new_ln += 1
288
+ old_left -= 1
289
+ new_left -= 1
290
+ else:
291
+ raise DiffParseError(f"line {i + 1}: invalid hunk line: {raw[:80]!r}")
292
+ i += 1
293
+ while i < n and lines[i].startswith("\\"):
294
+ i += 1
295
+ hunks.append(DiffHunk(old_start, old_count, new_start, new_count, section, tuple(collected)))
296
+ if i < n and not lines[i].startswith(_GIT_HEADER) and not (lines[i] == "-- " and n - i <= 3):
297
+ raise DiffParseError(f"line {i + 1}: unexpected content after hunk: {lines[i][:80]!r}")
298
+ return tuple(hunks), i
@@ -0,0 +1,174 @@
1
+ """Resolve a :class:`ScanRequest` into diff text plus a content reader."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from diffguard.core.enums import ChangeType, ScanMode
10
+ from diffguard.core.exceptions import ScanInputError
11
+ from diffguard.core.interfaces import ContentReader, Side
12
+ from diffguard.core.models import DiffDocument, FileChange, RepositoryInfo, ScanRequest
13
+ from diffguard.git.client import MAX_FILE_BYTES, GitClient
14
+ from diffguard.git.diff_parser import parse_diff
15
+ from diffguard.utils.logging import get_logger
16
+ from diffguard.utils.paths import resolve_within
17
+
18
+ log = get_logger("repository")
19
+ MAX_UNTRACKED_FILES = 2000
20
+ MAX_DIFF_INPUT_BYTES = 64 * 1024 * 1024
21
+
22
+
23
+ def _decode(data: bytes | None) -> str | None:
24
+ if data is None or len(data) > MAX_FILE_BYTES or b"\x00" in data:
25
+ return None
26
+ try:
27
+ return data.decode("utf-8")
28
+ except UnicodeDecodeError:
29
+ return None
30
+
31
+
32
+ class GitContentReader:
33
+ """Reads old/new file contents from Git objects, the index, or the working tree."""
34
+
35
+ def __init__(self, client: GitClient, root: Path, old_rev: str | None, new_source: str) -> None:
36
+ """``new_source`` is a commit SHA, ``":index"`` or ``":worktree"``."""
37
+ self._client = client
38
+ self._root = root
39
+ self._old_rev = old_rev
40
+ self._new_source = new_source
41
+
42
+ def read(self, change: FileChange, side: Side) -> str | None:
43
+ if change.is_binary:
44
+ return None
45
+ if side == "old":
46
+ if change.old_path is None or self._old_rev is None:
47
+ return None
48
+ return _decode(self._client.show(self._root, f"{self._old_rev}:{change.old_path}"))
49
+ if change.new_path is None:
50
+ return None
51
+ if self._new_source == ":worktree":
52
+ return self._read_worktree(change.new_path)
53
+ if self._new_source == ":index":
54
+ return _decode(self._client.show(self._root, f":{change.new_path}"))
55
+ return _decode(self._client.show(self._root, f"{self._new_source}:{change.new_path}"))
56
+
57
+ def _read_worktree(self, relative: str) -> str | None:
58
+ try:
59
+ path = resolve_within(self._root, relative)
60
+ if (self._root / relative).is_symlink() or not path.is_file():
61
+ return None
62
+ if path.stat().st_size > MAX_FILE_BYTES:
63
+ return None
64
+ return _decode(path.read_bytes())
65
+ except (OSError, ValueError):
66
+ return None
67
+ except Exception: # PathSafetyError and friends: unreadable, not fatal
68
+ return None
69
+
70
+
71
+ class DiffContentReader:
72
+ """Reconstructs contents from the diff itself (only whole-file adds/deletes)."""
73
+
74
+ def read(self, change: FileChange, side: Side) -> str | None:
75
+ if change.is_binary or "120000" in (change.old_mode, change.new_mode):
76
+ return None # symlink: the "content" is just the link target
77
+ if side == "new" and change.change_type is ChangeType.ADDED:
78
+ body = [line.content for line in change.added_lines()]
79
+ elif side == "old" and change.change_type is ChangeType.DELETED:
80
+ body = [line.content for line in change.removed_lines()]
81
+ else:
82
+ return None
83
+ return "\n".join(body) + ("\n" if body else "")
84
+
85
+
86
+ class ChainedReader:
87
+ def __init__(self, *readers: ContentReader) -> None:
88
+ self._readers = readers
89
+
90
+ def read(self, change: FileChange, side: Side) -> str | None:
91
+ for reader in self._readers:
92
+ value = reader.read(change, side)
93
+ if value is not None:
94
+ return value
95
+ return None
96
+
97
+
98
+ @dataclass(frozen=True, slots=True)
99
+ class ResolvedDiff:
100
+ text: str
101
+ reader: ContentReader
102
+ info: RepositoryInfo
103
+ root: Path
104
+ warnings: tuple[str, ...] = ()
105
+
106
+
107
+ def validate_request(request: ScanRequest) -> None:
108
+ for name, value in (("base", request.base), ("head", request.head)):
109
+ if value is not None and (not isinstance(value, str) or not value.strip()):
110
+ raise ScanInputError(f"{name} must be a non-empty string")
111
+ if request.diff_text is not None and (request.base or request.head or request.staged):
112
+ raise ScanInputError("a provided diff cannot be combined with base/head/staged")
113
+ if request.staged and (request.base or request.head):
114
+ raise ScanInputError("--staged cannot be combined with base/head")
115
+ if request.head and not request.base:
116
+ raise ScanInputError("head requires base")
117
+ repo = Path(os.fspath(request.repository))
118
+ if not repo.is_dir():
119
+ raise ScanInputError(f"repository path is not a directory: {repo}")
120
+
121
+
122
+ def resolve_diff(request: ScanRequest, client: GitClient) -> ResolvedDiff:
123
+ validate_request(request)
124
+ repo_dir = Path(os.fspath(request.repository)).resolve()
125
+
126
+ if request.diff_text is not None:
127
+ if len(request.diff_text.encode("utf-8", errors="replace")) > MAX_DIFF_INPUT_BYTES:
128
+ raise ScanInputError("provided diff is too large")
129
+ info = RepositoryInfo(mode=ScanMode.DIFF_INPUT, root_name=repo_dir.name)
130
+ return ResolvedDiff(request.diff_text, DiffContentReader(), info, repo_dir)
131
+
132
+ root = client.repo_root(repo_dir)
133
+ head_commit = client.head_commit(root)
134
+ branch = client.current_branch(root)
135
+ warnings: list[str] = []
136
+
137
+ if request.base is not None:
138
+ base_sha = client.resolve_commit(root, request.base)
139
+ head_sha = client.resolve_commit(root, request.head or "HEAD")
140
+ merge_base = client.merge_base(root, base_sha, head_sha)
141
+ text = client.diff_commits(root, merge_base, head_sha)
142
+ reader: ContentReader = ChainedReader(
143
+ GitContentReader(client, root, merge_base, head_sha), DiffContentReader()
144
+ )
145
+ info = RepositoryInfo(
146
+ ScanMode.RANGE, root.name, head_commit, branch, request.base, request.head or "HEAD"
147
+ )
148
+ return ResolvedDiff(text, reader, info, root, tuple(warnings))
149
+
150
+ if request.staged:
151
+ text = client.diff_staged(root)
152
+ reader = ChainedReader(GitContentReader(client, root, head_commit, ":index"), DiffContentReader())
153
+ info = RepositoryInfo(ScanMode.STAGED, root.name, head_commit, branch)
154
+ return ResolvedDiff(text, reader, info, root)
155
+
156
+ text = client.diff_worktree(root)
157
+ if request.include_untracked:
158
+ untracked = client.untracked_files(root)
159
+ if len(untracked) > MAX_UNTRACKED_FILES:
160
+ raise ScanInputError(
161
+ f"{len(untracked)} untracked files found (limit {MAX_UNTRACKED_FILES}); "
162
+ "add generated files to .gitignore or scan with --no-untracked"
163
+ )
164
+ chunks = [text] if text and text.endswith("\n") else ([text + "\n"] if text else [])
165
+ for rel in untracked:
166
+ chunks.append(client.diff_untracked(root, rel))
167
+ text = "".join(chunks)
168
+ reader = ChainedReader(GitContentReader(client, root, head_commit, ":worktree"), DiffContentReader())
169
+ info = RepositoryInfo(ScanMode.WORKTREE, root.name, head_commit, branch)
170
+ return ResolvedDiff(text, reader, info, root, tuple(warnings))
171
+
172
+
173
+ def parse_resolved(resolved: ResolvedDiff) -> DiffDocument:
174
+ return parse_diff(resolved.text)
File without changes