blot-git 0.3.1__tar.gz → 0.4.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 (91) hide show
  1. blot_git-0.4.0/.github/workflows/blot.yml +14 -0
  2. {blot_git-0.3.1 → blot_git-0.4.0}/.pre-commit-hooks.yaml +4 -1
  3. {blot_git-0.3.1 → blot_git-0.4.0}/PKG-INFO +2 -2
  4. {blot_git-0.3.1 → blot_git-0.4.0}/README.md +22 -1
  5. blot_git-0.4.0/action.yml +73 -0
  6. {blot_git-0.3.1 → blot_git-0.4.0}/docs/PYPI.md +1 -1
  7. {blot_git-0.3.1 → blot_git-0.4.0}/pyproject.toml +1 -1
  8. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/__init__.py +1 -1
  9. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/cli.py +23 -13
  10. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/diff.py +10 -0
  11. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/git.py +40 -0
  12. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/index.py +5 -3
  13. blot_git-0.4.0/tests/test_action.py +67 -0
  14. {blot_git-0.3.1 → blot_git-0.4.0}/tests/test_cli.py +40 -2
  15. blot_git-0.4.0/tests/test_git.py +36 -0
  16. {blot_git-0.3.1 → blot_git-0.4.0}/tests/test_hooks.py +1 -1
  17. {blot_git-0.3.1 → blot_git-0.4.0}/tests/test_why_github.py +2 -3
  18. blot_git-0.3.1/tests/test_git.py +0 -18
  19. {blot_git-0.3.1 → blot_git-0.4.0}/.gitattributes +0 -0
  20. {blot_git-0.3.1 → blot_git-0.4.0}/.github/ISSUE_TEMPLATE/bench_case.md +0 -0
  21. {blot_git-0.3.1 → blot_git-0.4.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  22. {blot_git-0.3.1 → blot_git-0.4.0}/.github/ISSUE_TEMPLATE/check_idea.md +0 -0
  23. {blot_git-0.3.1 → blot_git-0.4.0}/.github/pull_request_template.md +0 -0
  24. {blot_git-0.3.1 → blot_git-0.4.0}/.github/workflows/ci.yml +0 -0
  25. {blot_git-0.3.1 → blot_git-0.4.0}/.github/workflows/release.yml +0 -0
  26. {blot_git-0.3.1 → blot_git-0.4.0}/.gitignore +0 -0
  27. {blot_git-0.3.1 → blot_git-0.4.0}/CONTRIBUTING.md +0 -0
  28. {blot_git-0.3.1 → blot_git-0.4.0}/LICENSE +0 -0
  29. {blot_git-0.3.1 → blot_git-0.4.0}/assets/demo/demo.gif +0 -0
  30. {blot_git-0.3.1 → blot_git-0.4.0}/assets/demo/make_demo.py +0 -0
  31. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/blue/alert.svg +0 -0
  32. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/blue/faces.svg +0 -0
  33. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/blue/happy.svg +0 -0
  34. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/blue/idle.svg +0 -0
  35. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/blue/sad.svg +0 -0
  36. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/blue/sleepy.svg +0 -0
  37. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/blue/walk.svg +0 -0
  38. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/blue/worried.svg +0 -0
  39. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/build_sprites.py +0 -0
  40. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/mustard/alert.svg +0 -0
  41. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/mustard/faces.svg +0 -0
  42. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/mustard/happy.svg +0 -0
  43. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/mustard/idle.svg +0 -0
  44. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/mustard/sad.svg +0 -0
  45. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/mustard/sleepy.svg +0 -0
  46. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/mustard/walk.svg +0 -0
  47. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/mustard/worried.svg +0 -0
  48. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/orange/alert.svg +0 -0
  49. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/orange/faces.svg +0 -0
  50. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/orange/happy.svg +0 -0
  51. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/orange/idle.svg +0 -0
  52. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/orange/sad.svg +0 -0
  53. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/orange/sleepy.svg +0 -0
  54. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/orange/walk.svg +0 -0
  55. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/orange/worried.svg +0 -0
  56. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/sage/alert.svg +0 -0
  57. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/sage/faces.svg +0 -0
  58. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/sage/happy.svg +0 -0
  59. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/sage/idle.svg +0 -0
  60. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/sage/sad.svg +0 -0
  61. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/sage/sleepy.svg +0 -0
  62. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/sage/walk.svg +0 -0
  63. {blot_git-0.3.1 → blot_git-0.4.0}/assets/sora/sage/worried.svg +0 -0
  64. {blot_git-0.3.1 → blot_git-0.4.0}/bench/README.md +0 -0
  65. {blot_git-0.3.1 → blot_git-0.4.0}/bench/RESULTS.md +0 -0
  66. {blot_git-0.3.1 → blot_git-0.4.0}/bench/cases.json +0 -0
  67. {blot_git-0.3.1 → blot_git-0.4.0}/docs/EXPLAINER.md +0 -0
  68. {blot_git-0.3.1 → blot_git-0.4.0}/docs/PRD.md +0 -0
  69. {blot_git-0.3.1 → blot_git-0.4.0}/docs/competitors.md +0 -0
  70. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/__main__.py +0 -0
  71. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/bench.py +0 -0
  72. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/checks/__init__.py +0 -0
  73. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/checks/base.py +0 -0
  74. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/checks/cochange.py +0 -0
  75. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/checks/readded_bug.py +0 -0
  76. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/checks/removed_fix.py +0 -0
  77. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/classify.py +0 -0
  78. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/config.py +0 -0
  79. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/github.py +0 -0
  80. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/hooks.py +0 -0
  81. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/report.py +0 -0
  82. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/store.py +0 -0
  83. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/trace.py +0 -0
  84. {blot_git-0.3.1 → blot_git-0.4.0}/src/blot/why.py +0 -0
  85. {blot_git-0.3.1 → blot_git-0.4.0}/tests/conftest.py +0 -0
  86. {blot_git-0.3.1 → blot_git-0.4.0}/tests/test_bench.py +0 -0
  87. {blot_git-0.3.1 → blot_git-0.4.0}/tests/test_checks.py +0 -0
  88. {blot_git-0.3.1 → blot_git-0.4.0}/tests/test_classify.py +0 -0
  89. {blot_git-0.3.1 → blot_git-0.4.0}/tests/test_config.py +0 -0
  90. {blot_git-0.3.1 → blot_git-0.4.0}/tests/test_diff.py +0 -0
  91. {blot_git-0.3.1 → blot_git-0.4.0}/tests/test_index.py +0 -0
@@ -0,0 +1,14 @@
1
+ name: Blot on Blot
2
+
3
+ # Runs this repo's own action (action.yml) on every pull request, installing Blot from the
4
+ # pull request's code: it tests the action end to end and reviews Blot's history with Blot.
5
+ on: pull_request
6
+
7
+ jobs:
8
+ blot:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ - uses: ./
13
+ with:
14
+ blot-package: .
@@ -1,11 +1,14 @@
1
1
  # Lets users of the pre-commit framework add blot with:
2
2
  # - repo: https://github.com/Sym-jay/Blot
3
- # rev: v0.1.0
3
+ # rev: v0.4.0
4
4
  # hooks: [{id: blot}]
5
+ # The first commit indexes the repo's history; later commits refresh the index incrementally.
5
6
  - id: blot
6
7
  name: blot (history-aware checks)
7
8
  entry: blot check --staged
8
9
  language: python
9
10
  pass_filenames: false
10
11
  always_run: true
12
+ # blot warns without failing the commit, and pre-commit hides output of passing hooks
13
+ verbose: true
11
14
  stages: [pre-commit]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: blot-git
3
- Version: 0.3.1
3
+ Version: 0.4.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
@@ -40,7 +40,7 @@ It runs locally, needs no account or AI, and stays quiet unless the history give
40
40
  ```bash
41
41
  pip install blot-git
42
42
  cd your-repo
43
- blot index # one-time, builds .git/blot.db
43
+ blot index # optional: the first check indexes history itself
44
44
  blot install-hook # adds Blot to your pre-commit hook
45
45
  blot why src/app.py:42 # which commit explains this line, skipping refactors
46
46
  blot index --github # optional: issue/PR titles and labels via the gh CLI
@@ -49,7 +49,7 @@ Sora comes in four warm palettes:
49
49
  ```bash
50
50
  pip install blot-git # the PyPI name is blot-git; the command is just `blot`
51
51
  cd your-repo
52
- blot index # one-time, builds .git/blot.db (refreshes incrementally after that)
52
+ blot index # optional: the first check builds .git/blot.db itself and keeps it current
53
53
  blot install-hook # adds Blot to .git/hooks/pre-commit without touching existing hooks
54
54
  ```
55
55
 
@@ -79,6 +79,27 @@ blot index --github
79
79
 
80
80
  With the [GitHub CLI](https://cli.github.com) logged in, Blot fetches the titles and labels of the issues and PRs your fix commits mention, so warnings read `fixes #2935 "copy_current_request_context copies old session object"` (a real Flask issue) instead of a bare number. A `bug` label makes a commit count as a load-bearing fix; a fix-looking commit whose issues are only labelled `enhancement` or `documentation` is demoted. Refreshes only fetch what's new. Repos with GitHub Issues turned off (they track bugs elsewhere) are skipped.
81
81
 
82
+ ## Use in CI
83
+
84
+ Run Blot on every pull request and see its findings as warnings on the changed lines:
85
+
86
+ ```yaml
87
+ # .github/workflows/blot.yml
88
+ name: Blot
89
+ on: pull_request
90
+ jobs:
91
+ blot:
92
+ runs-on: ubuntu-latest
93
+ steps:
94
+ - uses: Sym-jay/Blot@v0.4.0
95
+ ```
96
+
97
+ The action checks out the pull request with its full history, installs Blot, runs `blot index` and
98
+ `blot check --range origin/<base>..HEAD --format json`, and turns each finding into a warning annotation.
99
+ It never fails the job because of findings. Inputs: `blot-package` (what to `pip install`; default
100
+ `blot-git`, the latest PyPI release), `python-version` (default `3.13`) and `base-ref`
101
+ (default: the pull request's base branch).
102
+
82
103
  ## Measure it on your repo
83
104
 
84
105
  ```bash
@@ -0,0 +1,73 @@
1
+ # Run Blot on a pull request and show its findings as warning annotations.
2
+ # Usage (in a workflow triggered by pull_request):
3
+ # - uses: Sym-jay/Blot@v0.4.0
4
+ # See "Use in CI" in README.md.
5
+ name: Blot
6
+ description: History-aware checks on the commits of a pull request, shown as warning annotations
7
+ author: Sym-jay
8
+ branding:
9
+ icon: alert-triangle
10
+ color: orange
11
+
12
+ inputs:
13
+ base-ref:
14
+ description: Branch the pull request merges into; the action checks origin/<base-ref>..HEAD
15
+ default: ${{ github.base_ref }}
16
+ python-version:
17
+ description: Python version used to run Blot
18
+ default: "3.13"
19
+ blot-package:
20
+ description: What to pip install (a pip requirement, e.g. blot-git==0.3.2)
21
+ default: blot-git # the latest release on PyPI
22
+
23
+ runs:
24
+ using: composite
25
+ steps:
26
+ - uses: actions/checkout@v4
27
+ with:
28
+ fetch-depth: 0 # Blot reads the whole history
29
+
30
+ - uses: actions/setup-python@v5
31
+ with:
32
+ python-version: ${{ inputs.python-version }}
33
+
34
+ - name: Install Blot
35
+ shell: bash
36
+ env:
37
+ BLOT_PACKAGE: ${{ inputs.blot-package }}
38
+ run: python -m pip install --disable-pip-version-check "$BLOT_PACKAGE"
39
+
40
+ - name: Run Blot
41
+ shell: bash
42
+ env:
43
+ BASE_REF: ${{ inputs.base-ref }}
44
+ BLOT_FINDINGS: ${{ runner.temp }}/blot-findings.json
45
+ PYTHONUTF8: "1" # commit subjects in findings may not be ASCII
46
+ run: |
47
+ if [[ -z "$BASE_REF" ]]; then
48
+ echo "::error title=blot::No base branch: run this action on pull_request, or set base-ref"
49
+ exit 1
50
+ fi
51
+ blot index
52
+ blot check --range "origin/${BASE_REF}..HEAD" --format json > "$BLOT_FINDINGS"
53
+ python - <<'PY'
54
+ # Turn blot's JSON findings into workflow annotations (::warning file=...,line=...::message).
55
+ import json, os
56
+
57
+ def esc(text, prop=False):
58
+ text = text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
59
+ return text.replace(":", "%3A").replace(",", "%2C") if prop else text
60
+
61
+ with open(os.environ["BLOT_FINDINGS"], encoding="utf-8") as f:
62
+ raw = f.read()
63
+ # blot check prints nothing on stdout when it hits an internal error (the reason is in the log above)
64
+ findings = json.loads(raw) if raw.strip() else []
65
+ for f in findings:
66
+ props = f"file={esc(f['path'], True)}"
67
+ if f.get("line"):
68
+ props += f",line={f['line']}"
69
+ props += f",title={esc('blot: ' + f['check'], True)}"
70
+ message = "\n".join([f["message"], *f.get("evidence", [])])
71
+ print(f"::warning {props}::{esc(message)}")
72
+ print(f"blot: {len(findings)} finding{'' if len(findings) == 1 else 's'}")
73
+ PY
@@ -15,7 +15,7 @@ It runs locally, needs no account or AI, and stays quiet unless the history give
15
15
  ```bash
16
16
  pip install blot-git
17
17
  cd your-repo
18
- blot index # one-time, builds .git/blot.db
18
+ blot index # optional: the first check indexes history itself
19
19
  blot install-hook # adds Blot to your pre-commit hook
20
20
  blot why src/app.py:42 # which commit explains this line, skipping refactors
21
21
  blot index --github # optional: issue/PR titles and labels via the gh CLI
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "blot-git"
3
- version = "0.3.1"
3
+ version = "0.4.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" }
@@ -1,3 +1,3 @@
1
1
  """blot: history-aware pre-commit checks."""
2
2
 
3
- __version__ = "0.3.1"
3
+ __version__ = "0.4.0"
@@ -11,6 +11,7 @@ Commands:
11
11
  from __future__ import annotations
12
12
 
13
13
  import argparse
14
+ import os
14
15
  import sys
15
16
 
16
17
  from blot import __version__
@@ -42,18 +43,31 @@ def _cmd_index(args: argparse.Namespace) -> int:
42
43
  return 0
43
44
 
44
45
 
45
- def _cmd_check(args: argparse.Namespace) -> int:
46
- from blot.diff import read_changes
46
+ def _open_index(repo: str):
47
+ """Open the index, building or refreshing it first.
48
+
49
+ The pre-commit framework installs Blot where users can't easily run `blot index`, so the hook
50
+ must look after the index itself: one full build on first use, then cheap incremental refreshes.
51
+ """
52
+ from blot.index import build_index
47
53
  from blot.store import Store
48
54
 
55
+ if not os.path.exists(Store.db_path(repo)):
56
+ print("blot: first run, indexing this repo's history once (big repos can take a minute)...",
57
+ file=sys.stderr)
58
+ build_index(repo)
59
+ return Store.open(repo)
60
+
61
+
62
+ def _cmd_check(args: argparse.Namespace) -> int:
63
+ from blot.diff import range_base, read_changes
64
+
49
65
  try:
50
66
  config = load_config(args.repo)
51
- store = Store.open(args.repo)
52
- if store is None:
53
- # Never break a commit because the index is missing; just say how to fix it.
54
- print("blot: no index yet, run `blot index` (commit allowed)", file=sys.stderr)
55
- return 0
67
+ store = _open_index(args.repo)
56
68
  changes = read_changes(args.repo, rev_range=args.range)
69
+ if args.range: # removed lines are numbered as in the range's base, not as in HEAD
70
+ store.rev = range_base(args.repo, args.range)
57
71
  findings = [f for check in all_checks(config) for f in check.run(changes, store, config)]
58
72
  except Exception as exc: # Blot's own failures must never block a commit
59
73
  print(f"blot: internal error, skipping checks ({exc.__class__.__name__}: {exc})", file=sys.stderr)
@@ -63,13 +77,9 @@ def _cmd_check(args: argparse.Namespace) -> int:
63
77
 
64
78
 
65
79
  def _cmd_why(args: argparse.Namespace) -> int:
66
- from blot.store import Store
67
80
  from blot.why import WhyError, explain, render
68
81
 
69
- store = Store.open(args.repo)
70
- if store is None:
71
- print("blot: no index yet, run `blot index` first", file=sys.stderr)
72
- return 1
82
+ store = _open_index(args.repo)
73
83
  try:
74
84
  path, explained = explain(store, args.location, args.rev)
75
85
  except WhyError as exc:
@@ -90,7 +100,7 @@ def _cmd_install_hook(args: argparse.Namespace) -> int:
90
100
  status = hooks.install(args.repo)
91
101
  print(f"blot: pre-commit hook {status} ({hooks.hook_path(args.repo)})")
92
102
  if status != "already installed":
93
- print("blot: run `blot index` once so the checks have history to work with")
103
+ print("blot: the first commit indexes this repo's history (or run `blot index` now)")
94
104
  return 0
95
105
 
96
106
 
@@ -145,3 +145,13 @@ def read_changes(repo: str, rev_range: str | None = None) -> list[FileChange]:
145
145
  args = ["diff", "-U0", "--no-color", "--no-ext-diff", "-M"]
146
146
  args.append(rev_range if rev_range else "--cached")
147
147
  return parse_unified_diff(run_git(repo, *args))
148
+
149
+
150
+ def range_base(repo: str, rev_range: str) -> str:
151
+ """The commit `git diff <rev_range>` compares against: A for `A..B`, the merge base for `A...B`."""
152
+ if "..." in rev_range:
153
+ left, right = rev_range.split("...", 1)
154
+ return run_git(repo, "merge-base", left or "HEAD", right or "HEAD").strip()
155
+ if ".." in rev_range:
156
+ return rev_range.split("..", 1)[0] or "HEAD"
157
+ return rev_range
@@ -34,6 +34,46 @@ def git_dir(repo: str) -> str:
34
34
  return run_git(repo, "rev-parse", "--absolute-git-dir").strip()
35
35
 
36
36
 
37
+ def head_sha(repo: str) -> str | None:
38
+ """The commit HEAD points at, read from .git files (the hook calls this on every commit).
39
+
40
+ Handles loose and packed refs, detached HEAD and worktrees (`commondir`). Anything else, such as
41
+ the reftable format, falls back to `git rev-parse`.
42
+ """
43
+ gd = git_dir(repo)
44
+ try:
45
+ with open(os.path.join(gd, "HEAD"), encoding="utf-8") as f:
46
+ head = f.read().strip()
47
+ if not head.startswith("ref: "):
48
+ return head if len(head) == 40 else None
49
+ ref = head[5:]
50
+ bases = [gd]
51
+ common = os.path.join(gd, "commondir")
52
+ if os.path.isfile(common):
53
+ with open(common, encoding="utf-8") as f:
54
+ bases.append(os.path.normpath(os.path.join(gd, f.read().strip())))
55
+ for base in bases:
56
+ loose = os.path.join(base, *ref.split("/"))
57
+ if os.path.isfile(loose):
58
+ with open(loose, encoding="utf-8") as f:
59
+ return f.read().strip()
60
+ packed = os.path.join(base, "packed-refs")
61
+ if os.path.isfile(packed):
62
+ with open(packed, encoding="utf-8") as f:
63
+ for line in f:
64
+ sha, _, name = line.strip().partition(" ")
65
+ if name == ref:
66
+ return sha
67
+ if not os.path.isdir(os.path.join(gd, "reftable")):
68
+ return None # unborn branch: no commits yet
69
+ except OSError:
70
+ pass
71
+ try:
72
+ return run_git(repo, "rev-parse", "--verify", "-q", "HEAD").strip() or None
73
+ except subprocess.CalledProcessError:
74
+ return None
75
+
76
+
37
77
  def run_git(repo: str, *args: str) -> str:
38
78
  result = subprocess.run(
39
79
  ["git", "-C", repo, *args],
@@ -20,7 +20,7 @@ from dataclasses import dataclass
20
20
  from blot.classify import CommitInfo, fix_severity, is_refactor, linked_issues
21
21
  from blot.config import Config, load_config
22
22
  from blot.diff import is_trivial_line, line_hash, normalize_line, parse_unified_diff
23
- from blot.git import run_git
23
+ from blot.git import head_sha, run_git
24
24
  from blot.store import CommitRow, Store
25
25
 
26
26
  _RECORD, _FIELD = "\x1e", "\x1f"
@@ -144,13 +144,15 @@ def build_index(
144
144
  ) -> IndexResult:
145
145
  """Index history up to `upto` into `db_path` (default .git/blot.db). Bench replays use both."""
146
146
  start = time.perf_counter()
147
- config = config or load_config(repo)
148
- head = _head(repo, upto)
147
+ head = head_sha(repo) if upto == "HEAD" else _head(repo, upto)
149
148
 
150
149
  store = Store.open(repo, db_path)
151
150
  last = store.get_meta("last_sha") if store else None
152
151
  if store:
153
152
  store.close()
153
+ if not full and head is not None and last == head: # already current: `blot check` hits this on every commit
154
+ return IndexResult(0, 0, time.perf_counter() - start, False)
155
+ config = config or load_config(repo)
154
156
  rebuild = full or not last or (head is not None and not _is_ancestor(repo, last, head))
155
157
  store = Store.create(repo, fresh=rebuild, path=db_path)
156
158
 
@@ -0,0 +1,67 @@
1
+ """action.yml: the step that turns `blot check --format json` output into workflow annotations."""
2
+
3
+ import json
4
+ import os
5
+ import subprocess
6
+ import sys
7
+ import textwrap
8
+ from pathlib import Path
9
+
10
+ from blot.cli import main
11
+
12
+ ACTION = Path(__file__).resolve().parent.parent / "action.yml"
13
+
14
+
15
+ def _annotate_script() -> str:
16
+ """The Python heredoc in action.yml's "Run Blot" step (stdlib only, so no YAML parser needed)."""
17
+ lines = ACTION.read_text(encoding="utf-8").splitlines()
18
+ start = next(i for i, line in enumerate(lines) if line.strip() == "python - <<'PY'") + 1
19
+ end = next(i for i in range(start, len(lines)) if lines[i].strip() == "PY")
20
+ return textwrap.dedent("\n".join(lines[start:end])) + "\n"
21
+
22
+
23
+ def _annotate(tmp_path: Path, raw: str) -> list[str]:
24
+ findings = tmp_path / "findings.json"
25
+ findings.write_text(raw, encoding="utf-8")
26
+ out = subprocess.run([sys.executable, "-c", _annotate_script()], env={**os.environ, "BLOT_FINDINGS": str(findings)},
27
+ capture_output=True, text=True, check=True).stdout
28
+ return out.splitlines()
29
+
30
+
31
+ def test_findings_become_warning_annotations(tmp_path):
32
+ findings = [
33
+ {"check": "removed-fix", "path": "src/a,b.py", "line": 12, "severity": 2,
34
+ "message": "You're changing a line added by a bug fix: 100% sure.",
35
+ "evidence": ['8efea0cc "Break reference cycle" (2020-10-03, fixes #3761)']},
36
+ {"check": "forgot-related-file", "path": "app.py", "line": None, "severity": 1,
37
+ "message": "app.py usually changes with views.py.", "evidence": []},
38
+ ]
39
+ assert _annotate(tmp_path, json.dumps(findings)) == [
40
+ "::warning file=src/a%2Cb.py,line=12,title=blot%3A removed-fix::"
41
+ "You're changing a line added by a bug fix: 100%25 sure."
42
+ '%0A8efea0cc "Break reference cycle" (2020-10-03, fixes #3761)',
43
+ "::warning file=app.py,title=blot%3A forgot-related-file::app.py usually changes with views.py.",
44
+ "blot: 2 findings",
45
+ ]
46
+
47
+
48
+ def test_no_findings_and_no_output(tmp_path):
49
+ assert _annotate(tmp_path, "[]\n") == ["blot: 0 findings"]
50
+ assert _annotate(tmp_path, "") == ["blot: 0 findings"] # blot check hit an internal error
51
+
52
+
53
+ def test_range_check_of_a_pr_branch_is_annotated(make_repo, tmp_path, capsys):
54
+ from test_checks import AFTER, BEFORE, GUARD
55
+
56
+ repo = make_repo([("Add app", {"app.py": BEFORE}),
57
+ ("Break reference cycle in App (fixes #3761)", {"app.py": AFTER})])
58
+ git = lambda *args: subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True) # noqa: E731
59
+ git("switch", "-q", "-c", "pr")
60
+ (repo / "app.py").write_text(AFTER.replace(GUARD, "self_ref = self"), encoding="utf-8")
61
+ git("commit", "-q", "-am", "Simplify App")
62
+
63
+ assert main(["--repo", str(repo), "check", "--range", "main..HEAD", "--format", "json"]) == 0
64
+ lines = _annotate(tmp_path, capsys.readouterr().out)
65
+ assert lines[-1].startswith("blot: ") and lines[-1] != "blot: 0 findings"
66
+ assert any(line.startswith("::warning file=app.py,line=") and ",title=blot%3A removed-fix::" in line
67
+ for line in lines)
@@ -11,10 +11,26 @@ def test_registry_has_three_checks():
11
11
  assert [c.id for c in REGISTRY] == ["removed-fix", "readded-bug", "forgot-related-file"]
12
12
 
13
13
 
14
- def test_check_without_index_never_blocks(make_repo, capsys):
14
+ def test_check_builds_the_index_on_first_run_then_refreshes_it(make_repo, capsys):
15
+ import subprocess
16
+
17
+ from test_checks import AFTER, BEFORE, GUARD
18
+
15
19
  repo = make_repo([("feat: init", {"a.py": "x = 1\n"})])
16
20
  assert main(["--repo", str(repo), "check"]) == 0
17
- assert "run `blot index`" in capsys.readouterr().err
21
+ assert "first run, indexing" in capsys.readouterr().err
22
+ assert main(["--repo", str(repo), "check"]) == 0
23
+ assert capsys.readouterr().err == "" # already indexed: silent
24
+
25
+ # a fix committed after the first check must be known to the next one (incremental refresh)
26
+ for message, content in (("Add app", BEFORE), ("Break reference cycle in App (fixes #3761)", AFTER)):
27
+ (repo / "app.py").write_text(content, encoding="utf-8")
28
+ subprocess.run(["git", "-C", str(repo), "add", "-A"], check=True)
29
+ subprocess.run(["git", "-C", str(repo), "commit", "-q", "-m", message], check=True)
30
+ (repo / "app.py").write_text(AFTER.replace(GUARD, "self_ref = self"), encoding="utf-8")
31
+ subprocess.run(["git", "-C", str(repo), "add", "-A"], check=True)
32
+ assert main(["--repo", str(repo), "check"]) == 0
33
+ assert "removed-fix" in capsys.readouterr().out
18
34
 
19
35
 
20
36
  def test_render_text():
@@ -62,3 +78,25 @@ def test_removed_fix_traces_past_refactor(make_repo, capsys):
62
78
  # plain blame stops at the split; blot must cite the fix behind it
63
79
  assert finding["evidence"][0].startswith(sha("HEAD~1")[:7] + ' "Break reference cycle in App (fixes #3761)"')
64
80
  assert finding["evidence"][1].startswith("traced past refactor " + sha("HEAD")[:7])
81
+
82
+
83
+ def test_check_range_reads_removed_lines_at_the_base(make_repo, capsys):
84
+ """In CI the PR's commits are already in the index and HEAD no longer has the removed line."""
85
+ from test_checks import AFTER, BEFORE, GUARD
86
+
87
+ repo = make_repo([("Add app", {"app.py": BEFORE}),
88
+ ("Break reference cycle in App (fixes #3761)", {"app.py": AFTER})])
89
+ git = lambda *args: subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True) # noqa: E731
90
+ git("switch", "-q", "-c", "pr")
91
+ (repo / "app.py").write_text(AFTER.replace(GUARD, "self_ref = self"), encoding="utf-8")
92
+ git("commit", "-q", "-am", "Simplify App")
93
+ git("switch", "-q", "main")
94
+ (repo / "README.md").write_text("app\n", encoding="utf-8")
95
+ git("add", "README.md")
96
+ git("commit", "-q", "-m", "docs: readme") # main moves on, so A..B and A...B differ
97
+ git("switch", "-q", "pr")
98
+
99
+ for rev_range in ("HEAD~1..HEAD", "main...pr"):
100
+ assert main(["--repo", str(repo), "check", "--range", rev_range, "--format", "json"]) == 0
101
+ found = [(f["check"], f["path"], f["line"]) for f in json.loads(capsys.readouterr().out)]
102
+ assert ("removed-fix", "app.py", 3) in found, rev_range
@@ -0,0 +1,36 @@
1
+ import os
2
+ import subprocess
3
+
4
+ from blot.git import git_dir, head_sha, run_git
5
+
6
+
7
+ def test_head_sha_matches_git_in_every_ref_layout(make_repo, tmp_path, monkeypatch):
8
+ monkeypatch.delenv("GIT_DIR", raising=False)
9
+ repo = make_repo([("one", {"a.py": "x = 1\n"}), ("two", {"a.py": "x = 2\n"})])
10
+ rev = lambda path: run_git(str(path), "rev-parse", "HEAD").strip() # noqa: E731
11
+
12
+ assert head_sha(str(repo)) == rev(repo) # loose ref
13
+ run_git(str(repo), "pack-refs", "--all")
14
+ assert head_sha(str(repo)) == rev(repo) # packed-refs only
15
+ wt = tmp_path / "wt"
16
+ subprocess.run(["git", "-C", str(repo), "worktree", "add", "-q", "-b", "side", str(wt)], check=True)
17
+ assert head_sha(str(wt)) == rev(wt) # worktree: ref lives in the common dir
18
+ run_git(str(repo), "checkout", "-q", "--detach", "HEAD~1")
19
+ assert head_sha(str(repo)) == rev(repo) # detached HEAD
20
+ empty = tmp_path / "empty"
21
+ subprocess.run(["git", "init", "-q", str(empty)], check=True)
22
+ assert head_sha(str(empty)) is None # no commits yet
23
+
24
+
25
+ def test_git_dir_matches_git_from_root_subdir_and_worktree(make_repo, tmp_path, monkeypatch):
26
+ monkeypatch.delenv("GIT_DIR", raising=False)
27
+ repo = make_repo([("init", {"pkg/a.py": "x = 1\n"})])
28
+ expected = os.path.normcase(os.path.normpath(run_git(str(repo), "rev-parse", "--absolute-git-dir").strip()))
29
+
30
+ assert os.path.normcase(git_dir(str(repo))) == expected
31
+ assert os.path.normcase(git_dir(str(repo / "pkg"))) == expected
32
+
33
+ wt = tmp_path / "wt"
34
+ subprocess.run(["git", "-C", str(repo), "worktree", "add", "-q", str(wt)], check=True)
35
+ wt_expected = os.path.normcase(os.path.normpath(run_git(str(wt), "rev-parse", "--absolute-git-dir").strip()))
36
+ assert os.path.normcase(git_dir(str(wt))) == wt_expected
@@ -43,7 +43,7 @@ def test_real_commit_runs_hook_and_is_not_blocked(make_repo):
43
43
  subprocess.run(["git", "-C", str(repo), "add", "a.py"], check=True)
