blot-git 0.0.1__tar.gz → 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.
Files changed (85) hide show
  1. {blot_git-0.0.1 → blot_git-0.1.0}/CONTRIBUTING.md +1 -1
  2. {blot_git-0.0.1 → blot_git-0.1.0}/PKG-INFO +5 -2
  3. {blot_git-0.0.1 → blot_git-0.1.0}/README.md +8 -12
  4. blot_git-0.1.0/assets/demo/demo.gif +0 -0
  5. blot_git-0.1.0/assets/demo/make_demo.py +142 -0
  6. {blot_git-0.0.1 → blot_git-0.1.0}/docs/PRD.md +2 -2
  7. {blot_git-0.0.1 → blot_git-0.1.0}/docs/PYPI.md +3 -1
  8. {blot_git-0.0.1 → blot_git-0.1.0}/pyproject.toml +3 -2
  9. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/__init__.py +1 -1
  10. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/checks/base.py +9 -1
  11. blot_git-0.1.0/src/blot/checks/cochange.py +48 -0
  12. blot_git-0.1.0/src/blot/checks/readded_bug.py +68 -0
  13. blot_git-0.1.0/src/blot/checks/removed_fix.py +140 -0
  14. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/config.py +6 -2
  15. blot_git-0.1.0/src/blot/git.py +54 -0
  16. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/hooks.py +1 -1
  17. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/store.py +7 -7
  18. blot_git-0.1.0/tests/test_checks.py +124 -0
  19. blot_git-0.1.0/tests/test_cli.py +64 -0
  20. {blot_git-0.0.1 → blot_git-0.1.0}/tests/test_config.py +17 -4
  21. blot_git-0.1.0/tests/test_git.py +18 -0
  22. blot_git-0.0.1/src/blot/checks/cochange.py +0 -24
  23. blot_git-0.0.1/src/blot/checks/readded_bug.py +0 -23
  24. blot_git-0.0.1/src/blot/checks/removed_fix.py +0 -22
  25. blot_git-0.0.1/src/blot/git.py +0 -17
  26. blot_git-0.0.1/tests/test_cli.py +0 -26
  27. {blot_git-0.0.1 → blot_git-0.1.0}/.gitattributes +0 -0
  28. {blot_git-0.0.1 → blot_git-0.1.0}/.github/ISSUE_TEMPLATE/bench_case.md +0 -0
  29. {blot_git-0.0.1 → blot_git-0.1.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  30. {blot_git-0.0.1 → blot_git-0.1.0}/.github/ISSUE_TEMPLATE/check_idea.md +0 -0
  31. {blot_git-0.0.1 → blot_git-0.1.0}/.github/pull_request_template.md +0 -0
  32. {blot_git-0.0.1 → blot_git-0.1.0}/.github/workflows/ci.yml +0 -0
  33. {blot_git-0.0.1 → blot_git-0.1.0}/.github/workflows/release.yml +0 -0
  34. {blot_git-0.0.1 → blot_git-0.1.0}/.gitignore +0 -0
  35. {blot_git-0.0.1 → blot_git-0.1.0}/.pre-commit-hooks.yaml +0 -0
  36. {blot_git-0.0.1 → blot_git-0.1.0}/LICENSE +0 -0
  37. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/blue/alert.svg +0 -0
  38. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/blue/faces.svg +0 -0
  39. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/blue/happy.svg +0 -0
  40. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/blue/idle.svg +0 -0
  41. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/blue/sad.svg +0 -0
  42. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/blue/sleepy.svg +0 -0
  43. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/blue/walk.svg +0 -0
  44. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/blue/worried.svg +0 -0
  45. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/build_sprites.py +0 -0
  46. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/mustard/alert.svg +0 -0
  47. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/mustard/faces.svg +0 -0
  48. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/mustard/happy.svg +0 -0
  49. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/mustard/idle.svg +0 -0
  50. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/mustard/sad.svg +0 -0
  51. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/mustard/sleepy.svg +0 -0
  52. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/mustard/walk.svg +0 -0
  53. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/mustard/worried.svg +0 -0
  54. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/orange/alert.svg +0 -0
  55. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/orange/faces.svg +0 -0
  56. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/orange/happy.svg +0 -0
  57. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/orange/idle.svg +0 -0
  58. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/orange/sad.svg +0 -0
  59. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/orange/sleepy.svg +0 -0
  60. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/orange/walk.svg +0 -0
  61. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/orange/worried.svg +0 -0
  62. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/sage/alert.svg +0 -0
  63. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/sage/faces.svg +0 -0
  64. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/sage/happy.svg +0 -0
  65. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/sage/idle.svg +0 -0
  66. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/sage/sad.svg +0 -0
  67. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/sage/sleepy.svg +0 -0
  68. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/sage/walk.svg +0 -0
  69. {blot_git-0.0.1 → blot_git-0.1.0}/assets/sora/sage/worried.svg +0 -0
  70. {blot_git-0.0.1 → blot_git-0.1.0}/bench/README.md +0 -0
  71. {blot_git-0.0.1 → blot_git-0.1.0}/bench/cases.json +0 -0
  72. {blot_git-0.0.1 → blot_git-0.1.0}/docs/EXPLAINER.md +0 -0
  73. {blot_git-0.0.1 → blot_git-0.1.0}/docs/competitors.md +0 -0
  74. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/__main__.py +0 -0
  75. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/checks/__init__.py +0 -0
  76. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/classify.py +0 -0
  77. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/cli.py +0 -0
  78. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/diff.py +0 -0
  79. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/index.py +0 -0
  80. {blot_git-0.0.1 → blot_git-0.1.0}/src/blot/report.py +0 -0
  81. {blot_git-0.0.1 → blot_git-0.1.0}/tests/conftest.py +0 -0
  82. {blot_git-0.0.1 → blot_git-0.1.0}/tests/test_classify.py +0 -0
  83. {blot_git-0.0.1 → blot_git-0.1.0}/tests/test_diff.py +0 -0
  84. {blot_git-0.0.1 → blot_git-0.1.0}/tests/test_hooks.py +0 -0
  85. {blot_git-0.0.1 → blot_git-0.1.0}/tests/test_index.py +0 -0
@@ -25,7 +25,7 @@ pytest
25
25
  ```
26
26
 
27
27
  ## Ground rules
28
- - Core stays **stdlib-only** and the `check` command stays **under 500 ms**.
28
+ - Core stays **stdlib-only on Python 3.11+** (3.10 gets one small dependency, `tomli`, to read config) and the `check` command stays **under 500 ms**. New runtime dependencies need a strong reason.
29
29
  - Quiet beats clever: a new warning must not raise the false-alarm rate on the bench.
30
30
 
31
31
  ## Releasing (maintainers)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: blot-git
3
- Version: 0.0.1
3
+ Version: 0.1.0
4
4
  Summary: A pre-commit check that has read your project's history: warns when a change removes a fix, re-adds a fixed bug, or forgets a file that always changes too.
5
5
  Project-URL: Homepage, https://github.com/Sym-jay/Blot
6
6
  Project-URL: Issues, https://github.com/Sym-jay/Blot/issues
@@ -17,6 +17,7 @@ Classifier: Programming Language :: Python :: 3
17
17
  Classifier: Topic :: Software Development :: Quality Assurance
18
18
  Classifier: Topic :: Software Development :: Version Control :: Git
19
19
  Requires-Python: >=3.10
20
+ Requires-Dist: tomli>=1.1.0; python_version < '3.11'
20
21
  Provides-Extra: dev
21
22
  Requires-Dist: pytest>=8; extra == 'dev'
22
23
  Provides-Extra: github
@@ -34,6 +35,8 @@ Blot warns you *before you commit* when your change:
34
35
 
35
36
  It runs locally, needs no account or AI, and stays quiet unless the history gives it a real reason to speak.
36
37
 
38
+ ![Blot catching a real Flask regression](https://raw.githubusercontent.com/Sym-jay/Blot/main/assets/demo/demo.gif)
39
+
37
40
  ```bash
38
41
  pip install blot-git
39
42
  cd your-repo
@@ -41,6 +44,6 @@ blot index # one-time, builds .git/blot.db
41
44
  blot install-hook # adds Blot to your pre-commit hook
42
45
  ```
43
46
 
44
- > **Status:** pre-alpha. Indexing and the git hook work; the three checks arrive in the next milestone.
47
+ > **Status:** pre-alpha. All three checks work; expect rough edges and please report false alarms.
45
48
 
46
49
  Meet Sora the slime, read the docs, or contribute on GitHub: https://github.com/Sym-jay/Blot
@@ -1,6 +1,6 @@
1
1
  # Blot
2
2
 
3
- [![CI](https://github.com/Sym-jay/Blot/actions/workflows/ci.yml/badge.svg)](https://github.com/Sym-jay/Blot/actions/workflows/ci.yml)
3
+ [![CI](https://github.com/Sym-jay/Blot/actions/workflows/ci.yml/badge.svg)](https://github.com/Sym-jay/Blot/actions/workflows/ci.yml) [![PyPI](https://img.shields.io/pypi/v/blot-git)](https://pypi.org/project/blot-git/)
4
4
 
5
5
  <img src="assets/sora/orange/walk.svg" width="480" alt="Sora, the Blot slime, sliding back and forth">
6
6
 
@@ -18,15 +18,11 @@ Blot warns you *before you commit* when your change:
18
18
 
19
19
  It runs locally, needs no account or AI, and stays quiet unless the history gives it a real reason to speak.
20
20
 
21
- ```
22
- $ git commit -m "simplify static route"
23
- blot: 1 warning
24
- ! removed-fix src/flask/app.py:355
25
- You're changing a line added by a bug fix:
26
- 8efea0cc "Break reference cycle created by default in Flask instances" (fixes #3761)
27
- ```
21
+ <img src="assets/demo/demo.gif" width="760" alt="Blot catching a real Flask regression: simplifying self_ref = weakref.ref(self) triggers a removed-fix warning that traces past a 2023 refactor to the 2020 reference-cycle fix">
22
+
23
+ *A real run on Flask. Plain `git blame` points to a 2023 commit that only moved this line; Blot traces past it to the 2020 fix that explains it. (Regenerate with `python assets/demo/make_demo.py`.)*
28
24
 
29
- > **Status:** pre-alpha. Milestone M1 is done: `blot index` builds the history index (Flask's 3,800 commits in ~2 s) and `blot install-hook` wires up git. The three checks land in M2, so `blot check` doesn't warn yet. See the [roadmap in the PRD](docs/PRD.md#12-milestones-4-weeks-part-time).
25
+ > **Status:** pre-alpha. Milestones M1 and M2 are done: `blot index` builds the history index (Flask's 3,800 commits in ~2 s), `blot install-hook` wires up git, and `blot check` runs the three checks. On Flask it traces an edit to `self_ref = weakref.ref(self)` past the 2023 file split to the 2020 fix, in under 500 ms. See the [roadmap in the PRD](docs/PRD.md#12-milestones-4-weeks-part-time).
30
26
 
31
27
  ## Meet Sora
32
28
 
@@ -50,15 +46,15 @@ Sora comes in four warm palettes:
50
46
 
51
47
  ## Quickstart
52
48
 
53
- Not on PyPI yet, so install from GitHub:
54
-
55
49
  ```bash
56
- pip install git+https://github.com/Sym-jay/Blot
50
+ pip install blot-git # the PyPI name is blot-git; the command is just `blot`
57
51
  cd your-repo
58
52
  blot index # one-time, builds .git/blot.db (refreshes incrementally after that)
59
53
  blot install-hook # adds Blot to .git/hooks/pre-commit without touching existing hooks
60
54
  ```
61
55
 
56
+ For the latest unreleased code, use `pip install git+https://github.com/Sym-jay/Blot` instead.
57
+
62
58
  Remove it any time with `blot install-hook --uninstall`. Settings go in `[tool.blot]` in `pyproject.toml` or a `.blot.toml` file (see `src/blot/config.py`).
63
59
 
64
60
  Or with the [pre-commit](https://pre-commit.com) framework, see `.pre-commit-hooks.yaml`.
Binary file
@@ -0,0 +1,142 @@
1
+ """Render the README / launch-post demo GIF: Blot catching a real Flask regression.
2
+
3
+ Run: pip install pillow && python assets/demo/make_demo.py [path/to/monospace.ttf]
4
+ Out: assets/demo/demo.gif
5
+
6
+ Every line of tool output below was captured from a real run on pallets/flask (d086db85)
7
+ with Blot's pre-commit hook installed. Only the typing animation is synthetic.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import importlib.util
13
+ import os
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from PIL import Image, ImageDraw, ImageFont
18
+
19
+ HERE = Path(__file__).parent
20
+ W, H = 1080, 580
21
+ PAD, LINE_H, FONT_SIZE = 28, 26, 18
22
+ VISIBLE_LINES = 20
23
+ COLORS = {
24
+ "bg": "#1F1B16", "bar": "#2A251E", "text": "#EDE3D3", "dim": "#8C8273", "prompt": "#A9BC8E",
25
+ "warn": "#E39A5B", "minus": "#E07A6A", "plus": "#9FCB8A", "sha": "#F4E2AE",
26
+ }
27
+
28
+ # (kind, text): "cmd" lines are typed, everything else appears at once.
29
+ SCRIPT: list[tuple[str, str]] = [
30
+ ("cmd", "pip install blot-git"),
31
+ ("dim", "Successfully installed blot-git-0.1.0"),
32
+ ("cmd", "blot index"),
33
+ ("text", "blot: indexed 3829 commits (103 load-bearing fixes), full, in 2.0s"),
34
+ ("cmd", "blot install-hook"),
35
+ ("text", "blot: pre-commit hook installed (.git/hooks/pre-commit)"),
36
+ ("note", "# that weakref looks over-complicated... let's simplify it"),
37
+ ("cmd", "git diff -U0"),
38
+ ("dim", "@@ -355 +355 @@ class Flask(App):"),
39
+ ("minus", "- self_ref = weakref.ref(self)"),
40
+ ("plus", "+ self_ref = self"),
41
+ ("cmd", 'git commit -am "Simplify static route"'),
42
+ ("warn", "blot: 1 warning"),
43
+ ("text", ""),
44
+ ("warn", " ! removed-fix src/flask/app.py:355"),
45
+ ("text", " You're removing or changing a line that a bug fix added."),
46
+ ("text", " Check that the bug it fixed can't come back."),
47
+ ("sha", ' 8efea0c "Break reference cycle created by default in Flask instances." (2020-10-03)'),
48
+ ("dim", ' traced past refactor 0ec7f71 "Split the App and Blueprint into Sansio and IO parts"'),
49
+ ]
50
+ SLEEPY_UNTIL = 3 # Sora dozes while the index builds
51
+ ALERT_FROM = 12 # Sora jumps to alert when the warning prints
52
+
53
+
54
+ def _sora():
55
+ spec = importlib.util.spec_from_file_location("build_sprites", HERE.parent / "sora" / "build_sprites.py")
56
+ mod = importlib.util.module_from_spec(spec)
57
+ spec.loader.exec_module(mod)
58
+ return mod
59
+
60
+
61
+ def _font(path: str | None) -> ImageFont.FreeTypeFont:
62
+ candidates = [path] if path else []
63
+ candidates += ["C:/Windows/Fonts/consola.ttf", "/System/Library/Fonts/Menlo.ttc",
64
+ "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"]
65
+ for c in candidates:
66
+ if c and os.path.exists(c):
67
+ return ImageFont.truetype(c, FONT_SIZE)
68
+ sys.exit("no monospace font found; pass a .ttf path as the first argument")
69
+
70
+
71
+ def _draw_sora(draw: ImageDraw.ImageDraw, sora, face: str, x: int, y: int, scale: int = 5) -> None:
72
+ palette = {**sora.PALETTES["orange"], **sora.FIXED}
73
+ cells = {}
74
+ for row_i, row in enumerate(sora.BODY):
75
+ for col_i, key in enumerate(row):
76
+ if key not in ".S":
77
+ cells[(col_i, row_i + sora.TOP)] = key
78
+ for col_i, row_i, key in sora.FACES[face]:
79
+ cells[(col_i, row_i + sora.TOP)] = key
80
+ for (cx, cy), key in cells.items():
81
+ draw.rectangle([x + cx * scale, y + cy * scale, x + cx * scale + scale - 1, y + cy * scale + scale - 1],
82
+ fill=palette[key])
83
+
84
+
85
+ def _frame(lines: list[tuple[str, str]], cursor: bool, face: str, font, sora) -> Image.Image:
86
+ img = Image.new("RGB", (W, H), COLORS["bg"])
87
+ d = ImageDraw.Draw(img)
88
+ d.rectangle([0, 0, W, 34], fill=COLORS["bar"])
89
+ for i, c in enumerate(("#E07A6A", "#E8A33B", "#9FCB8A")):
90
+ d.ellipse([16 + i * 22, 11, 28 + i * 22, 23], fill=c)
91
+ d.text((W // 2, 17), "blot demo: pallets/flask", font=font, fill=COLORS["dim"], anchor="mm")
92
+ shown = lines[-VISIBLE_LINES:]
93
+ for i, (kind, text) in enumerate(shown):
94
+ y = 50 + i * LINE_H
95
+ if kind == "cmd":
96
+ d.text((PAD, y), "$", font=font, fill=COLORS["prompt"])
97
+ d.text((PAD + 20, y), text, font=font, fill=COLORS["text"])
98
+ else:
99
+ color = COLORS.get(kind, COLORS["text"]) if kind != "note" else COLORS["dim"]
100
+ d.text((PAD, y), text, font=font, fill=color)
101
+ if cursor:
102
+ last_kind, last_text = shown[-1] if shown else ("cmd", "")
103
+ offset = 20 if last_kind == "cmd" else 0
104
+ cx = PAD + offset + int(font.getlength(last_text))
105
+ cy = 50 + (len(shown) - 1) * LINE_H
106
+ d.rectangle([cx + 2, cy + 2, cx + 11, cy + 20], fill=COLORS["text"])
107
+ _draw_sora(d, sora, face, W - 28 * 5 - 28, 40) # top right: the early lines there are short
108
+ return img
109
+
110
+
111
+ def main() -> None:
112
+ font = _font(sys.argv[1] if len(sys.argv) > 1 else None)
113
+ sora = _sora()
114
+ frames: list[Image.Image] = []
115
+ durations: list[int] = []
116
+ shown: list[tuple[str, str]] = []
117
+
118
+ def add(face: str, ms: int, cursor: bool = True) -> None:
119
+ frames.append(_frame(shown, cursor, face, font, sora))
120
+ durations.append(ms)
121
+
122
+ for step, (kind, text) in enumerate(SCRIPT):
123
+ face = "sleepy" if step < SLEEPY_UNTIL else ("alert" if step >= ALERT_FROM else "idle")
124
+ if kind == "cmd":
125
+ shown.append(("cmd", ""))
126
+ for n in range(0, len(text) + 1, 3):
127
+ shown[-1] = ("cmd", text[:n])
128
+ add(face, 45)
129
+ shown[-1] = ("cmd", text)
130
+ add(face, 450)
131
+ else:
132
+ shown.append((kind, text))
133
+ add(face, 1100 if step == len(SCRIPT) - 1 else 220, cursor=False)
134
+ add("alert", 4500, cursor=False)
135
+
136
+ out = HERE / "demo.gif"
137
+ frames[0].save(out, save_all=True, append_images=frames[1:], duration=durations, loop=0, optimize=True)
138
+ print(f"wrote {out} ({len(frames)} frames, {out.stat().st_size // 1024} KB)")
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
@@ -35,7 +35,7 @@ These mistakes are caught late (in CI, review or production) or never. AI coding
35
35
  **Goals (v0.1)**
36
36
  - G1. Catch the three mistakes above at commit time, locally, in under 500 ms.
37
37
  - G2. Stay **quiet**: on typical repos, at most 1 warning per 10 commits, and at least 80% of warnings judged useful on the bench.
38
- - G3. Install in one command on Windows, macOS and Linux. Stdlib-only Python.
38
+ - G3. Install in one command on Windows, macOS and Linux. Stdlib-only Python on 3.11+ (3.10 also installs `tomli`).
39
39
  - G4. Every warning cites real evidence (commit SHA, and PR or issue when available). Nothing is made up.
40
40
 
41
41
  **Non-goals (v0.1)**
@@ -130,7 +130,7 @@ The user either reads the linked issue and adjusts the change, or commits anyway
130
130
  - NFR2. **Quiet:** false-alarm rate on the bench's quiet cases at most 10%.
131
131
  - NFR3. **Safety:** never exit non-zero unless `--strict`. Any internal error prints one line and exits 0.
132
132
  - NFR4. **Privacy:** no network access except `index --github`. Nothing leaves the machine.
133
- - NFR5. **Portability:** Python 3.10+, stdlib only. Windows, macOS and Linux tested in CI.
133
+ - NFR5. **Portability:** Python 3.10+. No runtime dependencies on 3.11+; on 3.10, `tomli` reads config files (stdlib `tomllib` arrived in 3.11). Windows, macOS and Linux tested in CI.
134
134
 
135
135
  ## 8. Architecture
136
136
 
@@ -10,6 +10,8 @@ Blot warns you *before you commit* when your change:
10
10
 
11
11
  It runs locally, needs no account or AI, and stays quiet unless the history gives it a real reason to speak.
12
12
 
13
+ ![Blot catching a real Flask regression](https://raw.githubusercontent.com/Sym-jay/Blot/main/assets/demo/demo.gif)
14
+
13
15
  ```bash
14
16
  pip install blot-git
15
17
  cd your-repo
@@ -17,6 +19,6 @@ blot index # one-time, builds .git/blot.db
17
19
  blot install-hook # adds Blot to your pre-commit hook
18
20
  ```
19
21
 
20
- > **Status:** pre-alpha. Indexing and the git hook work; the three checks arrive in the next milestone.
22
+ > **Status:** pre-alpha. All three checks work; expect rough edges and please report false alarms.
21
23
 
22
24
  Meet Sora the slime, read the docs, or contribute on GitHub: https://github.com/Sym-jay/Blot
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "blot-git"
3
- version = "0.0.1"
3
+ version = "0.1.0"
4
4
  description = "A pre-commit check that has read your project's history: warns when a change removes a fix, re-adds a fixed bug, or forgets a file that always changes too."
5
5
  readme = "docs/PYPI.md" # text-only; the GitHub README's relative Sora images break on PyPI
6
6
  license = { text = "MIT" }
@@ -17,7 +17,8 @@ classifiers = [
17
17
  "Topic :: Software Development :: Quality Assurance",
18
18
  "Topic :: Software Development :: Version Control :: Git",
19
19
  ]
20
- dependencies = [] # core is stdlib-only: fast hook startup, trivial install
20
+ # core is stdlib-only: fast hook startup, trivial install. 3.10 has no tomllib, so it gets tomli
21
+ dependencies = ["tomli>=1.1.0; python_version < '3.11'"]
21
22
 
22
23
  [project.urls]
23
24
  Homepage = "https://github.com/Sym-jay/Blot"
@@ -1,3 +1,3 @@
1
1
  """blot: history-aware pre-commit checks."""
2
2
 
3
- __version__ = "0.0.1"
3
+ __version__ = "0.1.0"
@@ -9,7 +9,7 @@ from typing import TYPE_CHECKING
9
9
  if TYPE_CHECKING:
10
10
  from blot.config import Config
11
11
  from blot.diff import FileChange
12
- from blot.store import Store
12
+ from blot.store import CommitRow, Store
13
13
 
14
14
 
15
15
  @dataclass
@@ -29,3 +29,11 @@ class Check(ABC):
29
29
  @abstractmethod
30
30
  def run(self, changes: list[FileChange], store: Store, config: Config) -> list[Finding]:
31
31
  """Return findings for the staged changes. Must not call the network; target < 100 ms."""
32
+
33
+
34
+ def describe_commit(row: CommitRow) -> str:
35
+ """Evidence line: 'abc1234 "subject" (2020-10-03, fixes #3761)'."""
36
+ details = [row.date[:10]]
37
+ if row.issues:
38
+ details.append("fixes " + ", ".join(row.issues))
39
+ return f'{row.sha[:7]} "{row.subject}" ({", ".join(details)})'
@@ -0,0 +1,48 @@
1
+ """Check 3: you changed A, but B almost always changes with A, and B isn't staged.
2
+
3
+ Algorithm (association rules over commit history):
4
+ support(A, B) = number of commits touching both A and B
5
+ confidence(A→B) = support(A, B) / commits touching A
6
+ warn when confidence >= config.cochange_min_confidence
7
+ and support >= config.cochange_min_support
8
+ and B exists at HEAD and is not part of the change
9
+ Commits touching more than config.cochange_max_files_per_commit files are ignored
10
+ (mass reformatting and renames would otherwise link everything to everything).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from fnmatch import fnmatch
16
+
17
+ from blot.checks.base import Check, Finding
18
+ from blot.git import tracked_files
19
+
20
+
21
+ class ForgotRelatedFile(Check):
22
+ id = "forgot-related-file"
23
+ description = "Changed a file without the file that usually changes with it"
24
+
25
+ def run(self, changes, store, config) -> list[Finding]:
26
+ ignored = lambda p: any(fnmatch(p, pattern) for pattern in config.ignore_paths) # noqa: E731
27
+ staged = {p for c in changes for p in (c.path, c.old_path) if p}
28
+ head_files: set[str] | None = None
29
+ findings: list[Finding] = []
30
+ for change in changes:
31
+ if ignored(change.path):
32
+ continue
33
+ partners = store.partners(change.path, config.cochange_min_support, config.cochange_min_confidence)
34
+ if not partners and change.old_path and change.old_path != change.path:
35
+ partners = store.partners(change.old_path, config.cochange_min_support, config.cochange_min_confidence)
36
+ if partners and head_files is None:
37
+ head_files = tracked_files(store.repo)
38
+ for partner, support, confidence in partners: # strongest first
39
+ if partner in staged or partner not in head_files or ignored(partner):
40
+ continue
41
+ findings.append(Finding(
42
+ self.id, change.path, None,
43
+ f"{partner} changed together with this file in {confidence:.0%} of its commits "
44
+ f"({support} commits), but it isn't staged.",
45
+ severity=1,
46
+ ))
47
+ break # at most one finding per staged file
48
+ return findings
@@ -0,0 +1,68 @@
1
+ """Check 2: you're adding back a line that a load-bearing bug fix deliberately removed.
2
+
3
+ Algorithm:
4
+ 1. normalize each added line (strip whitespace and trailing comments)
5
+ 2. skip trivial lines: shorter than 12 chars, only brackets/keywords, imports
6
+ 3. look up its hash in fix_removed_lines (same path, or any path if it was renamed)
7
+ 4. skip if an identical line still exists elsewhere in the file at HEAD
8
+ (then the fix did not remove the idea, only one copy)
9
+ 5. warn with the fix commit that removed it
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import subprocess
15
+
16
+ from blot.checks.base import Check, Finding, describe_commit
17
+ from blot.diff import is_trivial_line, line_hash, normalize_line
18
+ from blot.git import run_git, tracked_files
19
+
20
+
21
+ def _head_lines(repo: str, path: str) -> set[str]:
22
+ try:
23
+ text = run_git(repo, "show", f"HEAD:{path}")
24
+ except subprocess.CalledProcessError:
25
+ return set()
26
+ return {normalize_line(line) for line in text.splitlines()}
27
+
28
+
29
+ class ReaddedBug(Check):
30
+ id = "readded-bug"
31
+ description = "Re-adding a line that a bug fix removed"
32
+
33
+ def run(self, changes, store, config) -> list[Finding]:
34
+ findings: list[Finding] = []
35
+ head_files: set[str] | None = None
36
+ for change in changes:
37
+ paths = {change.path, change.old_path} - {None}
38
+ head_lines: set[str] | None = None
39
+ reported: set[str] = set()
40
+ for number, text in change.added:
41
+ norm = normalize_line(text)
42
+ if is_trivial_line(norm):
43
+ continue
44
+ hits = store.fixes_that_removed(line_hash(norm))
45
+ if not hits:
46
+ continue
47
+ if any(p not in paths for p, _ in hits) and head_files is None:
48
+ head_files = tracked_files(store.repo)
49
+ # a fix on another path only counts if that path is gone (renamed or moved since)
50
+ shas = [sha for p, sha in hits if p in paths or p not in head_files]
51
+ rows = [r for r in map(store.get_commit, shas) if r and r.severity >= config.min_severity]
52
+ if not rows:
53
+ continue
54
+ if head_lines is None:
55
+ head_lines = _head_lines(store.repo, change.old_path) if change.old_path else set()
56
+ if norm in head_lines:
57
+ continue
58
+ row = max(rows, key=lambda r: r.date) # the most recent fix that removed it
59
+ if row.sha in reported:
60
+ continue
61
+ reported.add(row.sha)
62
+ findings.append(Finding(
63
+ self.id, change.path, number,
64
+ "You're adding back a line that a bug fix removed.\n"
65
+ "Check that this doesn't bring the bug back.",
66
+ [describe_commit(row)], row.severity,
67
+ ))
68
+ return findings
@@ -0,0 +1,140 @@
1
+ """Check 1: you're deleting or editing lines that a load-bearing bug fix added.
2
+
3
+ Algorithm:
4
+ 1. for each file, take the removed lines (old line numbers)
5
+ 2. `git blame -w -M -C --porcelain -L a,b HEAD -- <old_path>` for those ranges
6
+ 3. if the blamed commit is a refactor (classify.is_refactor), re-blame at its parent
7
+ on the original path, up to 3 hops
8
+ 4. warn if the final commit's severity >= config.min_severity
9
+
10
+ "The original path" is found in the refactor's own diff: the line it deleted with the same
11
+ normalized text, preferring the same path. That is how a file split is followed back.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import subprocess
17
+
18
+ from blot.checks.base import Check, Finding, describe_commit
19
+ from blot.diff import normalize_line, parse_unified_diff
20
+ from blot.git import run_git
21
+
22
+ MAX_HOPS = 3
23
+
24
+
25
+ def _ranges(numbers: list[int]) -> list[tuple[int, int]]:
26
+ """Collapse sorted line numbers into inclusive (start, end) runs."""
27
+ runs: list[tuple[int, int]] = []
28
+ for n in sorted(set(numbers)):
29
+ if runs and n == runs[-1][1] + 1:
30
+ runs[-1] = (runs[-1][0], n)
31
+ else:
32
+ runs.append((n, n))
33
+ return runs
34
+
35
+
36
+ def blame(repo: str, rev: str, path: str, lines: list[int]) -> dict[int, tuple[str, str, int]]:
37
+ """{line: (sha, path in that commit, line in that commit)} via one porcelain blame call."""
38
+ args = ["blame", "-w", "-M", "-C", "--porcelain"]
39
+ for start, end in _ranges(lines):
40
+ args += ["-L", f"{start},{end}"]
41
+ try:
42
+ out = run_git(repo, *args, rev, "--", path)
43
+ except subprocess.CalledProcessError:
44
+ return {}
45
+ result: dict[int, tuple[str, str, int]] = {}
46
+ filenames: dict[str, str] = {}
47
+ sha, orig, final = "", 0, 0
48
+ for line in out.splitlines():
49
+ if line.startswith("\t"):
50
+ result[final] = (sha, filenames.get(sha, path), orig)
51
+ elif line.startswith("filename "):
52
+ filenames[sha] = line[9:]
53
+ else:
54
+ parts = line.split(" ")
55
+ if len(parts) >= 3 and len(parts[0]) == 40 and parts[1].isdigit() and parts[2].isdigit():
56
+ sha, orig, final = parts[0], int(parts[1]), int(parts[2])
57
+ return result
58
+
59
+
60
+ class _RefactorOrigins:
61
+ """Where a refactor commit took each line from: normalized text -> [(old path, old line)]."""
62
+
63
+ def __init__(self, repo: str):
64
+ self.repo = repo
65
+ self.cache: dict[str, dict[str, list[tuple[str, int]]]] = {}
66
+
67
+ def find(self, sha: str, path: str, text: str) -> tuple[str, int] | None:
68
+ if sha not in self.cache:
69
+ origins: dict[str, list[tuple[str, int]]] = {}
70
+ try:
71
+ diff = run_git(self.repo, "show", "--format=", "-U0", "--no-color", "--no-ext-diff", "-M", sha)
72
+ except subprocess.CalledProcessError:
73
+ diff = ""
74
+ for change in parse_unified_diff(diff):
75
+ for number, removed in change.removed:
76
+ origins.setdefault(normalize_line(removed), []).append((change.old_path or change.path, number))
77
+ self.cache[sha] = origins
78
+ candidates = self.cache[sha].get(normalize_line(text), [])
79
+ same_path = [c for c in candidates if c[0] == path]
80
+ return (same_path or candidates or [None])[0]
81
+
82
+
83
+ class RemovedFix(Check):
84
+ id = "removed-fix"
85
+ description = "Changing code that a bug fix added"
86
+
87
+ def run(self, changes, store, config) -> list[Finding]:
88
+ repo = store.repo
89
+ origins = _RefactorOrigins(repo)
90
+ findings: list[Finding] = []
91
+ for change in changes:
92
+ if change.old_path is None or not change.removed:
93
+ continue
94
+ kept = {normalize_line(text) for _, text in change.added}
95
+ # whitespace-only edits and blank lines say nothing about the fix
96
+ texts = {n: t for n, t in change.removed if normalize_line(t) and normalize_line(t) not in kept}
97
+ if not texts:
98
+ continue
99
+
100
+ blamed = blame(repo, "HEAD", change.old_path, list(texts))
101
+ # line -> (sha, path, line in that commit, refactors traced past)
102
+ trail = {n: (sha, p, o, []) for n, (sha, p, o) in blamed.items() if n in texts}
103
+ for _ in range(MAX_HOPS):
104
+ pending: dict[tuple[str, str], list[tuple[int, int]]] = {} # (parent rev, path) -> [(line, origin line)]
105
+ for n, (sha, path, orig, via) in trail.items():
106
+ row = store.get_commit(sha)
107
+ if row is None or not row.is_refactor:
108
+ continue
109
+ origin = origins.find(sha, path, texts[n])
110
+ if origin is None:
111
+ continue
112
+ pending.setdefault((f"{sha}^", origin[0]), []).append((n, origin[1]))
113
+ if not pending:
114
+ break
115
+ for (rev, path), items in pending.items():
116
+ earlier = blame(repo, rev, path, [o for _, o in items])
117
+ for n, o in items:
118
+ if o in earlier:
119
+ sha, *_ = trail[n]
120
+ trail[n] = (*earlier[o], [*trail[n][3], sha])
121
+
122
+ reported: set[str] = set()
123
+ for n in sorted(trail):
124
+ sha, _, _, via = trail[n]
125
+ row = store.get_commit(sha)
126
+ if row is None or row.is_refactor or row.severity < config.min_severity or sha in reported:
127
+ continue
128
+ reported.add(sha) # one finding per fix per file, at its first line
129
+ evidence = [describe_commit(row)]
130
+ for ref_sha in via:
131
+ ref = store.get_commit(ref_sha)
132
+ if ref is not None:
133
+ evidence.append(f'traced past refactor {ref_sha[:7]} "{ref.subject}"')
134
+ findings.append(Finding(
135
+ self.id, change.old_path, n,
136
+ "You're removing or changing a line that a bug fix added.\n"
137
+ "Check that the bug it fixed can't come back.",
138
+ evidence, row.severity,
139
+ ))
140
+ return findings
@@ -8,7 +8,7 @@
8
8
  disabled-checks = ["forgot-related-file"]
9
9
  ignore-paths = ["docs/*", "*.lock"]
10
10
 
11
- TOML parsing needs Python 3.11+ (stdlib `tomllib`). On 3.10 the defaults are used.
11
+ TOML is read with the stdlib `tomllib` on Python 3.11+ and with `tomli` on 3.10 (a dependency there only).
12
12
  """
13
13
 
14
14
  from __future__ import annotations
@@ -35,7 +35,11 @@ def _read_toml(path: str) -> dict:
35
35
  try:
36
36
  import tomllib
37
37
  except ModuleNotFoundError: # Python 3.10
38
- return {}
38
+ try:
39
+ import tomli as tomllib
40
+ except ModuleNotFoundError:
41
+ print(f"blot: ignoring {os.path.basename(path)}: reading it on Python 3.10 needs tomli", file=sys.stderr)
42
+ return {}
39
43
  try:
40
44
  with open(path, "rb") as f:
41
45
  return tomllib.load(f)
@@ -0,0 +1,54 @@
1
+ """Thin wrapper around the git CLI. All git access goes through here so tests can fake it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+
8
+
9
+ def git_dir(repo: str) -> str:
10
+ """Absolute path of the repo's git directory.
11
+
12
+ Found by walking up from `repo` for `.git` (a directory, or a `gitdir:` file in worktrees and
13
+ submodules), which avoids spawning git: each git process costs ~40 ms on Windows and
14
+ `blot check` runs on every commit. Falls back to `git rev-parse` for anything unusual.
15
+ """
16
+ env_dir = os.environ.get("GIT_DIR")
17
+ if env_dir:
18
+ return os.path.abspath(env_dir)
19
+ here = os.path.abspath(repo)
20
+ while True:
21
+ dot_git = os.path.join(here, ".git")
22
+ if os.path.isdir(dot_git):
23
+ return dot_git
24
+ if os.path.isfile(dot_git):
25
+ with open(dot_git, encoding="utf-8") as f:
26
+ first = f.readline().strip()
27
+ if first.startswith("gitdir:"):
28
+ return os.path.normpath(os.path.join(here, first[len("gitdir:"):].strip()))
29
+ break
30
+ parent = os.path.dirname(here)
31
+ if parent == here:
32
+ break
33
+ here = parent
34
+ return run_git(repo, "rev-parse", "--absolute-git-dir").strip()
35
+
36
+
37
+ def run_git(repo: str, *args: str) -> str:
38
+ result = subprocess.run(
39
+ ["git", "-C", repo, *args],
40
+ capture_output=True,
41
+ text=True,
42
+ encoding="utf-8",
43
+ errors="replace",
44
+ check=True,
45
+ )
46
+ return result.stdout
47
+
48
+
49
+ def tracked_files(repo: str, rev: str = "HEAD") -> set[str]:
50
+ """Paths that exist at `rev` (empty for a repo with no commits yet)."""
51
+ try:
52
+ return set(run_git(repo, "ls-tree", "-r", "--name-only", "-z", rev).split("\0")) - {""}
53
+ except subprocess.CalledProcessError:
54
+ return set()
@@ -19,7 +19,7 @@ BEGIN, END = "# >>> blot >>>", "# <<< blot <<<"
19
19
 
20
20
  def hook_path(repo: str, name: str = "pre-commit") -> str:
21
21
  path = run_git(repo, "rev-parse", "--git-path", f"hooks/{name}").strip()
22
- return path if os.path.isabs(path) else os.path.join(repo, path)
22
+ return os.path.normpath(path if os.path.isabs(path) else os.path.join(repo, path))
23
23
 
24
24
 
25
25
  def _block(python: str) -> str: