Skip to content

Commit ffdef70

Browse files
authored
feat: clang-tidy checks only changed lines and skips without a compilation database (#303)
* feat: clang-tidy checks only changed lines and skips without a compilation database - Report only diagnostics on the lines a commit adds or changes, using clang-tidy's --line-filter (so --fix is limited too). The lines come from the staged changes, or from PRE_COMMIT_FROM_REF...PRE_COMMIT_TO_REF for pre-push and run --from-ref/--to-ref. Every line is checked when a file has no changes (run --all-files) or outside git; --all-lines turns the filter off. - Without a compilation database, skip clang-tidy locally with a notice and fail when CI is set. clang-tidy's own compile_commands.json and compile_flags.txt lookup next to the files, -p and --extra-arg count as a database. - Also look in builddir/, cmake-build-*/, build-*/, build/*/ and out/build/*/ for compile_commands.json. - Treat all file types pre-commit tags as c/c++ (.mm, .ino, module units) as source files. * refactor: name the compile_commands.json literal once * perf: find compile_commands.json with os.scandir; time out a stuck git diff * refactor: split the compile_commands.json pattern search * fix: keep line filters exact and short for large commits - clang-tidy uses the first --line-filter name that ends the reported path, so list longer names first: "a.cpp" no longer takes the lines of "data.cpp" and hides its new warnings. - Give each parallel run only its own file's filter, and split a serial run into several commands when the filter would make the command line too long (Windows: 32,767 characters, Linux: 128 KiB per argument). - Report any OSError from starting clang-tidy as a failed hook instead of a traceback. * fix: check every line when the file on disk is not the diffed version The staged (or pushed) line numbers only fit the file clang-tidy reads when the two match. pre-commit hides unstaged changes during a commit, but a direct run, --files, or a push with uncommitted changes can differ: then check every line instead of filtering with lines that do not fit. * fix: do not read an added "++ " line as a diff file header An added line "++ i;" shows as "+++ i;" in the diff, which the parser took for the next file's header, so later hunks of the file were lost. Skip each hunk's lines by their counts. Also say in the docs that --fix applies the fixes of the reported problems, which can touch a nearby unchanged line. * refactor: move hunk skipping out of the diff parser Keeps _parse_added_lines simple (SonarCloud cognitive complexity) and covers a diff that ends inside a hunk. --------- Co-authored-by: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com>
1 parent ae4e8b3 commit ffdef70

10 files changed

Lines changed: 1229 additions & 55 deletions

File tree

‎AGENTS.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ A pre-commit hook repo that auto-installs and runs `clang-format` and `clang-tid
2626
| `pyproject.toml` | Build config, deps (`pip>=26.1`), dev deps, entry points |
2727
| `cpp_linter_hooks/util.py` | Installed-wheel check, PyPI version resolution + pip install (prefix matching, offline fallback) |
2828
| `cpp_linter_hooks/clang_format.py` | clang-format wrapper (`--verbose`, `--dry-run`) |
29-
| `cpp_linter_hooks/clang_tidy.py` | clang-tidy wrapper (`--compile-commands`, `--jobs`, `--fix`, `-quiet` + status-line filter, `--checks` repair, error hints) |
29+
| `cpp_linter_hooks/clang_tidy.py` | clang-tidy wrapper (`--compile-commands`, missing-database policy, `--jobs`, `--fix`, `--all-lines`, `-quiet` + status-line filter, `--checks` repair, error hints) |
30+
| `cpp_linter_hooks/changed_lines.py` | Added line ranges per file from `git diff` (staged changes, or `PRE_COMMIT_FROM_REF...PRE_COMMIT_TO_REF`) |
3031
| `.pre-commit-hooks.yaml` | Hook metadata for pre-commit framework |
3132
| `testing/` | Test fixtures (`main.c`, `good.c`, `.clang-format`, `.clang-tidy`, CMakeLists) |
3233
| `examples/` | Example configs (CMake, Meson, large-project scoping) |
@@ -44,7 +45,8 @@ bash testing/run.sh # Integration tests (full pre-commit pipeline)
4445

4546
- **Version resolution**: A wheel already installed in the hook environment (found by its `<name>-<version>.dist-info` directory in site-packages, e.g. from `additional_dependencies`, with its executable in the environment's scripts directory) is used without network access when it matches `--version` (exact or prefix) or when no `--version` is given. Otherwise the version is resolved dynamically from PyPI at runtime. No hardcoded version lists. Prefix match supported (`--version=20` → `20.1.8`).
4647
- **Return values**: All hooks return `tuple[int, str]` — `(retval, output)`, where `retval` is the tool's exit code (`0` on success, non-zero on failure; `--dry-run` auto-adds `--Werror` so formatting issues fail).
47-
- **clang-tidy compile DB**: Auto-detected from `build/`, `out/`, `cmake-build-debug/`, `_build/`. Override with `--compile-commands=<dir>`, disable with `--no-compile-commands`.
48+
- **clang-tidy compile DB**: Auto-detected from `build/`, `out/`, `cmake-build-debug/`, `_build/`, `builddir/`, then `cmake-build-*/`, `build-*/`, `build/*/`, `out/build/*/` (newest wins). Override with `--compile-commands=<dir>`, disable with `--no-compile-commands`. If none is found, no `-p`/`--extra-arg*` is given and clang-tidy finds no `compile_commands.json`/`compile_flags.txt` next to the files or in their parents, the hook skips clang-tidy (retval 0, message on stderr), or fails when `CI` is set.
49+
- **clang-tidy changed lines**: By default only diagnostics on added lines are reported, via clang-tidy's `--line-filter`, so `-fix` applies only the fixes of those diagnostics (a fix may still edit an unchanged line nearby). Files without added lines are not checked. If any passed file has no changes (`--all-files`), differs on disk from the diffed version (index or `PRE_COMMIT_TO_REF`), or git fails, every line is checked. `--all-lines` or a user `--line-filter` turns this off. Tests: `tests/conftest.py` disables this and the missing-database check by default; use the `real_changed_lines` / `real_compile_db_check` fixtures to test them.
4850
- **clang-tidy parallel**: `--jobs=N` runs per-file in parallel. Forced serial when `--export-fixes`, `-fix`, or `-fix-errors` is used.
4951
- **clang-tidy output**: Without `--verbose`, the hook adds `-quiet` (unless the user set it) and strips status lines (`N warnings generated.`, `Suppressed N warnings ...`, `Use -header-filter=...`, `[1/N] Processing file ...`). With `--verbose`, output is unchanged.
5052
- **clang-tidy check lists**: `--checks=` / `--warnings-as-errors=` lists that YAML split at commas are joined again, quotes inside the value are removed, and `--checks=<file>` (e.g. `.clang-tidy`) gets a note. Notes are appended to the output, which pre-commit shows when the hook fails.

‎README.md‎

Lines changed: 59 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,11 @@ repos:
2929
3030
Run `pre-commit install` once in each clone. `--style=file` loads the style from your
3131
`.clang-format` file, and clang-tidy reads your `.clang-tidy` file by itself. The clang-tidy hook
32-
needs a `compile_commands.json`, which it looks for in `build/` and a few other directories (see
33-
[Compilation database](https://github.com/cpp-linter/cpp-linter-hooks#compilation-database));
34-
leave it out if you only run clang-tidy in CI, for example with
35-
[cpp-linter-action](https://cpp-linter.github.io/cpp-linter-action/).
32+
reports only problems on the lines that your commit adds or changes (see
33+
[Only changed lines](https://github.com/cpp-linter/cpp-linter-hooks#only-changed-lines)). It needs
34+
a `compile_commands.json`, which it looks for in `build/` and a few other directories; without one
35+
it skips clang-tidy on your machine and fails in CI (see
36+
[Compilation database](https://github.com/cpp-linter/cpp-linter-hooks#compilation-database)).
3637

3738
## Usage
3839

@@ -163,6 +164,34 @@ The hook passes `-quiet` to clang-tidy and drops status lines such as `522 warni
163164
which count warnings in system headers that clang-tidy does not show. Add `--verbose` to `args` to
164165
keep clang-tidy's full output.
165166

167+
#### Only changed lines
168+
169+
By default the hook reports only the problems on lines that the commit adds or changes, so old
170+
warnings elsewhere in a file do not block your commit. It reads the changes with `git diff`:
171+
172+
- On `git commit` and `pre-commit run`: the staged changes.
173+
- With `pre-commit run --from-ref A --to-ref B` and in the `pre-push` stage: the changes between
174+
the two commits.
175+
176+
The hook passes these lines to clang-tidy's `--line-filter`, so `--fix` applies only the fixes
177+
for problems reported on those lines (a fix can still touch a nearby line, for example to add a
178+
closing brace). Compiler errors are always reported. Files with no added lines, such as a pure rename, are
179+
not checked.
180+
181+
The hook checks every line when the files it gets have no changes, for example with
182+
`pre-commit run --all-files` on a clean working tree, when a file on disk differs from the
183+
version the lines come from (unstaged changes in a direct run, or uncommitted changes on
184+
`pre-push`), or outside a git repository. To always check
185+
every line, for example in a manual stage, add `--all-lines`:
186+
187+
```yaml
188+
- id: clang-tidy
189+
args: [--all-lines]
190+
```
191+
192+
Checking only changed lines does not make clang-tidy faster: it still analyzes the whole file.
193+
See [Performance optimization](https://github.com/cpp-linter/cpp-linter-hooks#performance-optimization).
194+
166195
> [!NOTE]
167196
> Add `--fix` to `args` to automatically apply clang-tidy fixes in place (equivalent to
168197
> passing `-fix` to clang-tidy directly). This is **opt-in** and **not the default** because
@@ -187,9 +216,13 @@ For CMake or Meson projects, clang-tidy works best with a `compile_commands.json
187216
file that records the exact compiler flags used for each file. Without it, clang-tidy
188217
may report false positives from missing include paths or wrong compiler flags.
189218

190-
The hook auto-detects `compile_commands.json` in common build directories (`build/`,
191-
`out/`, `cmake-build-debug/`, `_build/`) and passes `-p <dir>` to clang-tidy
192-
automatically — no configuration needed for most projects:
219+
The hook auto-detects `compile_commands.json` in common build directories and passes `-p <dir>`
220+
to clang-tidy automatically — no configuration needed for most projects. It looks in `build/`,
221+
`out/`, `cmake-build-debug/`, `_build/` and `builddir/` first, then in `cmake-build-*/`,
222+
`build-*/`, `build/*/` and `out/build/*/` (CMake presets, Visual Studio), where the most recently
223+
written one wins. Without `-p`, clang-tidy also finds a `compile_commands.json` or
224+
`compile_flags.txt` next to each file or in its parent directories, so a database in the
225+
repository root works too.
193226

194227
```yaml
195228
repos:
@@ -207,7 +240,19 @@ To specify the build directory explicitly:
207240
args: [--compile-commands=build]
208241
```
209242

210-
To disable auto-detection (e.g. in a monorepo where auto-detect might pick the wrong database):
243+
When no compilation database is found, clang-tidy would report missing headers instead of
244+
problems in your code, so the hook:
245+
246+
- **skips clang-tidy on your machine** and passes. The message says how to generate the database;
247+
pre-commit shows it with `pre-commit run -v` or `verbose: true` on the hook.
248+
- **fails in CI**, when the `CI` environment variable is set (GitHub Actions, GitLab CI and most CI
249+
services set it), so a broken setup does not pass unnoticed.
250+
251+
The hook runs clang-tidy anyway when `args` tell it how to compile: `-p`, `--extra-arg` or
252+
`--extra-arg-before`.
253+
254+
To disable auto-detection and always run clang-tidy without a database (e.g. in a monorepo where
255+
auto-detect might pick the wrong database, or for code that needs no compiler flags):
211256

212257
```yaml
213258
- id: clang-tidy
@@ -264,6 +309,11 @@ or `-j`:
264309
> overwrites a shared `--export-fixes` file and fixes to the same header can collide. Add
265310
> `require_serial: true` to the hook to run it once for all files.
266311

312+
With LLVM 21 and older, clang-tidy enables the `clang-analyzer-*` checks by default unless your
313+
`Checks` start with `-*`, and they take most of its time: in our measurements on
314+
[fmt](https://github.com/fmtlib/fmt), more than 90%. LLVM 22 removed them from the defaults. If
315+
clang-tidy is slow and you do not need them, add `-clang-analyzer-*` to `Checks` in `.clang-tidy`.
316+
267317
Alternatively, if you want to run the hooks manually on only the changed files, you can use the following command:
268318

269319
```bash
@@ -278,7 +328,7 @@ This approach ensures that only modified files are checked, further speeding up
278328
> Use `-v` or `--verbose` in `args` to enable verbose output.
279329
> For `clang-format`, it shows the list of processed files.
280330
> For `clang-tidy`, it prints which `compile_commands.json` is being used (when auto-detected or explicitly set)
281-
> and keeps clang-tidy's full output, without `-quiet`.
331+
> and which lines are reported, and keeps clang-tidy's full output, without `-quiet`.
282332
> pre-commit shows this output only when the hook fails; add `verbose: true` to the hook to see it on every run.
283333

284334
```yaml

‎cpp_linter_hooks/changed_lines.py‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
"""Find the lines that a commit or push changes, using git."""
2+
3+
import codecs
4+
import os
5+
import re
6+
import subprocess
7+
from collections.abc import Iterator
8+
from pathlib import PurePath
9+
10+
# "@@ -12,3 +14,2 @@": the old side spans 3 lines; the new side starts at line
11+
# 14 and spans 2 lines. A missing count means 1.
12+
HUNK_HEADER = re.compile(r"^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
13+
14+
LineRanges = list[list[int]]
15+
16+
17+
def diff_range() -> list[str]:
18+
"""Return the git diff arguments for the changes being checked.
19+
20+
pre-commit and prek set PRE_COMMIT_FROM_REF and PRE_COMMIT_TO_REF for
21+
``run --from-ref ... --to-ref ...`` and for the pre-push stage. Otherwise
22+
the hook checks a commit, so the changes are the staged ones.
23+
"""
24+
from_ref = os.environ.get("PRE_COMMIT_FROM_REF")
25+
to_ref = os.environ.get("PRE_COMMIT_TO_REF")
26+
if from_ref and to_ref:
27+
return [f"{from_ref}...{to_ref}"]
28+
return ["--cached"]
29+
30+
31+
def _git_diff(args: list[str]) -> str | None:
32+
"""Run ``git diff`` and return its output, or None if git fails."""
33+
command = [
34+
"git",
35+
"-c",
36+
"core.quotePath=false",
37+
"diff",
38+
"--relative",
39+
"--no-color",
40+
"--no-ext-diff",
41+
*args,
42+
]
43+
try:
44+
sp = subprocess.run(command, capture_output=True, check=False, timeout=60)
45+
except (OSError, subprocess.TimeoutExpired):
46+
return None
47+
if sp.returncode != 0:
48+
return None
49+
return sp.stdout.decode("utf-8", errors="surrogateescape")
50+
51+
52+
def normalize(path: str) -> str:
53+
"""Return a path in the form git prints it, relative and with "/"."""
54+
# PurePath also drops "./" segments.
55+
return PurePath(path).as_posix()
56+
57+
58+
def _unquote_path(path: str) -> str:
59+
"""Undo git's C-style quoting of unusual file names."""
60+
if len(path) >= 2 and path[0] == path[-1] == '"':
61+
raw = codecs.escape_decode(path[1:-1].encode("utf-8"))[0]
62+
return raw.decode("utf-8", errors="surrogateescape")
63+
return path
64+
65+
66+
def _count(group: str | None) -> int:
67+
"""Return a hunk header's line count, which is 1 when git leaves it out."""
68+
return 1 if group is None else int(group)
69+
70+
71+
def _skip_hunk_body(lines: Iterator[str], count: int) -> None:
72+
"""Consume the next count lines of a hunk.
73+
74+
They are skipped, not parsed, because an added line such as "++ i;"
75+
looks like a "+++ " file header. "\\ No newline at end of file" is not
76+
one of the hunk's lines.
77+
"""
78+
while count > 0:
79+
line = next(lines, None)
80+
if line is None:
81+
return
82+
if line[:1] in ("+", "-", " "):
83+
count -= 1
84+
85+
86+
def _parse_added_lines(diff: str) -> dict[str, LineRanges]:
87+
"""Return the added line ranges of each file in a ``git diff -U0`` output."""
88+
ranges: dict[str, LineRanges] = {}
89+
current: LineRanges | None = None
90+
lines = iter(diff.splitlines())
91+
for line in lines:
92+
if line.startswith("+++ "):
93+
name = _unquote_path(line[4:].rstrip("\t"))
94+
current = (
95+
None
96+
if name == "/dev/null"
97+
else ranges.setdefault(name.removeprefix("b/"), [])
98+
)
99+
continue
100+
match = HUNK_HEADER.match(line)
101+
if match is None:
102+
continue
103+
start, count = int(match.group(2)), _count(match.group(3))
104+
if count > 0 and current is not None:
105+
current.append([start, start + count - 1])
106+
_skip_hunk_body(lines, _count(match.group(1)) + count)
107+
return ranges
108+
109+
110+
def changed_lines(files: list[str]) -> dict[str, LineRanges] | None:
111+
"""Return the added line ranges of each file, keyed by the given path.
112+
113+
Returns None when the changed lines are unknown and every line should be
114+
checked: outside a git repository, when a file has no changes, which
115+
means the hook runs on files that were not changed (``--all-files`` or
116+
``--files``), or when a file on disk differs from the version the lines
117+
come from, so the line numbers would not match what clang-tidy reads. A
118+
file that is changed but has no added lines, for example a pure rename,
119+
maps to an empty list.
120+
"""
121+
if not files:
122+
return None
123+
revisions = diff_range()
124+
names = _git_diff(["--name-only", "-z", *revisions])
125+
if names is None:
126+
return None
127+
changed = set(names.split("\0"))
128+
normalized = {path: normalize(path) for path in files}
129+
if any(name not in changed for name in normalized.values()):
130+
return None
131+
# pre-commit hides unstaged changes during a commit, so the files on disk
132+
# match the index. A direct run, --files or a push with uncommitted
133+
# changes can leave them different from the diffed version.
134+
diffed_version = (
135+
[] if revisions == ["--cached"] else [os.environ["PRE_COMMIT_TO_REF"]]
136+
)
137+
if _git_diff(["--quiet", *diffed_version, "--", *files]) is None:
138+
return None
139+
140+
diff = _git_diff(["-U0", "--src-prefix=a/", "--dst-prefix=b/", *revisions])
141+
if diff is None:
142+
return None
143+
added = _parse_added_lines(diff)
144+
return {path: added.get(name, []) for path, name in normalized.items()}

0 commit comments

Comments
 (0)