44
44
  done = subprocess.run(["git", "-C", str(repo), "commit", "-m", "change"], capture_output=True, text=True)
45
45
  assert done.returncode == 0
46
- assert "no index yet" in done.stderr # the hook really ran
46
+ assert "first run, indexing" in done.stderr # the hook really ran, and indexed the repo
47
47
 
48
48
 
49
49
  def test_uninstall_deletes_hook_blot_created(make_repo):
@@ -46,9 +46,8 @@ def test_why_traces_past_a_refactor(make_repo):
46
46
 
47
47
  def test_why_cli_and_errors(make_repo, capsys):
48
48
  repo = make_repo(history())
49
- assert main(["--repo", str(repo), "why", "core.py:1"]) == 1 # no index yet
50
- assert "run `blot index`" in capsys.readouterr().err
51
- main(["--repo", str(repo), "index", "--quiet"])
49
+ assert main(["--repo", str(repo), "why", "core.py:1"]) == 0 # builds the index itself
50
+ assert "first run, indexing" in capsys.readouterr().err
52
51
  assert main(["--repo", str(repo), "why", "missing.py:1"]) == 1
53
52
  assert "not tracked" in capsys.readouterr().err
54
53
  assert main(["--repo", str(repo), "why", "core.py:999"]) == 1
@@ -1,18 +0,0 @@
1
- import os
2
- import subprocess
3
-
4
- from blot.git import git_dir, run_git
5
-
6
-
7
- def test_git_dir_matches_git_from_root_subdir_and_worktree(make_repo, tmp_path, monkeypatch):
8
- monkeypatch.delenv("GIT_DIR", raising=False)
9
- repo = make_repo([("init", {"pkg/a.py": "x = 1\n"})])
10
- expected = os.path.normcase(os.path.normpath(run_git(str(repo), "rev-parse", "--absolute-git-dir").strip()))
11
-
12
- assert os.path.normcase(git_dir(str(repo))) == expected
13
- assert os.path.normcase(git_dir(str(repo / "pkg"))) == expected
14
-
15
- wt = tmp_path / "wt"
16
- subprocess.run(["git", "-C", str(repo), "worktree", "add", "-q", str(wt)], check=True)
17
- wt_expected = os.path.normcase(os.path.normpath(run_git(str(wt), "rev-parse", "--absolute-git-dir").strip()))
18
- assert os.path.normcase(git_dir(str(wt))) == wt_expected
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes