diff-sheriff 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.
@@ -0,0 +1,3 @@
1
+ """Diff Sheriff: a local risk summary for Git changes."""
2
+
3
+ __version__ = "0.1.0"
diff_sheriff/cli.py ADDED
@@ -0,0 +1,51 @@
1
+ """Command line entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import subprocess
8
+ import sys
9
+
10
+ from . import __version__
11
+ from .core import collect_diff, parse_diff, render_markdown, render_text
12
+
13
+
14
+ def main() -> None:
15
+ parser = argparse.ArgumentParser(
16
+ prog="diff-sheriff",
17
+ description="Get a local, explainable risk summary of your Git changes.",
18
+ epilog="Examples: diff-sheriff | diff-sheriff --staged | diff-sheriff --base origin/main --format json",
19
+ )
20
+ parser.add_argument("--base", help="Compare committed changes since a base ref (for example origin/main)")
21
+ parser.add_argument("--staged", action="store_true", help="Analyze the Git index instead of unstaged changes")
22
+ parser.add_argument("--format", choices=("text", "markdown", "json"), default="text", help="Output format")
23
+ parser.add_argument("--fail-on", type=int, metavar="SCORE", help="Exit with status 1 when risk reaches SCORE (0–100)")
24
+ parser.add_argument("--version", action="version", version=f"diff-sheriff {__version__}")
25
+ args = parser.parse_args()
26
+ if args.base and args.staged:
27
+ parser.error("--base and --staged cannot be used together")
28
+ if args.fail_on is not None and not 0 <= args.fail_on <= 100:
29
+ parser.error("--fail-on must be between 0 and 100")
30
+ try:
31
+ diff, warnings = collect_diff(base=args.base, staged=args.staged)
32
+ if args.base:
33
+ status = subprocess.run(["git", "status", "--short"], capture_output=True, text=True)
34
+ if status.stdout.strip():
35
+ warnings.append("--base compares committed refs; uncommitted working tree changes are excluded.")
36
+ report = parse_diff(diff, warnings=warnings, base=args.base)
37
+ except (RuntimeError, FileNotFoundError) as exc:
38
+ print(f"diff-sheriff: {exc}", file=sys.stderr)
39
+ raise SystemExit(2)
40
+ if args.format == "json":
41
+ print(json.dumps(report.to_dict(), indent=2))
42
+ elif args.format == "markdown":
43
+ print(render_markdown(report))
44
+ else:
45
+ print(render_text(report))
46
+ if args.fail_on is not None and report.score >= args.fail_on:
47
+ raise SystemExit(1)
48
+
49
+
50
+ if __name__ == "__main__":
51
+ main()
diff_sheriff/core.py ADDED
@@ -0,0 +1,251 @@
1
+ """Git diff collection and explainable risk heuristics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import subprocess
7
+ from dataclasses import asdict, dataclass
8
+ from pathlib import Path
9
+
10
+
11
+ @dataclass
12
+ class FileChange:
13
+ path: str
14
+ added: int = 0
15
+ removed: int = 0
16
+ binary: bool = False
17
+ reasons: list[str] | None = None
18
+
19
+ @property
20
+ def risk(self) -> int:
21
+ return min(100, sum(_reason_points(reason) for reason in (self.reasons or [])))
22
+
23
+ def to_dict(self) -> dict:
24
+ result = asdict(self)
25
+ result["risk"] = self.risk
26
+ return result
27
+
28
+
29
+ @dataclass
30
+ class Report:
31
+ files: list[FileChange]
32
+ warnings: list[str]
33
+ base: str | None = None
34
+
35
+ @property
36
+ def added(self) -> int:
37
+ return sum(item.added for item in self.files)
38
+
39
+ @property
40
+ def removed(self) -> int:
41
+ return sum(item.removed for item in self.files)
42
+
43
+ @property
44
+ def score(self) -> int:
45
+ if not self.files:
46
+ return 0
47
+ touched = self.added + self.removed
48
+ scope_points = min(20, max(0, (touched - 100) // 100) + len(self.files) // 5)
49
+ return min(100, max((item.risk for item in self.files), default=0) + scope_points)
50
+
51
+ def to_dict(self) -> dict:
52
+ return {
53
+ "base": self.base,
54
+ "summary": {"files": len(self.files), "added": self.added, "removed": self.removed, "risk": self.score},
55
+ "files": [item.to_dict() for item in self.files],
56
+ "warnings": self.warnings,
57
+ }
58
+
59
+
60
+ def _reason_points(reason: str) -> int:
61
+ if reason.startswith("Sensitive path"):
62
+ return 45
63
+ if reason.startswith("Lockfile"):
64
+ return 20
65
+ if reason.startswith("Dependency manifest"):
66
+ return 5
67
+ if reason.startswith("Large"):
68
+ return 15
69
+ if reason.startswith("Deletion"):
70
+ return 10
71
+ if reason.startswith("Infrastructure"):
72
+ return 25
73
+ return 5
74
+
75
+
76
+ def _risk_reasons(path: str, added: int, removed: int) -> list[str]:
77
+ lower = path.lower().replace("\\", "/")
78
+ name = Path(lower).name
79
+ reasons: list[str] = []
80
+ secret_names = ("id_rsa", "id_ed25519", "credentials", "secrets", "private.key")
81
+ env_file = name == ".env" or (name.startswith(".env.") and not any(word in name for word in ("example", "sample", "template")))
82
+ if env_file or any(token in name for token in secret_names) or name.endswith((".pem", ".p12", ".pfx")):
83
+ reasons.append("Sensitive path: check for credentials or private keys")
84
+ if name in {"package-lock.json", "pnpm-lock.yaml", "yarn.lock", "poetry.lock", "uv.lock", "pipfile.lock", "cargo.lock", "go.sum", "composer.lock"}:
85
+ reasons.append("Lockfile changed: review dependency updates")
86
+ elif name in {"package.json", "pyproject.toml", "requirements.txt", "cargo.toml", "go.mod", "gemfile", "composer.json"}:
87
+ reasons.append("Dependency manifest changed")
88
+ if lower.endswith(".tf") or any(part in lower for part in (".github/workflows/", "terraform", "dockerfile", "kubernetes", "k8s/")):
89
+ reasons.append("Infrastructure or CI configuration changed")
90
+ if added + removed >= 500:
91
+ reasons.append(f"Large change: {added + removed} lines touched")
92
+ if removed >= 100:
93
+ reasons.append(f"Deletion-heavy change: {removed} lines removed")
94
+ return reasons
95
+
96
+
97
+ def collect_diff(base: str | None = None, staged: bool = False) -> tuple[str, list[str]]:
98
+ inside = subprocess.run(["git", "rev-parse", "--is-inside-work-tree"], capture_output=True, text=True)
99
+ if inside.returncode or inside.stdout.strip() != "true":
100
+ raise RuntimeError("not a Git repository (run diff-sheriff inside a Git working tree)")
101
+ # Pin options that user config could change: path quoting, prefixes, external diff tools.
102
+ command = [
103
+ "git", "-c", "core.quotePath=false", "diff", "--no-ext-diff", "--no-color",
104
+ "--find-renames", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/",
105
+ ]
106
+ if staged:
107
+ command.append("--cached")
108
+ if base:
109
+ command.extend([f"{base}...HEAD", "--"])
110
+ else:
111
+ command.append("--")
112
+ result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", errors="replace")
113
+ if result.returncode:
114
+ # Keep the first line only: git can print its whole usage text on bad arguments.
115
+ message = (result.stderr.strip().splitlines() or ["git diff failed"])[0]
116
+ raise RuntimeError(message)
117
+ warnings: list[str] = []
118
+ if not base and not staged:
119
+ staged_result = subprocess.run(["git", "diff", "--cached", "--quiet"], capture_output=True)
120
+ if staged_result.returncode == 1:
121
+ warnings.append("Staged changes are excluded. Use --staged to include them.")
122
+ return result.stdout, warnings
123
+
124
+
125
+ _ESCAPES = {"a": 7, "b": 8, "t": 9, "n": 10, "v": 11, "f": 12, "r": 13, '"': 34, "\\": 92}
126
+
127
+
128
+ def _unquote(text: str) -> str:
129
+ """Decode a Git C-style quoted path ("a/citt\\303\\240"); return plain text unchanged."""
130
+ if not (len(text) >= 2 and text.startswith('"') and text.endswith('"')):
131
+ return text
132
+ raw = bytearray()
133
+ body = text[1:-1]
134
+ index = 0
135
+ while index < len(body):
136
+ char = body[index]
137
+ if char == "\\" and index + 1 < len(body):
138
+ octal = re.match(r"[0-7]{3}", body[index + 1:])
139
+ if octal:
140
+ raw.append(int(octal.group(0), 8))
141
+ index += 4
142
+ continue
143
+ raw.append(_ESCAPES.get(body[index + 1], ord(body[index + 1])))
144
+ index += 2
145
+ continue
146
+ raw.extend(char.encode("utf-8"))
147
+ index += 1
148
+ return raw.decode("utf-8", errors="replace")
149
+
150
+
151
+ def _strip_prefix(path: str, prefix: str) -> str:
152
+ # Git appends a tab to ---/+++ names that contain spaces.
153
+ path = _unquote(path.rstrip("\t"))
154
+ return path[len(prefix):] if path.startswith(prefix) else path
155
+
156
+
157
+ def _path_from_git_line(rest: str) -> str:
158
+ """Best-effort path from 'a/X b/Y' when no ---/+++ or rename header names the file."""
159
+ if rest.startswith('"'):
160
+ tokens = re.findall(r'"(?:[^"\\]|\\.)*"|\S+', rest)
161
+ return _strip_prefix(tokens[-1], "b/") if tokens else rest
162
+ # Same path on both sides (mode change, binary): "a/" + P + " b/" + P.
163
+ size = (len(rest) - 5) // 2
164
+ if size > 0 and rest[size + 2:size + 5] == " b/" and rest[2:size + 2] == rest[size + 5:]:
165
+ return rest[size + 5:]
166
+ head, sep, tail = rest.rpartition(" b/")
167
+ return tail if sep else rest
168
+
169
+
170
+ def parse_diff(diff: str, warnings: list[str] | None = None, base: str | None = None) -> Report:
171
+ files: list[FileChange] = []
172
+ current: FileChange | None = None
173
+ in_header = False
174
+ old_path: str | None = None
175
+ for line in diff.splitlines():
176
+ if line.startswith("diff --git "):
177
+ current = FileChange(path=_path_from_git_line(line[len("diff --git "):]))
178
+ files.append(current)
179
+ in_header, old_path = True, None
180
+ elif current is None:
181
+ continue
182
+ elif in_header:
183
+ # Header lines come before the first hunk; content lines like "--- x" never reach here.
184
+ if line.startswith("@@"):
185
+ in_header = False
186
+ elif line.startswith("rename to "):
187
+ current.path = _unquote(line[len("rename to "):])
188
+ elif line.startswith("--- "):
189
+ old_path = None if line == "--- /dev/null" else _strip_prefix(line[4:], "a/")
190
+ elif line.startswith("+++ "):
191
+ if line == "+++ /dev/null":
192
+ if old_path:
193
+ current.path = old_path
194
+ else:
195
+ current.path = _strip_prefix(line[4:], "b/")
196
+ elif line.startswith(("Binary files ", "GIT binary patch")):
197
+ current.binary = True
198
+ elif line.startswith("@@"):
199
+ continue
200
+ elif line.startswith("+"):
201
+ current.added += 1
202
+ elif line.startswith("-"):
203
+ current.removed += 1
204
+ for item in files:
205
+ item.reasons = _risk_reasons(item.path, item.added, item.removed)
206
+ return Report(files=files, warnings=warnings or [], base=base)
207
+
208
+
209
+ def _notes(item: FileChange) -> str:
210
+ notes = list(item.reasons or [])
211
+ if item.binary:
212
+ notes.append("binary file")
213
+ return "; ".join(notes) or "—"
214
+
215
+
216
+ def render_text(report: Report) -> str:
217
+ """Plain aligned table for terminals."""
218
+ lines = [
219
+ f"Diff Sheriff: {len(report.files)} files, +{report.added} / -{report.removed} lines, risk {report.score}/100",
220
+ ]
221
+ if not report.files:
222
+ lines.append("No changes found.")
223
+ else:
224
+ rows = [(str(item.risk), item.path, f"+{item.added}", f"-{item.removed}", _notes(item))
225
+ for item in sorted(report.files, key=lambda f: (-f.risk, f.path))]
226
+ header = ("RISK", "FILE", "ADD", "DEL", "NOTES")
227
+ widths = [max(len(row[col]) for row in [header, *rows]) for col in range(4)]
228
+ lines.append("")
229
+ for row in [header, *rows]:
230
+ cells = [row[0].rjust(widths[0]), row[1].ljust(widths[1]), row[2].rjust(widths[2]), row[3].rjust(widths[3])]
231
+ lines.append(" ".join(cells + [row[4]]).rstrip())
232
+ if report.warnings:
233
+ lines += [""] + [f"note: {warning}" for warning in report.warnings]
234
+ lines += ["", "Risk is a review hint based on transparent heuristics, not a quality or security verdict."]
235
+ return "\n".join(lines)
236
+
237
+
238
+ def render_markdown(report: Report) -> str:
239
+ summary = f"{len(report.files)} files · +{report.added} / −{report.removed} lines · risk {report.score}/100"
240
+ lines = ["# Diff Sheriff report", "", summary, ""]
241
+ if not report.files:
242
+ lines.append("No changes found.")
243
+ else:
244
+ lines += ["| Risk | File | + | − | Review notes |", "|---:|---|---:|---:|---|"]
245
+ for item in sorted(report.files, key=lambda f: (-f.risk, f.path)):
246
+ path = item.path.replace("|", "\\|")
247
+ lines.append(f"| {item.risk} | `{path}` | {item.added} | {item.removed} | {_notes(item)} |")
248
+ if report.warnings:
249
+ lines += ["", "## Notes", ""] + [f"- {warning}" for warning in report.warnings]
250
+ lines += ["", "Risk is a review hint based on transparent heuristics, not a quality or security verdict."]
251
+ return "\n".join(lines)
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.5
2
+ Name: diff-sheriff
3
+ Version: 0.1.0
4
+ Summary: A local, zero-runtime-dependency risk summary for your Git diff.
5
+ Author: Diff Sheriff contributors
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Diff Sheriff contributors
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ License-File: LICENSE
28
+ Keywords: cli,code-review,developer-tools,diff,git
29
+ Classifier: Development Status :: 3 - Alpha
30
+ Classifier: Environment :: Console
31
+ Classifier: Intended Audience :: Developers
32
+ Classifier: License :: OSI Approved :: MIT License
33
+ Classifier: Operating System :: OS Independent
34
+ Classifier: Programming Language :: Python :: 3
35
+ Classifier: Topic :: Software Development :: Quality Assurance
36
+ Requires-Python: >=3.10
37
+ Description-Content-Type: text/markdown
38
+
39
+ # Diff Sheriff 🛡️
40
+
41
+ [![CI](https://github.com/santeluca-source/diff-sheriff/actions/workflows/ci.yml/badge.svg)](https://github.com/santeluca-source/diff-sheriff/actions/workflows/ci.yml)
42
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/santeluca-source/diff-sheriff/blob/main/LICENSE)
43
+
44
+ **Know where to look before you review the diff.**
45
+
46
+ Diff Sheriff is a tiny local CLI that summarizes your Git changes, points reviewers at files that deserve a closer look, and explains every risk hint. Your code stays on your machine. No API key, account, or runtime dependency.
47
+
48
+ ![diff-sheriff run in a terminal: six changed files ranked by review risk](https://raw.githubusercontent.com/santeluca-source/diff-sheriff/main/docs/demo.svg)
49
+
50
+ Plain-text version of the same kind of report:
51
+
52
+ ```text
53
+ $ diff-sheriff
54
+ Diff Sheriff: 4 files, +86 / -12 lines, risk 45/100
55
+
56
+ RISK FILE ADD DEL NOTES
57
+ 45 .env.production +4 -0 Sensitive path: check for credentials or private keys
58
+ 20 uv.lock +18 -7 Lockfile changed: review dependency updates
59
+ 0 README.md +5 -0 —
60
+ 0 src/api.py +59 -5 —
61
+
62
+ Risk is a review hint based on transparent heuristics, not a quality or security verdict.
63
+ ```
64
+
65
+ ## Install
66
+
67
+ Requires Python 3.10+ and Git. Install from a checkout with [pipx](https://pipx.pypa.io/):
68
+
69
+ ```bash
70
+ git clone https://github.com/santeluca-source/diff-sheriff.git
71
+ cd diff-sheriff
72
+ pipx install .
73
+ ```
74
+
75
+ Or run without installing:
76
+
77
+ ```bash
78
+ python -m pip install .
79
+ ```
80
+
81
+ ## Use
82
+
83
+ ```bash
84
+ diff-sheriff # unstaged working-tree diff
85
+ diff-sheriff --staged # staged changes
86
+ diff-sheriff --base origin/main # committed changes since a ref
87
+ diff-sheriff --format json # machine-readable output
88
+ diff-sheriff --format markdown # paste into a PR description
89
+ diff-sheriff --fail-on 40 # CI gate; exits 1 at or above score
90
+ ```
91
+
92
+ `--base` compares committed changes since the ref and excludes uncommitted edits. The tool prints a note when it detects those edits. Staged changes are excluded from the default view and called out in a note.
93
+
94
+ ## Develop
95
+
96
+ ```bash
97
+ python -m pip install -e .
98
+ python -m unittest discover -s tests -v
99
+ ```
100
+
101
+ ## What the score means
102
+
103
+ The score is an explainable nudge, not an assessment of code quality. It is based on file paths and changed-line counts:
104
+
105
+ - Credential-looking filenames: **45 points** (`.env`, `.env.production`, `*.pem`, `id_rsa`, …; `.env.example`, `.env.sample` and `.env.template` are not flagged)
106
+ - CI, container, or infrastructure paths: **25 points**
107
+ - Dependency lockfiles: **20 points**
108
+ - Dependency manifests: **5 points**
109
+ - 500+ touched lines: **15 points**
110
+ - 100+ removed lines: **10 points**
111
+ - Larger diffs add a capped review-scope adjustment to the report score.
112
+
113
+ Signals can overlap. A high score means “take a closer look,” not “this change is unsafe.” No file contents are uploaded or sent anywhere. Diff Sheriff does not inspect source code for vulnerabilities, and filename heuristics can miss secrets or flag examples. Review the actual diff.
114
+
115
+ ## Why this exists
116
+
117
+ Code review is easier when reviewers know where to start. Diff Sheriff gives a lightweight map of a change before the human review begins, while keeping the analysis local and the rules visible.
118
+
119
+ ## Contributing
120
+
121
+ Issues and pull requests are welcome. Keep the tool small, offline, and explicit about why a file is flagged. Please include a short rationale for new heuristics and avoid rules that depend on a particular language or hosting service.
122
+
123
+ ## License
124
+
125
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,8 @@
1
+ diff_sheriff/__init__.py,sha256=9uxmjLp_KL25GsnRDH-9nFUqoVJ9uRVTvYOxYWZdGKo,81
2
+ diff_sheriff/cli.py,sha256=shBy8H6GcDSoCXLYQ4QqhAyiTwo-bi5NMquOsiheQbM,2230
3
+ diff_sheriff/core.py,sha256=OFYlr8u402JkQBQucqnnpaFnAqrvi5HVmTGBs2wycLk,10321
4
+ diff_sheriff-0.1.0.dist-info/METADATA,sha256=69QTf1wG2cyJNTOur_55MLuUJHB-KiC94m0YR_1VzEc,5569
5
+ diff_sheriff-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ diff_sheriff-0.1.0.dist-info/entry_points.txt,sha256=ec2_bHDuoh1pacTqNiAm0ZxOK3C0mUmfxuQLM8TvYc8,55
7
+ diff_sheriff-0.1.0.dist-info/licenses/LICENSE,sha256=KpsjNreXHmHCGNhTgdzfrqQTXH5WCkZ8uMfebES7fLk,1082
8
+ diff_sheriff-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ diff-sheriff = diff_sheriff.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Diff Sheriff contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.