diff-sheriff 0.1.0__tar.gz
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.
- diff_sheriff-0.1.0/.github/workflows/ci.yml +35 -0
- diff_sheriff-0.1.0/.github/workflows/publish.yml +45 -0
- diff_sheriff-0.1.0/.gitignore +7 -0
- diff_sheriff-0.1.0/CONTRIBUTING.md +12 -0
- diff_sheriff-0.1.0/LICENSE +21 -0
- diff_sheriff-0.1.0/PKG-INFO +125 -0
- diff_sheriff-0.1.0/README.md +87 -0
- diff_sheriff-0.1.0/docs/demo.svg +8 -0
- diff_sheriff-0.1.0/pyproject.toml +28 -0
- diff_sheriff-0.1.0/src/diff_sheriff/__init__.py +3 -0
- diff_sheriff-0.1.0/src/diff_sheriff/cli.py +51 -0
- diff_sheriff-0.1.0/src/diff_sheriff/core.py +251 -0
- diff_sheriff-0.1.0/tests/test_cli_integration.py +92 -0
- diff_sheriff-0.1.0/tests/test_core.py +110 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
test:
|
|
13
|
+
name: ${{ matrix.os }} / Python ${{ matrix.python }}
|
|
14
|
+
runs-on: ${{ matrix.os }}
|
|
15
|
+
strategy:
|
|
16
|
+
fail-fast: false
|
|
17
|
+
matrix:
|
|
18
|
+
os: [ubuntu-latest]
|
|
19
|
+
python: ["3.10", "3.11", "3.12", "3.13"]
|
|
20
|
+
include:
|
|
21
|
+
- os: windows-latest
|
|
22
|
+
python: "3.13"
|
|
23
|
+
- os: macos-latest
|
|
24
|
+
python: "3.13"
|
|
25
|
+
steps:
|
|
26
|
+
- uses: actions/checkout@v4
|
|
27
|
+
- uses: actions/setup-python@v5
|
|
28
|
+
with:
|
|
29
|
+
python-version: ${{ matrix.python }}
|
|
30
|
+
- name: Install
|
|
31
|
+
run: python -m pip install .
|
|
32
|
+
- name: Smoke test the installed command
|
|
33
|
+
run: diff-sheriff --version
|
|
34
|
+
- name: Unit and integration tests
|
|
35
|
+
run: python -m unittest discover -s tests -v
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
# Runs when a GitHub release is published. Uses PyPI Trusted Publishing (OIDC): no API token is stored.
|
|
4
|
+
on:
|
|
5
|
+
release:
|
|
6
|
+
types: [published]
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
build:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: "3.13"
|
|
19
|
+
- name: Check the tag matches the package version
|
|
20
|
+
run: |
|
|
21
|
+
version=$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
|
|
22
|
+
test "v$version" = "${GITHUB_REF_NAME}" || { echo "Tag ${GITHUB_REF_NAME} does not match version $version"; exit 1; }
|
|
23
|
+
- name: Build sdist and wheel
|
|
24
|
+
run: |
|
|
25
|
+
python -m pip install build
|
|
26
|
+
python -m build
|
|
27
|
+
- uses: actions/upload-artifact@v4
|
|
28
|
+
with:
|
|
29
|
+
name: dist
|
|
30
|
+
path: dist/
|
|
31
|
+
|
|
32
|
+
publish:
|
|
33
|
+
needs: build
|
|
34
|
+
runs-on: ubuntu-latest
|
|
35
|
+
environment:
|
|
36
|
+
name: pypi
|
|
37
|
+
url: https://pypi.org/p/diff-sheriff
|
|
38
|
+
permissions:
|
|
39
|
+
id-token: write
|
|
40
|
+
steps:
|
|
41
|
+
- uses: actions/download-artifact@v4
|
|
42
|
+
with:
|
|
43
|
+
name: dist
|
|
44
|
+
path: dist/
|
|
45
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Thanks for helping make code review calmer. Keep contributions focused and keep Diff Sheriff local, explainable, and dependency-light.
|
|
4
|
+
|
|
5
|
+
Before opening a pull request:
|
|
6
|
+
|
|
7
|
+
1. Explain the user problem and the behavior change.
|
|
8
|
+
2. Keep risk hints specific and actionable.
|
|
9
|
+
3. Update the README when changing the CLI or its heuristics.
|
|
10
|
+
4. Do not add network calls or collect repository contents.
|
|
11
|
+
|
|
12
|
+
For larger changes, open an issue first so we can agree on the shape of the feature.
|
|
@@ -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.
|
|
@@ -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
|
+
[](https://github.com/santeluca-source/diff-sheriff/actions/workflows/ci.yml)
|
|
42
|
+
[](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
|
+

|
|
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,87 @@
|
|
|
1
|
+
# Diff Sheriff 🛡️
|
|
2
|
+
|
|
3
|
+
[](https://github.com/santeluca-source/diff-sheriff/actions/workflows/ci.yml)
|
|
4
|
+
[](https://github.com/santeluca-source/diff-sheriff/blob/main/LICENSE)
|
|
5
|
+
|
|
6
|
+
**Know where to look before you review the diff.**
|
|
7
|
+
|
|
8
|
+
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.
|
|
9
|
+
|
|
10
|
+

|
|
11
|
+
|
|
12
|
+
Plain-text version of the same kind of report:
|
|
13
|
+
|
|
14
|
+
```text
|
|
15
|
+
$ diff-sheriff
|
|
16
|
+
Diff Sheriff: 4 files, +86 / -12 lines, risk 45/100
|
|
17
|
+
|
|
18
|
+
RISK FILE ADD DEL NOTES
|
|
19
|
+
45 .env.production +4 -0 Sensitive path: check for credentials or private keys
|
|
20
|
+
20 uv.lock +18 -7 Lockfile changed: review dependency updates
|
|
21
|
+
0 README.md +5 -0 —
|
|
22
|
+
0 src/api.py +59 -5 —
|
|
23
|
+
|
|
24
|
+
Risk is a review hint based on transparent heuristics, not a quality or security verdict.
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
Requires Python 3.10+ and Git. Install from a checkout with [pipx](https://pipx.pypa.io/):
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
git clone https://github.com/santeluca-source/diff-sheriff.git
|
|
33
|
+
cd diff-sheriff
|
|
34
|
+
pipx install .
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Or run without installing:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
python -m pip install .
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Use
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
diff-sheriff # unstaged working-tree diff
|
|
47
|
+
diff-sheriff --staged # staged changes
|
|
48
|
+
diff-sheriff --base origin/main # committed changes since a ref
|
|
49
|
+
diff-sheriff --format json # machine-readable output
|
|
50
|
+
diff-sheriff --format markdown # paste into a PR description
|
|
51
|
+
diff-sheriff --fail-on 40 # CI gate; exits 1 at or above score
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`--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.
|
|
55
|
+
|
|
56
|
+
## Develop
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
python -m pip install -e .
|
|
60
|
+
python -m unittest discover -s tests -v
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## What the score means
|
|
64
|
+
|
|
65
|
+
The score is an explainable nudge, not an assessment of code quality. It is based on file paths and changed-line counts:
|
|
66
|
+
|
|
67
|
+
- Credential-looking filenames: **45 points** (`.env`, `.env.production`, `*.pem`, `id_rsa`, …; `.env.example`, `.env.sample` and `.env.template` are not flagged)
|
|
68
|
+
- CI, container, or infrastructure paths: **25 points**
|
|
69
|
+
- Dependency lockfiles: **20 points**
|
|
70
|
+
- Dependency manifests: **5 points**
|
|
71
|
+
- 500+ touched lines: **15 points**
|
|
72
|
+
- 100+ removed lines: **10 points**
|
|
73
|
+
- Larger diffs add a capped review-scope adjustment to the report score.
|
|
74
|
+
|
|
75
|
+
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.
|
|
76
|
+
|
|
77
|
+
## Why this exists
|
|
78
|
+
|
|
79
|
+
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.
|
|
80
|
+
|
|
81
|
+
## Contributing
|
|
82
|
+
|
|
83
|
+
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.
|
|
84
|
+
|
|
85
|
+
## License
|
|
86
|
+
|
|
87
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="874" height="299" viewBox="0 0 874 299" role="img" aria-label="diff-sheriff terminal demo">
|
|
2
|
+
<title>diff-sheriff demo: risk summary of a Git diff</title>
|
|
3
|
+
<style>.t{font:14px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre}
|
|
4
|
+
@keyframes k1{0%,5.00%{opacity:0}5.01%,94%{opacity:1}100%{opacity:0}}.k1{animation:k1 12.0s linear infinite}@keyframes k2{0%,5.50%{opacity:0}5.51%,94%{opacity:1}100%{opacity:0}}.k2{animation:k2 12.0s linear infinite}@keyframes k3{0%,6.00%{opacity:0}6.01%,94%{opacity:1}100%{opacity:0}}.k3{animation:k3 12.0s linear infinite}@keyframes k4{0%,6.50%{opacity:0}6.51%,94%{opacity:1}100%{opacity:0}}.k4{animation:k4 12.0s linear infinite}@keyframes k5{0%,7.00%{opacity:0}7.01%,94%{opacity:1}100%{opacity:0}}.k5{animation:k5 12.0s linear infinite}@keyframes k6{0%,7.50%{opacity:0}7.51%,94%{opacity:1}100%{opacity:0}}.k6{animation:k6 12.0s linear infinite}@keyframes k7{0%,8.00%{opacity:0}8.01%,94%{opacity:1}100%{opacity:0}}.k7{animation:k7 12.0s linear infinite}@keyframes k8{0%,8.50%{opacity:0}8.51%,94%{opacity:1}100%{opacity:0}}.k8{animation:k8 12.0s linear infinite}@keyframes k9{0%,9.00%{opacity:0}9.01%,94%{opacity:1}100%{opacity:0}}.k9{animation:k9 12.0s linear infinite}@keyframes k10{0%,9.50%{opacity:0}9.51%,94%{opacity:1}100%{opacity:0}}.k10{animation:k10 12.0s linear infinite}@keyframes k11{0%,10.00%{opacity:0}10.01%,94%{opacity:1}100%{opacity:0}}.k11{animation:k11 12.0s linear infinite}@keyframes k12{0%,10.50%{opacity:0}10.51%,94%{opacity:1}100%{opacity:0}}.k12{animation:k12 12.0s linear infinite}@keyframes k13{0%,11.00%{opacity:0}11.01%,94%{opacity:1}100%{opacity:0}}.k13{animation:k13 12.0s linear infinite}@keyframes k14{0%,11.50%{opacity:0}11.51%,94%{opacity:1}100%{opacity:0}}.k14{animation:k14 12.0s linear infinite}@keyframes k15{0%,12.00%{opacity:0}12.01%,94%{opacity:1}100%{opacity:0}}.k15{animation:k15 12.0s linear infinite}@keyframes k16{0%,12.50%{opacity:0}12.51%,94%{opacity:1}100%{opacity:0}}.k16{animation:k16 12.0s linear infinite}@keyframes k17{0%,13.00%{opacity:0}13.01%,94%{opacity:1}100%{opacity:0}}.k17{animation:k17 12.0s linear infinite}@keyframes k18{0%,13.50%{opacity:0}13.51%,94%{opacity:1}100%{opacity:0}}.k18{animation:k18 12.0s linear infinite}@keyframes k19{0%,14.00%{opacity:0}14.01%,94%{opacity:1}100%{opacity:0}}.k19{animation:k19 12.0s linear infinite}@keyframes k20{0%,14.50%{opacity:0}14.51%,94%{opacity:1}100%{opacity:0}}.k20{animation:k20 12.0s linear infinite}@keyframes k21{0%,15.00%{opacity:0}15.01%,94%{opacity:1}100%{opacity:0}}.k21{animation:k21 12.0s linear infinite}@keyframes k22{0%,15.50%{opacity:0}15.51%,94%{opacity:1}100%{opacity:0}}.k22{animation:k22 12.0s linear infinite}@keyframes k23{0%,16.00%{opacity:0}16.01%,94%{opacity:1}100%{opacity:0}}.k23{animation:k23 12.0s linear infinite}@keyframes k24{0%,16.50%{opacity:0}16.51%,94%{opacity:1}100%{opacity:0}}.k24{animation:k24 12.0s linear infinite}@keyframes k25{0%,17.00%{opacity:0}17.01%,94%{opacity:1}100%{opacity:0}}.k25{animation:k25 12.0s linear infinite}@keyframes k26{0%,17.50%{opacity:0}17.51%,94%{opacity:1}100%{opacity:0}}.k26{animation:k26 12.0s linear infinite}@keyframes k27{0%,22.17%{opacity:0}22.18%,94%{opacity:1}100%{opacity:0}}.k27{animation:k27 12.0s linear infinite}@keyframes k28{0%,23.17%{opacity:0}23.18%,94%{opacity:1}100%{opacity:0}}.k28{animation:k28 12.0s linear infinite}@keyframes k29{0%,24.17%{opacity:0}24.18%,94%{opacity:1}100%{opacity:0}}.k29{animation:k29 12.0s linear infinite}@keyframes k30{0%,25.17%{opacity:0}25.18%,94%{opacity:1}100%{opacity:0}}.k30{animation:k30 12.0s linear infinite}@keyframes k31{0%,26.17%{opacity:0}26.18%,94%{opacity:1}100%{opacity:0}}.k31{animation:k31 12.0s linear infinite}@keyframes k32{0%,27.17%{opacity:0}27.18%,94%{opacity:1}100%{opacity:0}}.k32{animation:k32 12.0s linear infinite}@keyframes k33{0%,28.17%{opacity:0}28.18%,94%{opacity:1}100%{opacity:0}}.k33{animation:k33 12.0s linear infinite}@keyframes k34{0%,29.17%{opacity:0}29.18%,94%{opacity:1}100%{opacity:0}}.k34{animation:k34 12.0s linear infinite}@keyframes k35{0%,30.17%{opacity:0}30.18%,94%{opacity:1}100%{opacity:0}}.k35{animation:k35 12.0s linear infinite}@keyframes k36{0%,31.17%{opacity:0}31.18%,94%{opacity:1}100%{opacity:0}}.k36{animation:k36 12.0s linear infinite}@keyframes k37{0%,32.17%{opacity:0}32.18%,94%{opacity:1}100%{opacity:0}}.k37{animation:k37 12.0s linear infinite}</style>
|
|
5
|
+
<rect width="874" height="299" rx="10" fill="#0d1117"/>
|
|
6
|
+
<circle cx="20" cy="18" r="6" fill="#ff5f57"/><circle cx="40" cy="18" r="6" fill="#febc2e"/><circle cx="60" cy="18" r="6" fill="#28c840"/>
|
|
7
|
+
<g xml:space="preserve"><text x="20" y="48" class="t" fill="#f0f6fc"><tspan fill="#7ee787">$ </tspan><tspan class="k1">d</tspan><tspan class="k2">i</tspan><tspan class="k3">f</tspan><tspan class="k4">f</tspan><tspan class="k5">-</tspan><tspan class="k6">s</tspan><tspan class="k7">h</tspan><tspan class="k8">e</tspan><tspan class="k9">r</tspan><tspan class="k10">i</tspan><tspan class="k11">f</tspan><tspan class="k12">f</tspan><tspan class="k13"> </tspan><tspan class="k14">-</tspan><tspan class="k15">-</tspan><tspan class="k16">b</tspan><tspan class="k17">a</tspan><tspan class="k18">s</tspan><tspan class="k19">e</tspan><tspan class="k20"> </tspan><tspan class="k21">H</tspan><tspan class="k22">E</tspan><tspan class="k23">A</tspan><tspan class="k24">D</tspan><tspan class="k25">~</tspan><tspan class="k26">1</tspan></text><text x="20" y="69" class="t k27"><tspan fill="#f0f6fc" font-weight="bold">Diff Sheriff: 6 files, +97 / -15 lines, risk 46/100</tspan></text><text x="20" y="90" class="t k28"><tspan fill="#8b949e" font-style="italic"></tspan></text><text x="20" y="111" class="t k29"><tspan fill="#8b949e">RISK FILE ADD DEL NOTES</tspan></text><text x="20" y="132" class="t k30"><tspan fill="#ff7b72" font-weight="bold"> 45</tspan><tspan fill="#c9d1d9"> .env.production +2 -0 Sensitive path: check for credentials or private keys</tspan></text><text x="20" y="153" class="t k31"><tspan fill="#ffa657" font-weight="bold"> 25</tspan><tspan fill="#c9d1d9"> .github/workflows/deploy.yml +5 -2 Infrastructure or CI configuration changed</tspan></text><text x="20" y="174" class="t k32"><tspan fill="#e3b341" font-weight="bold"> 20</tspan><tspan fill="#c9d1d9"> uv.lock +18 -7 Lockfile changed: review dependency updates</tspan></text><text x="20" y="195" class="t k33"><tspan fill="#79c0ff" font-weight="bold"> 5</tspan><tspan fill="#c9d1d9"> pyproject.toml +2 -1 Dependency manifest changed</tspan></text><text x="20" y="216" class="t k34"><tspan fill="#8b949e" font-weight="bold"> 0</tspan><tspan fill="#c9d1d9"> README.md +6 -0 —</tspan></text><text x="20" y="237" class="t k35"><tspan fill="#8b949e" font-weight="bold"> 0</tspan><tspan fill="#c9d1d9"> src/api.py +64 -5 —</tspan></text><text x="20" y="258" class="t k36"><tspan fill="#8b949e" font-style="italic"></tspan></text><text x="20" y="279" class="t k37"><tspan fill="#8b949e" font-style="italic">Risk is a review hint based on transparent heuristics, not a quality or security verdict.</tspan></text></g>
|
|
8
|
+
</svg>
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "diff-sheriff"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A local, zero-runtime-dependency risk summary for your Git diff."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { file = "LICENSE" }
|
|
12
|
+
authors = [{ name = "Diff Sheriff contributors" }]
|
|
13
|
+
keywords = ["git", "code-review", "cli", "developer-tools", "diff"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Environment :: Console",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.scripts]
|
|
25
|
+
diff-sheriff = "diff_sheriff.cli:main"
|
|
26
|
+
|
|
27
|
+
[tool.hatch.build.targets.wheel]
|
|
28
|
+
packages = ["src/diff_sheriff"]
|
|
@@ -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()
|
|
@@ -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,92 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
import tempfile
|
|
6
|
+
import unittest
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def git(cwd, *args):
|
|
14
|
+
return subprocess.run(
|
|
15
|
+
["git", *args], cwd=cwd, capture_output=True, text=True, check=True
|
|
16
|
+
).stdout.strip()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CliIntegrationTests(unittest.TestCase):
|
|
20
|
+
def test_staged_changes_json_and_ci_threshold(self):
|
|
21
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
22
|
+
repo = Path(directory)
|
|
23
|
+
git(repo, "init")
|
|
24
|
+
git(repo, "config", "user.email", "test@example.invalid")
|
|
25
|
+
git(repo, "config", "user.name", "Diff Sheriff test")
|
|
26
|
+
(repo / "app.py").write_text("print('hello')\n", encoding="utf-8")
|
|
27
|
+
git(repo, "add", "app.py")
|
|
28
|
+
git(repo, "commit", "-m", "initial")
|
|
29
|
+
|
|
30
|
+
(repo / ".env").write_text("TOKEN=example-value\n", encoding="utf-8")
|
|
31
|
+
git(repo, "add", ".env")
|
|
32
|
+
env = os.environ.copy()
|
|
33
|
+
env["PYTHONPATH"] = str(ROOT / "src")
|
|
34
|
+
command = [sys.executable, "-m", "diff_sheriff.cli", "--staged", "--format", "json"]
|
|
35
|
+
result = subprocess.run(command, cwd=repo, env=env, capture_output=True, text=True)
|
|
36
|
+
self.assertEqual(result.returncode, 0, result.stderr)
|
|
37
|
+
report = json.loads(result.stdout)
|
|
38
|
+
self.assertEqual(report["summary"]["files"], 1)
|
|
39
|
+
self.assertEqual(report["files"][0]["path"], ".env")
|
|
40
|
+
self.assertEqual(report["summary"]["risk"], 45)
|
|
41
|
+
|
|
42
|
+
gated = subprocess.run(command + ["--fail-on", "40"], cwd=repo, env=env, capture_output=True, text=True)
|
|
43
|
+
self.assertEqual(gated.returncode, 1)
|
|
44
|
+
|
|
45
|
+
default = subprocess.run(
|
|
46
|
+
[sys.executable, "-m", "diff_sheriff.cli", "--format", "json"],
|
|
47
|
+
cwd=repo, env=env, capture_output=True, text=True,
|
|
48
|
+
)
|
|
49
|
+
self.assertEqual(default.returncode, 0, default.stderr)
|
|
50
|
+
self.assertEqual(json.loads(default.stdout)["summary"]["files"], 0)
|
|
51
|
+
self.assertTrue(json.loads(default.stdout)["warnings"])
|
|
52
|
+
|
|
53
|
+
def test_base_compares_committed_changes(self):
|
|
54
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
55
|
+
repo = Path(directory)
|
|
56
|
+
git(repo, "init")
|
|
57
|
+
git(repo, "config", "user.email", "test@example.invalid")
|
|
58
|
+
git(repo, "config", "user.name", "Diff Sheriff test")
|
|
59
|
+
(repo / "app.py").write_text("print('hello')\n", encoding="utf-8")
|
|
60
|
+
git(repo, "add", "app.py")
|
|
61
|
+
git(repo, "commit", "-m", "initial")
|
|
62
|
+
base = git(repo, "rev-parse", "HEAD")
|
|
63
|
+
(repo / "app.py").write_text("print('updated')\n", encoding="utf-8")
|
|
64
|
+
git(repo, "commit", "-am", "update")
|
|
65
|
+
|
|
66
|
+
env = os.environ.copy()
|
|
67
|
+
env["PYTHONPATH"] = str(ROOT / "src")
|
|
68
|
+
result = subprocess.run(
|
|
69
|
+
[sys.executable, "-m", "diff_sheriff.cli", "--base", base, "--format", "json"],
|
|
70
|
+
cwd=repo, env=env, capture_output=True, text=True,
|
|
71
|
+
)
|
|
72
|
+
self.assertEqual(result.returncode, 0, result.stderr)
|
|
73
|
+
report = json.loads(result.stdout)
|
|
74
|
+
self.assertEqual(report["summary"]["files"], 1)
|
|
75
|
+
self.assertEqual(report["files"][0]["path"], "app.py")
|
|
76
|
+
|
|
77
|
+
def test_outside_git_repository_gives_short_error(self):
|
|
78
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
79
|
+
env = os.environ.copy()
|
|
80
|
+
env["PYTHONPATH"] = str(ROOT / "src")
|
|
81
|
+
env["GIT_CEILING_DIRECTORIES"] = str(Path(directory).parent)
|
|
82
|
+
result = subprocess.run(
|
|
83
|
+
[sys.executable, "-m", "diff_sheriff.cli"],
|
|
84
|
+
cwd=directory, env=env, capture_output=True, text=True,
|
|
85
|
+
)
|
|
86
|
+
self.assertEqual(result.returncode, 2)
|
|
87
|
+
self.assertIn("not a Git repository", result.stderr)
|
|
88
|
+
self.assertLess(len(result.stderr.splitlines()), 3)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
unittest.main()
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
|
|
3
|
+
from diff_sheriff.core import parse_diff, render_text
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ParseDiffTests(unittest.TestCase):
|
|
7
|
+
def test_counts_lines_and_flags_sensitive_path(self):
|
|
8
|
+
diff = """diff --git a/.env b/.env
|
|
9
|
+
--- a/.env
|
|
10
|
+
+++ b/.env
|
|
11
|
+
@@ -0,0 +1,2 @@
|
|
12
|
+
+TOKEN=redacted
|
|
13
|
+
+MODE=dev
|
|
14
|
+
"""
|
|
15
|
+
report = parse_diff(diff)
|
|
16
|
+
self.assertEqual((report.added, report.removed), (2, 0))
|
|
17
|
+
self.assertEqual(report.files[0].risk, 45)
|
|
18
|
+
|
|
19
|
+
def test_example_env_file_is_not_flagged_as_secret(self):
|
|
20
|
+
report = parse_diff("""diff --git a/.env.example b/.env.example
|
|
21
|
+
--- a/.env.example
|
|
22
|
+
+++ b/.env.example
|
|
23
|
+
@@ -0,0 +1 @@
|
|
24
|
+
+TOKEN=replace-me
|
|
25
|
+
""")
|
|
26
|
+
self.assertEqual(report.files[0].risk, 0)
|
|
27
|
+
|
|
28
|
+
def test_dependency_manifest_and_lockfile_have_distinct_scores(self):
|
|
29
|
+
report = parse_diff("""diff --git a/pyproject.toml b/pyproject.toml
|
|
30
|
+
--- a/pyproject.toml
|
|
31
|
+
+++ b/pyproject.toml
|
|
32
|
+
@@ -1 +1 @@
|
|
33
|
+
-old
|
|
34
|
+
+new
|
|
35
|
+
diff --git a/uv.lock b/uv.lock
|
|
36
|
+
--- a/uv.lock
|
|
37
|
+
+++ b/uv.lock
|
|
38
|
+
@@ -1 +1 @@
|
|
39
|
+
-old
|
|
40
|
+
+new
|
|
41
|
+
""")
|
|
42
|
+
self.assertEqual([item.risk for item in report.files], [5, 20])
|
|
43
|
+
|
|
44
|
+
def test_terraform_file_is_flagged(self):
|
|
45
|
+
report = parse_diff("""diff --git a/main.tf b/main.tf
|
|
46
|
+
--- a/main.tf
|
|
47
|
+
+++ b/main.tf
|
|
48
|
+
@@ -0,0 +1 @@
|
|
49
|
+
+resource \"thing\" {}
|
|
50
|
+
""")
|
|
51
|
+
self.assertEqual(report.files[0].risk, 25)
|
|
52
|
+
|
|
53
|
+
def test_lines_that_look_like_headers_are_counted(self):
|
|
54
|
+
report = parse_diff("""diff --git a/q.sql b/q.sql
|
|
55
|
+
--- a/q.sql
|
|
56
|
+
+++ b/q.sql
|
|
57
|
+
@@ -2,2 +1,0 @@
|
|
58
|
+
--- comment
|
|
59
|
+
-++x
|
|
60
|
+
@@ -5,0 +4 @@
|
|
61
|
+
+++y
|
|
62
|
+
""")
|
|
63
|
+
self.assertEqual((report.files[0].added, report.files[0].removed), (1, 2))
|
|
64
|
+
|
|
65
|
+
def test_quoted_non_ascii_path_is_decoded(self):
|
|
66
|
+
report = parse_diff('''diff --git "a/citt\\303\\240/n.txt" "b/citt\\303\\240/n.txt"
|
|
67
|
+
--- "a/citt\\303\\240/n.txt"
|
|
68
|
+
+++ "b/citt\\303\\240/n.txt"
|
|
69
|
+
@@ -1 +1 @@
|
|
70
|
+
-hi
|
|
71
|
+
+bye
|
|
72
|
+
''')
|
|
73
|
+
self.assertEqual(report.files[0].path, "città/n.txt")
|
|
74
|
+
|
|
75
|
+
def test_folder_named_b_and_rename_without_content(self):
|
|
76
|
+
report = parse_diff("""diff --git a/my b/f.txt b/my b/g.txt
|
|
77
|
+
similarity index 100%
|
|
78
|
+
rename from my b/f.txt
|
|
79
|
+
rename to my b/g.txt
|
|
80
|
+
diff --git a/my b/x.bin b/my b/x.bin
|
|
81
|
+
index 1..2 100644
|
|
82
|
+
Binary files a/my b/x.bin and b/my b/x.bin differ
|
|
83
|
+
""")
|
|
84
|
+
self.assertEqual([item.path for item in report.files], ["my b/g.txt", "my b/x.bin"])
|
|
85
|
+
self.assertTrue(report.files[1].binary)
|
|
86
|
+
|
|
87
|
+
def test_deleted_file_keeps_its_path(self):
|
|
88
|
+
report = parse_diff("""diff --git a/old.py b/old.py
|
|
89
|
+
deleted file mode 100644
|
|
90
|
+
--- a/old.py
|
|
91
|
+
+++ /dev/null
|
|
92
|
+
@@ -1 +0,0 @@
|
|
93
|
+
-print(1)
|
|
94
|
+
""")
|
|
95
|
+
self.assertEqual((report.files[0].path, report.files[0].removed), ("old.py", 1))
|
|
96
|
+
|
|
97
|
+
def test_text_format_is_not_markdown(self):
|
|
98
|
+
report = parse_diff("""diff --git a/a.py b/a.py
|
|
99
|
+
--- a/a.py
|
|
100
|
+
+++ b/a.py
|
|
101
|
+
@@ -0,0 +1 @@
|
|
102
|
+
+x
|
|
103
|
+
""")
|
|
104
|
+
text = render_text(report)
|
|
105
|
+
self.assertNotIn("|", text)
|
|
106
|
+
self.assertIn("a.py", text)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
if __name__ == "__main__":
|
|
110
|
+
unittest.main()
|