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
diffguard/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """diffguard - guard every AI-generated diff before it reaches a human.
2
+
3
+ Public API::
4
+
5
+ from diffguard import Scanner, ScanRequest
6
+
7
+ scanner = Scanner.from_config(".diffguard.yml")
8
+ result = scanner.scan(ScanRequest(repository=".", base="main", head="HEAD"))
9
+ print(result.decision.outcome, int(result.exit_code))
10
+ """
11
+
12
+ from diffguard.core.enums import Decision, ExitCode, FindingStatus, ScanStatus, Severity
13
+ from diffguard.core.exceptions import (
14
+ DiffGuardError,
15
+ DiffParseError,
16
+ PolicyError,
17
+ ScanInputError,
18
+ )
19
+ from diffguard.core.models import Finding, Policy, ScanRequest, ScanResult
20
+ from diffguard.engine.scanner import Scanner
21
+ from diffguard.version import __version__
22
+
23
+ __all__ = [
24
+ "Decision",
25
+ "DiffGuardError",
26
+ "DiffParseError",
27
+ "ExitCode",
28
+ "Finding",
29
+ "FindingStatus",
30
+ "Policy",
31
+ "PolicyError",
32
+ "ScanInputError",
33
+ "ScanRequest",
34
+ "ScanResult",
35
+ "ScanStatus",
36
+ "Scanner",
37
+ "Severity",
38
+ "__version__",
39
+ ]
diffguard/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from diffguard.cli.main import app
2
+
3
+ if __name__ == "__main__":
4
+ app()
File without changes
@@ -0,0 +1,97 @@
1
+ """Baselines: findings accepted as pre-existing, matched by stable fingerprint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import json
7
+ from collections.abc import Iterable, Mapping
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+
11
+ from diffguard.core.enums import FindingStatus
12
+ from diffguard.core.exceptions import PolicyError
13
+ from diffguard.core.models import Finding
14
+
15
+ BASELINE_VERSION = 1
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class BaselineEntry:
20
+ fingerprint: str
21
+ rule_id: str
22
+ file_path: str | None
23
+ message: str
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class Baseline:
28
+ entries: Mapping[str, BaselineEntry] = field(default_factory=dict)
29
+
30
+ def __contains__(self, fingerprint: object) -> bool:
31
+ return fingerprint in self.entries
32
+
33
+ def __len__(self) -> int:
34
+ return len(self.entries)
35
+
36
+
37
+ def load_baseline(path: str | Path) -> Baseline:
38
+ file = Path(path)
39
+ try:
40
+ data = json.loads(file.read_text(encoding="utf-8"))
41
+ except OSError as exc:
42
+ raise PolicyError(f"cannot read baseline {file}: {exc.strerror or exc}") from exc
43
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
44
+ raise PolicyError(f"baseline {file} is not valid JSON: {exc}") from exc
45
+ if not isinstance(data, dict) or data.get("version") != BASELINE_VERSION:
46
+ raise PolicyError(f"baseline {file}: unsupported or missing version (expected {BASELINE_VERSION})")
47
+ items = data.get("findings")
48
+ if not isinstance(items, list):
49
+ raise PolicyError(f"baseline {file}: 'findings' must be a list")
50
+ entries: dict[str, BaselineEntry] = {}
51
+ for index, item in enumerate(items):
52
+ if not isinstance(item, dict) or not isinstance(item.get("fingerprint"), str):
53
+ raise PolicyError(f"baseline {file}: findings[{index}] needs a string 'fingerprint'")
54
+ fp = item["fingerprint"]
55
+ entries[fp] = BaselineEntry(
56
+ fingerprint=fp,
57
+ rule_id=str(item.get("rule_id", "")),
58
+ file_path=item.get("file_path") if isinstance(item.get("file_path"), str) else None,
59
+ message=str(item.get("message", "")),
60
+ )
61
+ return Baseline(entries)
62
+
63
+
64
+ def write_baseline(path: str | Path, findings: Iterable[Finding]) -> int:
65
+ """Write a baseline for ``findings`` (suppressed findings are excluded). Returns the count."""
66
+ unique: dict[str, Finding] = {}
67
+ for finding in findings:
68
+ if finding.status is FindingStatus.SUPPRESSED:
69
+ continue
70
+ unique.setdefault(finding.fingerprint, finding)
71
+ payload = {
72
+ "version": BASELINE_VERSION,
73
+ "findings": [
74
+ {
75
+ "fingerprint": f.fingerprint,
76
+ "rule_id": f.rule_id,
77
+ "file_path": f.file_path,
78
+ "message": f.message,
79
+ }
80
+ for f in sorted(unique.values(), key=lambda f: (f.file_path or "", f.rule_id, f.fingerprint))
81
+ ],
82
+ }
83
+ Path(path).write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
84
+ return len(unique)
85
+
86
+
87
+ def apply_baseline(findings: Iterable[Finding], baseline: Baseline | None) -> list[Finding]:
88
+ result: list[Finding] = []
89
+ for finding in findings:
90
+ if (
91
+ baseline is not None
92
+ and finding.status is FindingStatus.ACTIVE
93
+ and finding.fingerprint in baseline
94
+ ):
95
+ finding = dataclasses.replace(finding, status=FindingStatus.BASELINED)
96
+ result.append(finding)
97
+ return result
@@ -0,0 +1 @@
1
+ """Command-line interface for diffguard."""
diffguard/cli/main.py ADDED
@@ -0,0 +1,323 @@
1
+ """Command-line interface.
2
+
3
+ Exit codes (stable, see docs/cli.md):
4
+ 0 scan completed, no blocking findings
5
+ 1 policy violation (blocking findings)
6
+ 2 invalid configuration or input (also used by usage errors)
7
+ 3 internal/execution failure (scan incomplete, git unavailable, bug)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import dataclasses
13
+ import sys
14
+ from enum import StrEnum
15
+ from pathlib import Path
16
+ from typing import Annotated
17
+
18
+ import typer
19
+
20
+ from diffguard.baselines.manager import load_baseline, write_baseline
21
+ from diffguard.core.enums import ExitCode, FindingStatus, Severity
22
+ from diffguard.core.exceptions import DiffGuardError, PolicyError, ScanInputError
23
+ from diffguard.core.models import ScanRequest
24
+ from diffguard.engine.registry import default_registry
25
+ from diffguard.engine.scanner import Scanner
26
+ from diffguard.git.repository import MAX_DIFF_INPUT_BYTES
27
+ from diffguard.policies.loader import DEFAULT_POLICY_FILENAME, load_policy
28
+ from diffguard.reporting.json_report import render_json
29
+ from diffguard.reporting.markdown_report import render_markdown
30
+ from diffguard.reporting.text_report import render_text
31
+ from diffguard.utils.logging import configure_logging
32
+ from diffguard.version import __version__
33
+
34
+ app = typer.Typer(
35
+ name="diffguard",
36
+ help="Guard every AI-generated diff before it reaches a human.",
37
+ no_args_is_help=True,
38
+ add_completion=False,
39
+ pretty_exceptions_enable=False,
40
+ )
41
+
42
+ POLICY_TEMPLATE = """\
43
+ # diffguard policy. Docs: docs/configuration.md
44
+ version: 1
45
+
46
+ task:
47
+ id: "TASK-1"
48
+ description: "Describe what this change is allowed to do"
49
+ # Paths are relative to the repository root. '**' crosses directories;
50
+ # a pattern without '/' matches only at the root (use '**/name' for any depth).
51
+ allowed_paths:
52
+ - "src/**"
53
+ - "tests/**"
54
+ protected_paths:
55
+ - ".github/workflows/**"
56
+ - ".diffguard.yml"
57
+ max_changed_lines: 500
58
+
59
+ rules:
60
+ scope:
61
+ severity: error
62
+ secrets:
63
+ severity: error
64
+ dangerous_patterns:
65
+ severity: warning
66
+ dependency_changes:
67
+ severity: warning
68
+ test_removal:
69
+ severity: warning
70
+ config_changes:
71
+ severity: warning
72
+
73
+ enforcement:
74
+ fail_on:
75
+ - error
76
+ """
77
+
78
+
79
+ class OutputFormat(StrEnum):
80
+ TEXT = "text"
81
+ JSON = "json"
82
+ MARKDOWN = "markdown"
83
+
84
+
85
+ class FailOn(StrEnum):
86
+ INFO = "info"
87
+ WARNING = "warning"
88
+ ERROR = "error"
89
+
90
+
91
+ def _version_callback(value: bool) -> None:
92
+ if value:
93
+ typer.echo(f"diffguard {__version__}")
94
+ raise typer.Exit(0)
95
+
96
+
97
+ @app.callback()
98
+ def _main(
99
+ version: Annotated[
100
+ bool,
101
+ typer.Option(
102
+ "--version", callback=_version_callback, is_eager=True, help="Show the version and exit."
103
+ ),
104
+ ] = False,
105
+ ) -> None:
106
+ """diffguard: policy enforcement for AI-generated Git changes."""
107
+
108
+
109
+ def _fail(message: str, code: ExitCode) -> typer.Exit:
110
+ typer.echo(f"diffguard: error: {message}", err=True)
111
+ return typer.Exit(int(code))
112
+
113
+
114
+ def _handle(exc: BaseException, debug: bool) -> typer.Exit:
115
+ if isinstance(exc, PolicyError):
116
+ for error in exc.errors:
117
+ typer.echo(f"diffguard: invalid policy: {error}", err=True)
118
+ return typer.Exit(int(exc.exit_code))
119
+ if isinstance(exc, DiffGuardError):
120
+ if debug:
121
+ raise exc
122
+ return _fail(str(exc), exc.exit_code)
123
+ if debug:
124
+ raise exc
125
+ return _fail(
126
+ f"internal error ({type(exc).__name__}: {exc}); rerun with --debug for a traceback",
127
+ ExitCode.INTERNAL_ERROR,
128
+ )
129
+
130
+
131
+ def _locate_policy(policy: Path | None, repo: Path) -> tuple[Path | None, list[str]]:
132
+ if policy is not None:
133
+ return policy, []
134
+ candidate = repo / DEFAULT_POLICY_FILENAME
135
+ if candidate.is_file():
136
+ return candidate, []
137
+ return None, [
138
+ f"no {DEFAULT_POLICY_FILENAME} found in {repo}; using built-in default policy "
139
+ "(run 'diffguard init' to create one)"
140
+ ]
141
+
142
+
143
+ def _read_diff(source: str) -> str:
144
+ try:
145
+ if source == "-":
146
+ data = sys.stdin.buffer.read(MAX_DIFF_INPUT_BYTES + 1)
147
+ else:
148
+ path = Path(source)
149
+ if path.stat().st_size > MAX_DIFF_INPUT_BYTES:
150
+ raise ScanInputError(f"diff file {source} is too large")
151
+ data = path.read_bytes()
152
+ except OSError as exc:
153
+ raise ScanInputError(f"cannot read diff from {source}: {exc.strerror or exc}") from exc
154
+ if len(data) > MAX_DIFF_INPUT_BYTES:
155
+ raise ScanInputError("diff input is too large")
156
+ return data.decode("utf-8", errors="replace")
157
+
158
+
159
+ def _write(path: Path, text: str) -> None:
160
+ try:
161
+ path.write_text(text, encoding="utf-8", newline="\n")
162
+ except OSError as exc:
163
+ raise ScanInputError(f"cannot write {path}: {exc.strerror or exc}") from exc
164
+
165
+
166
+ @app.command()
167
+ def scan(
168
+ repo: Annotated[Path, typer.Option("--repo", "-C", help="Repository directory.")] = Path("."),
169
+ staged: Annotated[bool, typer.Option("--staged", help="Scan staged changes.")] = False,
170
+ base: Annotated[str | None, typer.Option("--base", help="Base revision (uses the merge base).")] = None,
171
+ head: Annotated[
172
+ str | None, typer.Option("--head", help="Head revision (default HEAD with --base).")
173
+ ] = None,
174
+ diff_file: Annotated[
175
+ str | None, typer.Option("--diff-file", help="Unified diff file, or '-' for stdin.")
176
+ ] = None,
177
+ policy: Annotated[
178
+ Path | None, typer.Option("--policy", "-p", help="Policy file (default: .diffguard.yml).")
179
+ ] = None,
180
+ fmt: Annotated[OutputFormat, typer.Option("--format", "-f", help="Output format.")] = OutputFormat.TEXT,
181
+ output: Annotated[
182
+ Path | None, typer.Option("--output", "-o", help="Write the report here instead of stdout.")
183
+ ] = None,
184
+ json_file: Annotated[
185
+ Path | None, typer.Option("--json-file", help="Also write a JSON report to this file.")
186
+ ] = None,
187
+ markdown_file: Annotated[
188
+ Path | None, typer.Option("--markdown-file", help="Also write a Markdown report to this file.")
189
+ ] = None,
190
+ rule: Annotated[
191
+ list[str] | None, typer.Option("--rule", "-r", help="Run only this rule (repeatable).")
192
+ ] = None,
193
+ baseline: Annotated[
194
+ Path | None, typer.Option("--baseline", help="Baseline file of accepted findings.")
195
+ ] = None,
196
+ write_baseline_to: Annotated[
197
+ Path | None, typer.Option("--write-baseline", help="Write current findings as a baseline and exit 0.")
198
+ ] = None,
199
+ fail_on: Annotated[
200
+ FailOn | None, typer.Option("--fail-on", help="Override: fail at this severity or above.")
201
+ ] = None,
202
+ no_untracked: Annotated[
203
+ bool, typer.Option("--no-untracked", help="Ignore untracked files in working-tree scans.")
204
+ ] = False,
205
+ verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Verbose logging.")] = False,
206
+ debug: Annotated[bool, typer.Option("--debug", help="Show tracebacks and debug logging.")] = False,
207
+ ) -> None:
208
+ """Scan Git changes against the policy."""
209
+ configure_logging(verbose=verbose, debug=debug)
210
+ try:
211
+ policy_path, warnings = _locate_policy(policy, repo)
212
+ registry = default_registry()
213
+ if policy_path is not None:
214
+ loaded = load_policy(policy_path, rule_names=registry.names, check_ids=registry.check_ids)
215
+ else:
216
+ from diffguard.core.models import Policy
217
+
218
+ loaded = Policy()
219
+ if fail_on is not None:
220
+ loaded = dataclasses.replace(loaded, fail_on=Severity.at_least(Severity(fail_on.value)))
221
+ scanner = Scanner(
222
+ loaded,
223
+ registry=registry,
224
+ only_rules=rule,
225
+ warnings=warnings,
226
+ baseline=load_baseline(baseline) if baseline else None,
227
+ )
228
+ request = ScanRequest(
229
+ repository=repo,
230
+ base=base,
231
+ head=head,
232
+ staged=staged,
233
+ diff_text=_read_diff(diff_file) if diff_file else None,
234
+ include_untracked=not no_untracked,
235
+ )
236
+ result = scanner.scan(request)
237
+
238
+ rendered = {
239
+ OutputFormat.TEXT: render_text,
240
+ OutputFormat.JSON: render_json,
241
+ OutputFormat.MARKDOWN: render_markdown,
242
+ }[fmt](result)
243
+ if output:
244
+ _write(output, rendered)
245
+ else:
246
+ sys.stdout.write(rendered)
247
+ sys.stdout.flush()
248
+ if json_file:
249
+ _write(json_file, render_json(result))
250
+ if markdown_file:
251
+ _write(markdown_file, render_markdown(result))
252
+
253
+ if write_baseline_to:
254
+ if result.execution_errors:
255
+ raise typer.Exit(int(ExitCode.INTERNAL_ERROR))
256
+ count = write_baseline(
257
+ write_baseline_to,
258
+ [f for f in result.findings if f.status is not FindingStatus.SUPPRESSED],
259
+ )
260
+ typer.echo(f"diffguard: wrote baseline with {count} finding(s) to {write_baseline_to}", err=True)
261
+ raise typer.Exit(0)
262
+ raise typer.Exit(int(result.exit_code))
263
+ except typer.Exit:
264
+ raise
265
+ except Exception as exc: # noqa: BLE001 - mapped to stable exit codes
266
+ raise _handle(exc, debug) from None
267
+
268
+
269
+ @app.command()
270
+ def init(
271
+ path: Annotated[Path, typer.Option("--path", help="Where to write the policy.")] = Path(
272
+ DEFAULT_POLICY_FILENAME
273
+ ),
274
+ force: Annotated[bool, typer.Option("--force", help="Overwrite an existing file.")] = False,
275
+ ) -> None:
276
+ """Create a starter .diffguard.yml."""
277
+ if path.exists() and not force:
278
+ raise _fail(f"{path} already exists (use --force to overwrite)", ExitCode.INVALID_INPUT)
279
+ try:
280
+ _write(path, POLICY_TEMPLATE)
281
+ except DiffGuardError as exc:
282
+ raise _fail(str(exc), exc.exit_code) from None
283
+ typer.echo(f"Created {path}")
284
+
285
+
286
+ @app.command()
287
+ def validate(
288
+ policy: Annotated[Path, typer.Option("--policy", "-p", help="Policy file to validate.")] = Path(
289
+ DEFAULT_POLICY_FILENAME
290
+ ),
291
+ debug: Annotated[bool, typer.Option("--debug")] = False,
292
+ ) -> None:
293
+ """Validate a policy file (schema, globs, rule options)."""
294
+ configure_logging(debug=debug)
295
+ try:
296
+ registry = default_registry()
297
+ loaded = load_policy(policy, rule_names=registry.names, check_ids=registry.check_ids)
298
+ Scanner(loaded, registry=registry) # validates rule options too
299
+ except Exception as exc: # noqa: BLE001
300
+ raise _handle(exc, debug) from None
301
+ typer.echo(f"{policy}: valid (policy version {loaded.version})")
302
+
303
+
304
+ @app.command()
305
+ def rules() -> None:
306
+ """List available rules and the checks (finding IDs) they can emit."""
307
+ for rule in default_registry().rules:
308
+ meta = rule.metadata
309
+ typer.echo(f"{meta.name} [{meta.category.value}, default severity: {meta.default_severity.value}]")
310
+ typer.echo(f" {meta.description}")
311
+ for check_id, title in meta.checks.items():
312
+ typer.echo(f" {check_id} {title}")
313
+ typer.echo("")
314
+
315
+
316
+ @app.command()
317
+ def version() -> None:
318
+ """Print the diffguard version."""
319
+ typer.echo(f"diffguard {__version__}")
320
+
321
+
322
+ if __name__ == "__main__":
323
+ app()
File without changes
@@ -0,0 +1,103 @@
1
+ """Enumerations shared across diffguard."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import IntEnum, StrEnum
6
+
7
+
8
+ class Severity(StrEnum):
9
+ """Finding severity, ordered INFO < WARNING < ERROR."""
10
+
11
+ INFO = "info"
12
+ WARNING = "warning"
13
+ ERROR = "error"
14
+
15
+ @property
16
+ def rank(self) -> int:
17
+ return _SEVERITY_RANK[self]
18
+
19
+ @classmethod
20
+ def parse(cls, value: object) -> Severity:
21
+ if isinstance(value, str):
22
+ try:
23
+ return cls(value.strip().lower())
24
+ except ValueError:
25
+ pass
26
+ raise ValueError(f"invalid severity {value!r}; expected one of: info, warning, error")
27
+
28
+ @classmethod
29
+ def at_least(cls, threshold: Severity) -> frozenset[Severity]:
30
+ return frozenset(s for s in cls if s.rank >= threshold.rank)
31
+
32
+
33
+ _SEVERITY_RANK: dict[Severity, int] = {
34
+ Severity.INFO: 0,
35
+ Severity.WARNING: 1,
36
+ Severity.ERROR: 2,
37
+ }
38
+
39
+
40
+ class Confidence(StrEnum):
41
+ LOW = "low"
42
+ MEDIUM = "medium"
43
+ HIGH = "high"
44
+
45
+
46
+ class Category(StrEnum):
47
+ SCOPE = "scope"
48
+ SECRETS = "secrets"
49
+ DANGEROUS_PATTERN = "dangerous-pattern"
50
+ DEPENDENCY = "dependency"
51
+ TESTING = "testing"
52
+ CONFIGURATION = "configuration"
53
+
54
+
55
+ class ChangeType(StrEnum):
56
+ ADDED = "added"
57
+ MODIFIED = "modified"
58
+ DELETED = "deleted"
59
+ RENAMED = "renamed"
60
+ COPIED = "copied"
61
+ MODE_CHANGED = "mode_changed"
62
+
63
+
64
+ class LineKind(StrEnum):
65
+ ADDED = "added"
66
+ REMOVED = "removed"
67
+ CONTEXT = "context"
68
+
69
+
70
+ class FindingStatus(StrEnum):
71
+ ACTIVE = "active"
72
+ SUPPRESSED = "suppressed"
73
+ BASELINED = "baselined"
74
+
75
+
76
+ class Decision(StrEnum):
77
+ """Overall enforcement outcome."""
78
+
79
+ PASS = "pass"
80
+ WARN = "warn"
81
+ FAIL = "fail"
82
+ ERROR = "error"
83
+
84
+
85
+ class ScanStatus(StrEnum):
86
+ COMPLETE = "complete"
87
+ INCOMPLETE = "incomplete"
88
+
89
+
90
+ class ScanMode(StrEnum):
91
+ WORKTREE = "worktree"
92
+ STAGED = "staged"
93
+ RANGE = "range"
94
+ DIFF_INPUT = "diff-input"
95
+
96
+
97
+ class ExitCode(IntEnum):
98
+ """Stable process exit codes (documented in docs/cli.md)."""
99
+
100
+ OK = 0
101
+ POLICY_VIOLATION = 1
102
+ INVALID_INPUT = 2
103
+ INTERNAL_ERROR = 3
@@ -0,0 +1,57 @@
1
+ """Exception hierarchy.
2
+
3
+ Policy violations are *findings*, never exceptions. Exceptions describe problems
4
+ with configuration, input, or execution, and each carries a stable exit code.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Sequence
10
+
11
+ from diffguard.core.enums import ExitCode
12
+
13
+
14
+ class DiffGuardError(Exception):
15
+ """Base class for all expected diffguard errors."""
16
+
17
+ exit_code: ExitCode = ExitCode.INTERNAL_ERROR
18
+
19
+
20
+ class PolicyError(DiffGuardError):
21
+ """The policy or baseline is invalid. Carries every validation error found."""
22
+
23
+ exit_code = ExitCode.INVALID_INPUT
24
+
25
+ def __init__(self, errors: Sequence[str] | str) -> None:
26
+ self.errors: tuple[str, ...] = (errors,) if isinstance(errors, str) else tuple(errors)
27
+ super().__init__("; ".join(self.errors))
28
+
29
+
30
+ class ScanInputError(DiffGuardError):
31
+ """The scan request or its inputs (revisions, repository, diff) are invalid."""
32
+
33
+ exit_code = ExitCode.INVALID_INPUT
34
+
35
+
36
+ class DiffParseError(ScanInputError):
37
+ """The unified diff is malformed or in an unsupported format."""
38
+
39
+
40
+ class GitUnavailableError(DiffGuardError):
41
+ """Git could not be executed (missing executable, timeout)."""
42
+
43
+
44
+ class GitCommandError(DiffGuardError):
45
+ """A Git command failed unexpectedly."""
46
+
47
+
48
+ class PathSafetyError(DiffGuardError):
49
+ """A path escapes the repository root or follows an unsafe symlink."""
50
+
51
+
52
+ class PatternError(ValueError):
53
+ """A glob pattern in a policy is invalid or ambiguous."""
54
+
55
+
56
+ class PluginError(DiffGuardError):
57
+ """A rule plugin could not be loaded or conflicts with an existing rule."""
@@ -0,0 +1,20 @@
1
+ """Small protocols that keep the analysis engine independent of Git."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal, Protocol
6
+
7
+ from diffguard.core.models import FileChange
8
+
9
+ Side = Literal["old", "new"]
10
+
11
+
12
+ class ContentReader(Protocol):
13
+ """Reads full file contents for the old or new side of a change.
14
+
15
+ Returns ``None`` when contents are unavailable (binary, too large, not valid
16
+ UTF-8, outside the repository, or not obtainable from the diff source).
17
+ Rules must treat ``None`` explicitly and never assume an empty file.
18
+ """
19
+
20
+ def read(self, change: FileChange, side: Side) -> str | None: ...