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,75 @@
1
+ """Load policy YAML from disk using safe, duplicate-key-rejecting parsing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Collection
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import yaml
11
+
12
+ from diffguard.core.exceptions import PolicyError
13
+ from diffguard.core.models import Policy
14
+ from diffguard.policies.schema import parse_policy
15
+
16
+ DEFAULT_POLICY_FILENAME = ".diffguard.yml"
17
+ MAX_POLICY_BYTES = 256 * 1024
18
+
19
+
20
+ class _StrictLoader(yaml.SafeLoader):
21
+ """SafeLoader that rejects duplicate mapping keys instead of keeping the last."""
22
+
23
+ def construct_mapping(self, node: yaml.MappingNode, deep: bool = False) -> dict[Any, Any]:
24
+ seen: set[Any] = set()
25
+ for key_node, _ in node.value:
26
+ key = self.construct_object(key_node, deep=True)
27
+ try:
28
+ duplicate = key in seen
29
+ except TypeError:
30
+ continue
31
+ if duplicate:
32
+ raise yaml.constructor.ConstructorError(
33
+ None, None, f"duplicate key {key!r}", key_node.start_mark
34
+ )
35
+ seen.add(key)
36
+ return super().construct_mapping(node, deep)
37
+
38
+
39
+ def parse_yaml(text: str, *, source: str = "policy") -> object:
40
+ try:
41
+ return yaml.load(text, Loader=_StrictLoader) # noqa: S506 - SafeLoader subclass
42
+ except yaml.YAMLError as exc:
43
+ mark = getattr(exc, "problem_mark", None)
44
+ where = f" at line {mark.line + 1}, column {mark.column + 1}" if mark else ""
45
+ problem = getattr(exc, "problem", None) or str(exc)
46
+ raise PolicyError(f"{source}: invalid YAML{where}: {problem}") from exc
47
+
48
+
49
+ def read_text_file(path: Path, *, what: str) -> str:
50
+ try:
51
+ size = path.stat().st_size
52
+ except OSError as exc:
53
+ raise PolicyError(f"cannot read {what} {path}: {exc.strerror or exc}") from exc
54
+ if size > MAX_POLICY_BYTES:
55
+ raise PolicyError(f"{what} {path} is larger than {MAX_POLICY_BYTES // 1024} KiB")
56
+ try:
57
+ return path.read_text(encoding="utf-8")
58
+ except (OSError, UnicodeDecodeError) as exc:
59
+ raise PolicyError(f"cannot read {what} {path}: {exc}") from exc
60
+
61
+
62
+ def load_policy(
63
+ path: str | os.PathLike[str],
64
+ *,
65
+ rule_names: Collection[str],
66
+ check_ids: Collection[str],
67
+ ) -> Policy:
68
+ """Load and validate the policy at ``path``."""
69
+ file = Path(path)
70
+ text = read_text_file(file, what="policy file")
71
+ data = parse_yaml(text, source=str(file))
72
+ try:
73
+ return parse_policy(data, rule_names=rule_names, check_ids=check_ids, source=str(file))
74
+ except PolicyError as exc:
75
+ raise PolicyError([f"{file}: {e}" for e in exc.errors]) from exc
@@ -0,0 +1,292 @@
1
+ """Policy schema validation: turns parsed YAML into an immutable :class:`Policy`.
2
+
3
+ All validation errors are collected and reported together. Nothing invalid is
4
+ silently ignored: unknown keys, wrong types, unsupported versions and conflicting
5
+ settings are all errors.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import difflib
11
+ from collections.abc import Collection, Mapping
12
+ from datetime import date, datetime
13
+ from typing import Any
14
+
15
+ from diffguard.core.enums import Severity
16
+ from diffguard.core.exceptions import PatternError, PolicyError
17
+ from diffguard.core.models import Policy, RuleConfig, SuppressionRule, TaskContext
18
+ from diffguard.utils.paths import compile_pattern, normalize_pattern
19
+
20
+ SUPPORTED_VERSIONS = (1,)
21
+ _TOP_KEYS = {"version", "task", "rules", "enforcement", "exclude_paths", "suppressions",
22
+ "baseline", "settings"} # fmt: skip
23
+ _TASK_KEYS = {"id", "description", "allowed_paths", "protected_paths", "max_changed_lines"}
24
+ _RULE_KEYS = {"enabled", "severity", "options"}
25
+ _SUPPRESSION_KEYS = {"rule", "path", "fingerprint", "reason", "expires"}
26
+
27
+
28
+ class _Collector:
29
+ def __init__(self) -> None:
30
+ self.errors: list[str] = []
31
+
32
+ def add(self, where: str, message: str) -> None:
33
+ self.errors.append(f"{where}: {message}")
34
+
35
+
36
+ def _suggest(name: str, choices: Collection[str]) -> str:
37
+ close = difflib.get_close_matches(name, list(choices), n=1)
38
+ return f" (did you mean '{close[0]}'?)" if close else ""
39
+
40
+
41
+ def _mapping(value: object, where: str, c: _Collector) -> Mapping[str, Any] | None:
42
+ if not isinstance(value, Mapping):
43
+ c.add(where, f"must be a mapping, got {type(value).__name__}")
44
+ return None
45
+ bad = [k for k in value if not isinstance(k, str)]
46
+ if bad:
47
+ c.add(where, f"keys must be strings, got {bad[0]!r}")
48
+ return None
49
+ return value
50
+
51
+
52
+ def _check_unknown(data: Mapping[str, Any], allowed: Collection[str], where: str, c: _Collector) -> None:
53
+ for key in data:
54
+ if key not in allowed:
55
+ prefix = f"{where}." if where else ""
56
+ c.add(f"{prefix}{key}", f"unknown key{_suggest(key, allowed)}")
57
+
58
+
59
+ def _patterns(value: object, where: str, c: _Collector) -> tuple[str, ...]:
60
+ if value is None:
61
+ return ()
62
+ if not isinstance(value, list):
63
+ c.add(where, "must be a list of glob patterns")
64
+ return ()
65
+ out: list[str] = []
66
+ for index, item in enumerate(value):
67
+ try:
68
+ pattern = normalize_pattern(item)
69
+ compile_pattern(pattern)
70
+ except PatternError as exc:
71
+ c.add(f"{where}[{index}]", str(exc))
72
+ continue
73
+ if pattern not in out:
74
+ out.append(pattern)
75
+ return tuple(out)
76
+
77
+
78
+ def _optional_str(value: object, where: str, c: _Collector) -> str | None:
79
+ if value is None:
80
+ return None
81
+ if not isinstance(value, str):
82
+ c.add(where, f"must be a string, got {type(value).__name__}")
83
+ return None
84
+ return value
85
+
86
+
87
+ def _parse_task(value: object, c: _Collector) -> TaskContext:
88
+ if value is None:
89
+ return TaskContext()
90
+ data = _mapping(value, "task", c)
91
+ if data is None:
92
+ return TaskContext()
93
+ _check_unknown(data, _TASK_KEYS, "task", c)
94
+ allowed = _patterns(data.get("allowed_paths"), "task.allowed_paths", c)
95
+ protected = _patterns(data.get("protected_paths"), "task.protected_paths", c)
96
+ for pattern in sorted(set(allowed) & set(protected)):
97
+ c.add("task", f"pattern {pattern!r} is both allowed and protected (protected always wins)")
98
+ limit = data.get("max_changed_lines")
99
+ if limit is not None and (not isinstance(limit, int) or isinstance(limit, bool) or limit < 1):
100
+ c.add("task.max_changed_lines", "must be a positive integer")
101
+ limit = None
102
+ return TaskContext(
103
+ id=_optional_str(data.get("id"), "task.id", c),
104
+ description=_optional_str(data.get("description"), "task.description", c),
105
+ allowed_paths=allowed,
106
+ protected_paths=protected,
107
+ max_changed_lines=limit,
108
+ )
109
+
110
+
111
+ def _parse_rules(value: object, rule_names: Collection[str], c: _Collector) -> dict[str, RuleConfig]:
112
+ if value is None:
113
+ return {}
114
+ data = _mapping(value, "rules", c)
115
+ if data is None:
116
+ return {}
117
+ rules: dict[str, RuleConfig] = {}
118
+ for name, raw in data.items():
119
+ where = f"rules.{name}"
120
+ if name not in rule_names:
121
+ c.add(
122
+ where,
123
+ f"unknown rule{_suggest(name, rule_names)}; known rules: " + ", ".join(sorted(rule_names)),
124
+ )
125
+ continue
126
+ cfg = _mapping(raw, where, c)
127
+ if cfg is None:
128
+ continue
129
+ _check_unknown(cfg, _RULE_KEYS, where, c)
130
+ enabled = cfg.get("enabled", True)
131
+ if not isinstance(enabled, bool):
132
+ c.add(f"{where}.enabled", "must be true or false")
133
+ enabled = True
134
+ severity: Severity | None = None
135
+ if "severity" in cfg:
136
+ try:
137
+ severity = Severity.parse(cfg["severity"])
138
+ except ValueError as exc:
139
+ c.add(f"{where}.severity", str(exc))
140
+ options = cfg.get("options", {})
141
+ if options is None:
142
+ options = {}
143
+ opts = _mapping(options, f"{where}.options", c)
144
+ rules[name] = RuleConfig(enabled=enabled, severity=severity, options=dict(opts or {}))
145
+ return rules
146
+
147
+
148
+ def _parse_enforcement(value: object, c: _Collector) -> frozenset[Severity]:
149
+ default = frozenset({Severity.ERROR})
150
+ if value is None:
151
+ return default
152
+ data = _mapping(value, "enforcement", c)
153
+ if data is None:
154
+ return default
155
+ _check_unknown(data, {"fail_on"}, "enforcement", c)
156
+ if "fail_on" not in data:
157
+ return default
158
+ raw = data["fail_on"]
159
+ if not isinstance(raw, list):
160
+ c.add("enforcement.fail_on", "must be a list of severities")
161
+ return default
162
+ result: set[Severity] = set()
163
+ for index, item in enumerate(raw):
164
+ try:
165
+ result.add(Severity.parse(item))
166
+ except ValueError as exc:
167
+ c.add(f"enforcement.fail_on[{index}]", str(exc))
168
+ if Severity.WARNING in result and Severity.ERROR not in result:
169
+ c.add("enforcement.fail_on", "failing on 'warning' but not 'error' is contradictory")
170
+ if Severity.INFO in result and not {Severity.WARNING, Severity.ERROR} <= result:
171
+ c.add("enforcement.fail_on", "failing on 'info' requires 'warning' and 'error' too")
172
+ return frozenset(result)
173
+
174
+
175
+ def _parse_expiry(value: object, where: str, c: _Collector) -> date | None:
176
+ if value is None:
177
+ return None
178
+ if isinstance(value, datetime):
179
+ return value.date()
180
+ if isinstance(value, date):
181
+ return value
182
+ if isinstance(value, str):
183
+ try:
184
+ return date.fromisoformat(value)
185
+ except ValueError:
186
+ pass
187
+ c.add(where, "must be an ISO date (YYYY-MM-DD)")
188
+ return None
189
+
190
+
191
+ def _parse_suppressions(
192
+ value: object, rule_names: Collection[str], check_ids: Collection[str], c: _Collector
193
+ ) -> tuple[SuppressionRule, ...]:
194
+ if value is None:
195
+ return ()
196
+ if not isinstance(value, list):
197
+ c.add("suppressions", "must be a list")
198
+ return ()
199
+ out: list[SuppressionRule] = []
200
+ known = set(rule_names) | set(check_ids)
201
+ for index, raw in enumerate(value):
202
+ where = f"suppressions[{index}]"
203
+ data = _mapping(raw, where, c)
204
+ if data is None:
205
+ continue
206
+ _check_unknown(data, _SUPPRESSION_KEYS, where, c)
207
+ rule = data.get("rule")
208
+ if not isinstance(rule, str) or rule not in known:
209
+ c.add(f"{where}.rule", f"must be a rule name or check ID, got {rule!r}")
210
+ continue
211
+ reason = data.get("reason")
212
+ if not isinstance(reason, str) or not reason.strip():
213
+ c.add(f"{where}.reason", "is required and must be a non-empty string")
214
+ continue
215
+ paths = _patterns([data["path"]] if "path" in data else None, f"{where}.path", c)
216
+ fingerprint = _optional_str(data.get("fingerprint"), f"{where}.fingerprint", c)
217
+ if not paths and not fingerprint:
218
+ c.add(where, "needs 'path' or 'fingerprint' (use rules.<name>.enabled to disable a rule)")
219
+ continue
220
+ out.append(
221
+ SuppressionRule(
222
+ rule=rule,
223
+ reason=reason.strip(),
224
+ path=paths[0] if paths else None,
225
+ fingerprint=fingerprint,
226
+ expires=_parse_expiry(data.get("expires"), f"{where}.expires", c),
227
+ )
228
+ )
229
+ return tuple(out)
230
+
231
+
232
+ def parse_policy(
233
+ data: object,
234
+ *,
235
+ rule_names: Collection[str],
236
+ check_ids: Collection[str],
237
+ source: str | None = None,
238
+ ) -> Policy:
239
+ """Validate ``data`` and build a :class:`Policy`; raises :class:`PolicyError`."""
240
+ c = _Collector()
241
+ if data is None:
242
+ raise PolicyError("policy is empty; at least 'version: 1' is required")
243
+ root = _mapping(data, "policy", c)
244
+ if root is None:
245
+ raise PolicyError(c.errors)
246
+ _check_unknown(root, _TOP_KEYS, "", c)
247
+
248
+ version = root.get("version")
249
+ if version is None:
250
+ c.add("version", "is required (supported: " + ", ".join(map(str, SUPPORTED_VERSIONS)) + ")")
251
+ elif isinstance(version, bool) or version not in SUPPORTED_VERSIONS:
252
+ c.add(
253
+ "version",
254
+ f"unsupported policy version {version!r} (supported: {', '.join(map(str, SUPPORTED_VERSIONS))})",
255
+ )
256
+
257
+ task = _parse_task(root.get("task"), c)
258
+ rules = _parse_rules(root.get("rules"), rule_names, c)
259
+ fail_on = _parse_enforcement(root.get("enforcement"), c)
260
+ exclude = _patterns(root.get("exclude_paths"), "exclude_paths", c)
261
+ suppressions = _parse_suppressions(root.get("suppressions"), rule_names, check_ids, c)
262
+
263
+ baseline_path: str | None = None
264
+ if root.get("baseline") is not None:
265
+ baseline = _mapping(root["baseline"], "baseline", c)
266
+ if baseline is not None:
267
+ _check_unknown(baseline, {"path"}, "baseline", c)
268
+ baseline_path = _optional_str(baseline.get("path"), "baseline.path", c)
269
+ allow_inline = False
270
+ if root.get("settings") is not None:
271
+ settings = _mapping(root["settings"], "settings", c)
272
+ if settings is not None:
273
+ _check_unknown(settings, {"allow_inline_suppressions"}, "settings", c)
274
+ flag = settings.get("allow_inline_suppressions", False)
275
+ if isinstance(flag, bool):
276
+ allow_inline = flag
277
+ else:
278
+ c.add("settings.allow_inline_suppressions", "must be true or false")
279
+
280
+ if c.errors:
281
+ raise PolicyError(c.errors)
282
+ return Policy(
283
+ version=1,
284
+ task=task,
285
+ rules=rules,
286
+ fail_on=fail_on,
287
+ exclude_paths=exclude,
288
+ suppressions=suppressions,
289
+ baseline_path=baseline_path,
290
+ allow_inline_suppressions=allow_inline,
291
+ source_path=source,
292
+ )
diffguard/py.typed ADDED
File without changes
File without changes
@@ -0,0 +1,104 @@
1
+ """Versioned, machine-readable JSON report (schema: schemas/report-v1.schema.json)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from diffguard.core.enums import FindingStatus, Severity
9
+ from diffguard.core.models import Finding, ScanResult
10
+
11
+ REPORT_SCHEMA_VERSION = "1.0"
12
+
13
+
14
+ def _finding_dict(f: Finding) -> dict[str, Any]:
15
+ return {
16
+ "rule_id": f.rule_id,
17
+ "rule": f.rule_name,
18
+ "severity": f.severity.value,
19
+ "category": f.category.value,
20
+ "message": f.message,
21
+ "file": f.file_path,
22
+ "line": f.line,
23
+ "line_side": f.line_side if f.line is not None else None,
24
+ "evidence": f.evidence,
25
+ "explanation": f.explanation,
26
+ "remediation": f.remediation,
27
+ "confidence": f.confidence.value if f.confidence else None,
28
+ "fingerprint": f.fingerprint,
29
+ "status": f.status.value,
30
+ "suppression": (
31
+ {"source": f.suppression.source, "reason": f.suppression.reason} if f.suppression else None
32
+ ),
33
+ }
34
+
35
+
36
+ def result_to_dict(result: ScanResult) -> dict[str, Any]:
37
+ active = result.active_findings
38
+ repo = result.repository
39
+ return {
40
+ "schema_version": REPORT_SCHEMA_VERSION,
41
+ "tool": {"name": "diffguard", "version": result.scanner_version},
42
+ "scan": {
43
+ "timestamp": result.timestamp.isoformat().replace("+00:00", "Z"),
44
+ "status": result.status.value,
45
+ "mode": repo.mode.value,
46
+ "repository": {
47
+ "name": repo.root_name,
48
+ "branch": repo.branch,
49
+ "head_commit": repo.head_commit,
50
+ "base": repo.base,
51
+ "head": repo.head,
52
+ },
53
+ "policy": {
54
+ "version": result.policy_version,
55
+ "source": result.policy_source,
56
+ "task_id": result.task_id,
57
+ },
58
+ },
59
+ "decision": {
60
+ "outcome": result.decision.outcome.value,
61
+ "exit_code": int(result.exit_code),
62
+ "blocking_findings": result.decision.blocking_findings,
63
+ "fail_on": [s.value for s in result.decision.fail_on],
64
+ "reason": result.decision.reason,
65
+ },
66
+ "summary": {
67
+ "files_changed": result.stats.files_changed,
68
+ "lines_added": result.stats.lines_added,
69
+ "lines_removed": result.stats.lines_removed,
70
+ "files_excluded": result.stats.files_excluded,
71
+ "binary_files": result.stats.binary_files,
72
+ "findings": {
73
+ "total": len(result.findings),
74
+ "active": len(active),
75
+ "suppressed": len(result.findings_with_status(FindingStatus.SUPPRESSED)),
76
+ "baselined": len(result.findings_with_status(FindingStatus.BASELINED)),
77
+ "by_severity": {
78
+ s.value: sum(1 for f in active if f.severity is s)
79
+ for s in (Severity.ERROR, Severity.WARNING, Severity.INFO)
80
+ },
81
+ },
82
+ },
83
+ "findings": [_finding_dict(f) for f in result.findings],
84
+ "rules": [
85
+ {
86
+ "name": r.name,
87
+ "description": r.description,
88
+ "category": r.category.value,
89
+ "enabled": r.enabled,
90
+ "severity": r.severity.value,
91
+ "checks": dict(r.checks),
92
+ }
93
+ for r in result.rules
94
+ ],
95
+ "execution_errors": [
96
+ {"source": e.source, "error_type": e.error_type, "message": e.message}
97
+ for e in result.execution_errors
98
+ ],
99
+ "warnings": list(result.warnings),
100
+ }
101
+
102
+
103
+ def render_json(result: ScanResult, *, indent: int | None = 2) -> str:
104
+ return json.dumps(result_to_dict(result), indent=indent, ensure_ascii=False) + "\n"
@@ -0,0 +1,96 @@
1
+ """Markdown report suitable for pull-request comments and job summaries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from diffguard.core.enums import Decision, FindingStatus, Severity
6
+ from diffguard.core.models import Finding, ScanResult
7
+
8
+ _TITLES = {
9
+ Decision.PASS: "PASS",
10
+ Decision.WARN: "PASS with warnings",
11
+ Decision.FAIL: "FAIL",
12
+ Decision.ERROR: "ERROR (scan incomplete)",
13
+ }
14
+
15
+
16
+ def _code(text: str) -> str:
17
+ longest = max((len(run) for run in text.split("`")[1::2]), default=0)
18
+ fence = "`" * (longest + 1 if "`" in text else 1)
19
+ pad = " " if text.startswith("`") or text.endswith("`") else ""
20
+ return f"{fence}{pad}{text}{pad}{fence}"
21
+
22
+
23
+ def _location(f: Finding) -> str:
24
+ if f.file_path is None:
25
+ return "(repository-wide)"
26
+ where = f.file_path + (f":{f.line}" if f.line is not None else "")
27
+ return _code(where) + (" (old side)" if f.line is not None and f.line_side == "old" else "")
28
+
29
+
30
+ def _finding_block(f: Finding) -> list[str]:
31
+ lines = [f"- **{f.rule_id}** {_location(f)} - {f.message}"]
32
+ if f.evidence:
33
+ lines.append(f" - Evidence: {_code(f.evidence)}")
34
+ lines.append(f" - Why it matters: {f.explanation}")
35
+ lines.append(f" - How to fix: {f.remediation}")
36
+ return lines
37
+
38
+
39
+ def render_markdown(result: ScanResult) -> str:
40
+ d = result.decision
41
+ out: list[str] = [f"## diffguard: {_TITLES[d.outcome]}", ""]
42
+ out.append(f"{d.reason}.")
43
+ out.append("")
44
+ s = result.stats
45
+ out.append(
46
+ f"**Scanned:** {s.files_changed} file(s), +{s.lines_added} / -{s.lines_removed} lines"
47
+ + (f", {s.files_excluded} excluded" if s.files_excluded else "")
48
+ + (f", {s.binary_files} binary (contents not inspected)" if s.binary_files else "")
49
+ )
50
+ meta = [f"mode `{result.repository.mode.value}`", f"diffguard {result.scanner_version}"]
51
+ if result.task_id:
52
+ meta.insert(0, f"task `{result.task_id}`")
53
+ out.append("**Details:** " + ", ".join(meta))
54
+ out.append("")
55
+
56
+ active = result.active_findings
57
+ if active:
58
+ out.append("| Severity | Count |")
59
+ out.append("|---|---|")
60
+ for sev in (Severity.ERROR, Severity.WARNING, Severity.INFO):
61
+ count = sum(1 for f in active if f.severity is sev)
62
+ if count:
63
+ out.append(f"| {sev.value} | {count} |")
64
+ out.append("")
65
+ for sev in (Severity.ERROR, Severity.WARNING, Severity.INFO):
66
+ group = [f for f in active if f.severity is sev]
67
+ if group:
68
+ out.append(f"### {sev.value.capitalize()} ({len(group)})")
69
+ out.append("")
70
+ for f in group:
71
+ out.extend(_finding_block(f))
72
+ out.append("")
73
+ else:
74
+ out.append("No active findings.")
75
+ out.append("")
76
+
77
+ suppressed = result.findings_with_status(FindingStatus.SUPPRESSED)
78
+ baselined = result.findings_with_status(FindingStatus.BASELINED)
79
+ if suppressed or baselined:
80
+ out.append(f"_{len(suppressed)} suppressed and {len(baselined)} baselined finding(s) not counted._")
81
+ for f in suppressed:
82
+ reason = f.suppression.reason if f.suppression and f.suppression.reason else "no reason given"
83
+ out.append(f"- suppressed {f.rule_id} {_location(f)} ({reason})")
84
+ out.append("")
85
+ if result.execution_errors:
86
+ out.append("### Execution errors")
87
+ out.append("")
88
+ for e in result.execution_errors:
89
+ out.append(f"- `{e.source}` failed with {e.error_type}: {e.message}")
90
+ out.append("")
91
+ if result.warnings:
92
+ out.append("### Warnings")
93
+ out.append("")
94
+ out.extend(f"- {w}" for w in result.warnings)
95
+ out.append("")
96
+ return "\n".join(out).rstrip() + "\n"
@@ -0,0 +1,43 @@
1
+ """Plain-text console report (ASCII only so it renders on any terminal)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from diffguard.core.enums import FindingStatus, Severity
6
+ from diffguard.core.models import ScanResult
7
+
8
+
9
+ def render_text(result: ScanResult) -> str:
10
+ d = result.decision
11
+ s = result.stats
12
+ out = [
13
+ f"diffguard {result.scanner_version} - {d.outcome.value.upper()} "
14
+ f"(exit {int(result.exit_code)}): {d.reason}",
15
+ f"scanned {s.files_changed} file(s), +{s.lines_added} -{s.lines_removed} lines"
16
+ + (f", {s.files_excluded} excluded" if s.files_excluded else "")
17
+ + (f", {s.binary_files} binary not inspected" if s.binary_files else ""),
18
+ ]
19
+ if result.task_id:
20
+ out.append(f"task: {result.task_id}")
21
+ out.append("")
22
+ for f in result.active_findings:
23
+ where = f.file_path or "-"
24
+ if f.file_path and f.line is not None:
25
+ where += f":{f.line}" + (" (old)" if f.line_side == "old" else "")
26
+ out.append(f"{f.severity.value.upper():7} {f.rule_id} {where}")
27
+ out.append(f" {f.message}")
28
+ if f.evidence:
29
+ out.append(f" evidence: {f.evidence}")
30
+ out.append(f" why: {f.explanation}")
31
+ out.append(f" fix: {f.remediation}")
32
+ counts = {sev: sum(1 for f in result.active_findings if f.severity is sev) for sev in Severity}
33
+ out.append(
34
+ f"summary: {counts[Severity.ERROR]} error, {counts[Severity.WARNING]} warning, "
35
+ f"{counts[Severity.INFO]} info; "
36
+ f"{len(result.findings_with_status(FindingStatus.SUPPRESSED))} suppressed, "
37
+ f"{len(result.findings_with_status(FindingStatus.BASELINED))} baselined"
38
+ )
39
+ for e in result.execution_errors:
40
+ out.append(f"execution error in {e.source}: {e.error_type}: {e.message}")
41
+ for w in result.warnings:
42
+ out.append(f"warning: {w}")
43
+ return "\n".join(out) + "\n"
File without changes