Repository navigation
feat(ci): route static analysis through clang-tool-chain-tidy + fbuild compile DB (phase A of #2303) - #2307
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughDetects fbuild-compiled boards, obtains or generates fbuild's compile_commands.json, filters translation units to files under Changes
Sequence Diagram(s)sequenceDiagram
participant CI as CI script
participant FDB as fbuild_compiledb helper
participant Shell as subprocess / fbuild CLI
participant DB as compile_commands.json
participant Clang as clang-tool-chain-tidy
CI->>FDB: was_compiled_with_fbuild(build_root, board)
FDB-->>CI: true / false
alt fbuild compiled
CI->>FDB: ensure_compile_commands(project_root, build_root, board)
FDB-->>DB: return existing path OR
FDB->>Shell: run `fbuild ... --target compiledb`
Shell-->>FDB: exit status
FDB-->>CI: compile_commands.json path or None
alt compile DB found
CI->>CI: _load_src_files_from_compile_db(DB, project_root) -> [src files]
CI->>Clang: run `clang-tool-chain-tidy -p DB.parent` + filtered files
Clang-->>CI: exit code
else no compile DB
CI-->>CI: print error -> exit 1
end
else not fbuild compiled
CI->>CI: run legacy `pio check` flow
end
Estimated Code Review Effort🎯 3 (Moderate) | ⏱️ ~30 minutes Possibly Related Issues
Possibly Related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
ci/docs/fbuild-static-analysis-research.md (1)
75-103: Nit: add language tags to fenced code blocks (MD040).markdownlint flags the fences at lines 75, 86, and 98 as missing a language. They're CLI/help text snippets —
text(orconsole) is fine and silences the warning.-``` +```text $ fbuild build --help ...🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/docs/fbuild-static-analysis-research.md` around lines 75 - 103, The three fenced code blocks showing the fbuild help output, the list of built-in subcommands (starting with "fbuild clang-tidy ..."), and the filesystem tree (the block beginning with ".fbuild/build/<env>/release/") are missing language tags and trigger markdownlint MD040; add a language marker such as ```text or ```console to each fence to silence the warning and preserve CLI formatting..github/workflows/build_template.yml (1)
226-233: Nit: comment vs. code disagree about conditionality.The inline comment says "apt-install is cheap and idempotent enough to run unconditionally," but the command is actually gated by
! command -v cppcheck >/dev/null 2>&1. Either drop that sentence or reword to reflect that the install is guarded. Behavior itself is fine.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/build_template.yml around lines 226 - 233, Update the inline comment to match the actual guarded behavior: replace or reword the sentence saying "apt-install is cheap and idempotent enough to run unconditionally" to indicate the install is conditional (it only runs on Linux and only if cppcheck is not already present). Refer to the shell conditional `if [[ "$(uname -s)" == "Linux" ]] && ! command -v cppcheck >/dev/null 2>&1; then` and adjust the preceding comment so it accurately describes that the apt-get install is performed only when cppcheck is missing on Linux.ci/util/fbuild_compiledb.py (1)
63-76: Optional: redundantproject_root(positional arg +cwd=).
subprocess.runpassesstr(project_root)as thePROJECT_DIRpositional tofbuildAND setscwd=str(project_root). Per the fbuild CLI (documented in the research doc),PROJECT_DIRis optional — fbuild resolves its project from thecwdwhen not provided. Passing both introduces redundancy; one source of truth is clearer. The--target compiledbflag is stable in fbuild 2.1.12+.Suggested refactor
try: subprocess.run( [ "fbuild", "build", "-e", board_name, "--target", "compiledb", - str(project_root), ], check=True, cwd=str(project_root), )🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/util/fbuild_compiledb.py` around lines 63 - 76, The subprocess.run call that invokes fbuild currently passes str(project_root) both as the positional PROJECT_DIR argument and as cwd, causing redundant sources of truth; update the invocation in the code that builds the compiledb (the subprocess.run call in ci/util/fbuild_compiledb.py) to remove the positional str(project_root) from the args list and only rely on cwd=str(project_root) (leave "fbuild", "build", "-e", board_name, "--target", "compiledb" as the args and keep check=True and cwd=str(project_root)); this simplifies invocation and prevents mismatch between PROJECT_DIR and cwd.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ci/ci-cppcheck.py`:
- Around line 121-142: The function run_cppcheck_against_compile_db currently
masks a missing cppcheck by printing and returning 0 and builds the command
display via ' '.join(cmd); change it to fail fast with a non-zero exit (raise an
exception or call sys.exit(1)) and include a clear descriptive error message
when shutil.which("cppcheck") is None (refer to the check around
shutil.which("cppcheck")), and replace the debug display that uses ' '.join(cmd)
with subprocess.list2cmdline(cmd) when printing the command (refer to the cmd
variable and the f"Running cppcheck against compile DB: {compile_db}"/print of
the command); keep existing flags (compile_db, project_root,
f"--file-filter={project_root / 'src'}/*") unchanged.
- Line 137: The file-filter f-string in ci/ci-cppcheck.py uses project_root /
'src' which yields OS-native separators and can produce mixed backslashes on
Windows; update the construction that creates the file-filter (the
f"--file-filter=..." expression referencing project_root and 'src') to call
Path.as_posix() on the directory path so the glob uses forward slashes (e.g.,
convert (project_root / 'src') to its posix form before appending /*) ensuring
cppcheck's file-filter matches paths on Windows.
---
Nitpick comments:
In @.github/workflows/build_template.yml:
- Around line 226-233: Update the inline comment to match the actual guarded
behavior: replace or reword the sentence saying "apt-install is cheap and
idempotent enough to run unconditionally" to indicate the install is conditional
(it only runs on Linux and only if cppcheck is not already present). Refer to
the shell conditional `if [[ "$(uname -s)" == "Linux" ]] && ! command -v
cppcheck >/dev/null 2>&1; then` and adjust the preceding comment so it
accurately describes that the apt-get install is performed only when cppcheck is
missing on Linux.
In `@ci/docs/fbuild-static-analysis-research.md`:
- Around line 75-103: The three fenced code blocks showing the fbuild help
output, the list of built-in subcommands (starting with "fbuild clang-tidy
..."), and the filesystem tree (the block beginning with
".fbuild/build/<env>/release/") are missing language tags and trigger
markdownlint MD040; add a language marker such as ```text or ```console to each
fence to silence the warning and preserve CLI formatting.
In `@ci/util/fbuild_compiledb.py`:
- Around line 63-76: The subprocess.run call that invokes fbuild currently
passes str(project_root) both as the positional PROJECT_DIR argument and as cwd,
causing redundant sources of truth; update the invocation in the code that
builds the compiledb (the subprocess.run call in ci/util/fbuild_compiledb.py) to
remove the positional str(project_root) from the args list and only rely on
cwd=str(project_root) (leave "fbuild", "build", "-e", board_name, "--target",
"compiledb" as the args and keep check=True and cwd=str(project_root)); this
simplifies invocation and prevents mismatch between PROJECT_DIR and cwd.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 90e7f90b-f127-4693-93ef-cfffce122b1f
📒 Files selected for processing (5)
.github/workflows/build_template.yml.github/workflows/build_template_custom_board.ymlci/ci-cppcheck.pyci/docs/fbuild-static-analysis-research.mdci/util/fbuild_compiledb.py
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
ci/ci-cppcheck.py (1)
15-18: 🛠️ Refactor suggestion | 🟠 Major
parse_argsshould accept an optionallist[str]for testability.Per coding guidelines,
parse_argsfunctions MUST accept an optionallist[str]parameter for testing flexibility.✏️ Proposed change
-def parse_args() -> argparse.Namespace: +def parse_args(args: list[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser(description="Run cppcheck on the project") parser.add_argument("board", nargs="?", help="Board to check, optional") - return parser.parse_args() + return parser.parse_args(args)As per coding guidelines: parse_args functions MUST accept an optional list[str] parameter for testing flexibility.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/ci-cppcheck.py` around lines 15 - 18, The parse_args function must accept an optional list[str] parameter for testability; update the signature of parse_args (function name: parse_args) to accept an optional parameter like args: Optional[list[str]] = None (import Optional and list typing if needed) and pass that parameter into parser.parse_args(args) so callers/tests can supply arguments programmatically while keeping the existing default behavior.
🧹 Nitpick comments (1)
ci/ci-cppcheck.py (1)
147-154: Consider distinguishing "no src TUs" from "DB was empty/malformed".Returning
0when the filter yields no files is defensible for boards whose fbuild DB legitimately covers only framework code, but it also silently passes if the DB exists but contains no entries at all, or if every path fails to resolve (e.g. stale absolute paths from a different checkout on Windows CI). Consider at least differentiating: fail whenentriesis empty/unparseable, and only return0when entries existed but none were undersrc/. This keeps the legitimate "framework-only DB" case working while catching real breakage.Optional — not a blocker for this PR, but worth a follow-up given the intent to provide real coverage rather than a skip.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/ci-cppcheck.py` around lines 147 - 154, The current caller treats any empty result from _load_src_files_from_compile_db(compile_db, project_root) as a benign "no src TUs" and returns 0; change the logic so we distinguish a truly empty/malformed compile DB from a compile DB that contains entries but none under src/. Update _load_src_files_from_compile_db (or have it also return/raise metadata) so callers can detect "no entries parsed / parse error" versus "entries parsed but filtered to zero src files"; in the caller, when parsing failed or entries list is empty, print an error and return non‑zero, but when entries existed and filtering produced zero src TUs, keep the existing informational message and return 0. Ensure you reference the compile_db input and the returned files/entries values so the behavior is deterministic.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ci/ci-cppcheck.py`:
- Around line 194-205: The current branch in was_compiled_with_fbuild(...)
treats a missing fbuild compile DB from ensure_compile_commands(...) as success
by printing a WARN and returning 0; instead fail fast: when
ensure_compile_commands(...) returns None, log a descriptive error (use the
existing logger or print to stderr) and abort with a non-zero exit (e.g., raise
RuntimeError or call sys.exit(1)) rather than returning 0 so
run_static_analysis_against_compile_db(...) is not silently skipped; update the
block around ensure_compile_commands, keeping the same message text but elevate
it to an error and return a non-zero failure.
---
Outside diff comments:
In `@ci/ci-cppcheck.py`:
- Around line 15-18: The parse_args function must accept an optional list[str]
parameter for testability; update the signature of parse_args (function name:
parse_args) to accept an optional parameter like args: Optional[list[str]] =
None (import Optional and list typing if needed) and pass that parameter into
parser.parse_args(args) so callers/tests can supply arguments programmatically
while keeping the existing default behavior.
---
Nitpick comments:
In `@ci/ci-cppcheck.py`:
- Around line 147-154: The current caller treats any empty result from
_load_src_files_from_compile_db(compile_db, project_root) as a benign "no src
TUs" and returns 0; change the logic so we distinguish a truly empty/malformed
compile DB from a compile DB that contains entries but none under src/. Update
_load_src_files_from_compile_db (or have it also return/raise metadata) so
callers can detect "no entries parsed / parse error" versus "entries parsed but
filtered to zero src files"; in the caller, when parsing failed or entries list
is empty, print an error and return non‑zero, but when entries existed and
filtering produced zero src TUs, keep the existing informational message and
return 0. Ensure you reference the compile_db input and the returned
files/entries values so the behavior is deterministic.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: f9a1abf5-f6ed-4eb7-9a9b-0a175a6761c9
📒 Files selected for processing (1)
ci/ci-cppcheck.py
…fast on missing DB Two review fixes per CodeRabbit on PR #2307: - `parse_args` now accepts an optional `argv: list[str] | None` so callers can pass explicit argv for testing. Matches the project coding guideline for testable argparse entry points. - When `was_compiled_with_fbuild(...)` is true but `ensure_compile_commands(...)` returns None, exit 1 with a descriptive error rather than printing WARN and returning 0. Masking a real fbuild toolchain failure as success was exactly the short-term SKIP behavior this PR is meant to replace. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…d compile DB Supersedes the short-term SKIP from #2305 with real static-analysis coverage on fbuild-compiled boards, routed entirely through `clang-tool-chain-tidy` against fbuild's own compile database. No system-package dependency, no `pio check`, no PIO project tree. - New helper `ci/util/fbuild_compiledb.py` wraps `fbuild build -e <env> --target compiledb` (built into fbuild 2.1+). Emits `.build/.fbuild/build/<env>/release/compile_commands.json` without a full compile. Also lifts `was_compiled_with_fbuild()` out of `ci-cppcheck.py` (previously inline from #2305) so `ci-iwyu.py` and future analysis tools can share it. - `ci/ci-cppcheck.py` now branches on `was_compiled_with_fbuild()` and invokes `uv run clang-tool-chain-tidy -p <db-dir> <src/ files>` for fbuild boards. PIO-backed boards continue through `pio check` unchanged. `clang-tool-chain` lazily validates/fetches its bundled toolchain on first use, so no `apt-get install` is needed. Matches the invocation pattern at `ci/lint/stage_impls.py:101-114`. - `parse_args(argv: list[str] | None = None)` per testability guideline. Missing-DB path fails fast with stderr + exit 1 (per CodeRabbit: no silent fallback on missing critical resources). - Check selection is governed by the repo-root `.clang-tidy` — already enables the cppcheck-equivalent families (`bugprone-*`, `clang-analyzer-*`, `performance-*`). No inline `--checks` override. - Source filter preserved: compile-DB loader filters entries to files under `<project_root>/src/`, matching `pio check --src-filters=+<src/>`. - Research memo `ci/docs/fbuild-static-analysis-research.md` documents the `clang-tool-chain` API surface and fbuild's compile-DB behavior. Closes #2301 (fbuild static-analysis support), #2302 (esp32c2 regression). Phase A of #2303 — IWYU migration onto the same pathway lands in a follow-up PR. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
3f2b84f to
54dde64
Compare
|
@coderabbitai review — latest commit addresses both your earlier concerns: |
🧩 Analysis chain🏁 Script executed: Length of output: 12300
✅ Fix 1 — def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
...
return parser.parse_args(argv)The signature and pass-through to ✅ Fix 2 — Fail-fast on missing compile DB ( if compile_db is None:
print(
f"ERROR: could not obtain fbuild compile_commands.json ...",
file=sys.stderr,
)
return 1Properly routes the error to One minor residual item worth a quick look: In except (subprocess.CalledProcessError, FileNotFoundError) as exc:
print(
f"ensure_compile_commands: failed to generate fbuild compile DB "
f"for '{board_name}': {exc}"
) # ← no file=sys.stderrSince this is an error path (and the caller now treats Otherwise the logic looks solid: the 🧠 Learnings used✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
ci/ci-cppcheck.py (1)
156-169: Nit: echo the resolved command for debuggability.The previous cppcheck path printed the full command (via
subprocess.list2cmdline), which is invaluable when CI fails and you need to reproduce locally. Consider restoring that here.♻️ Suggested tweak
print( f"Running clang-tool-chain-tidy against {len(files)} src/ files using " f"compile DB: {compile_db}" ) cmd = [ "uv", "run", "clang-tool-chain-tidy", "-p", str(compile_db.parent), *files, ] + print(f" command: {subprocess.list2cmdline(cmd)}") cp = subprocess.run(cmd)As per coding guidelines: Use subprocess.list2cmdline() for all command line construction instead of string join.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/ci-cppcheck.py` around lines 156 - 169, Add a debug print of the fully-resolved command before executing it: use subprocess.list2cmdline(cmd) to format the cmd list and print it (alongside the existing message about files and compile_db) so that the exact command run by subprocess.run(cmd) (where cmd is defined and uses compile_db and files) is echoed for CI debugging and local reproduction.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ci/ci-cppcheck.py`:
- Around line 112-128: The loop that builds files from the compile database uses
Path(raw).resolve() which resolves relative paths against the process CWD;
instead, use the entry's "directory" field to resolve relative file entries per
the JSON Compilation Database spec: for each entry in the function reading the
compile DB, obtain entry.get("directory") (fall back to src_root or skip if
missing), construct Path(directory) / raw and then resolve that combined path
(catch OSError), ensure you still check relative_to(src_root) as before, and
append the resolved string; update the code around the entries loop where raw
and resolved are handled to use the entry "directory" for resolution.
---
Nitpick comments:
In `@ci/ci-cppcheck.py`:
- Around line 156-169: Add a debug print of the fully-resolved command before
executing it: use subprocess.list2cmdline(cmd) to format the cmd list and print
it (alongside the existing message about files and compile_db) so that the exact
command run by subprocess.run(cmd) (where cmd is defined and uses compile_db and
files) is echoed for CI debugging and local reproduction.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 0c09fb01-1490-40bf-89ee-844de7d167bc
📒 Files selected for processing (1)
ci/ci-cppcheck.py
…spec Per the JSON Compilation Database spec, the `file` field may be absolute or relative to the entry's `directory` field. The previous code used `Path(raw).resolve()` which resolves against the Python CWD, so a relative `file` would resolve incorrectly and be silently filtered out of the src/ list — potentially yielding zero TUs (and a success return) even though fbuild had actually emitted source entries. Fix: when `file` is relative, resolve it against the entry's `directory` (falling back to the compile DB's parent when `directory` is missing), matching what clang-tidy / clangd itself does. Addresses CodeRabbit on PR #2307 (ci/ci-cppcheck.py:128, fingerprint f24a46e1). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
@coderabbitai review — latest commit |
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
ci/ci-cppcheck.py (1)
112-128:⚠️ Potential issue | 🟠 MajorRelative
fileentries are still resolved against CWD, not the entry'sdirectory— and the downstreamreturn 0on empty set masks it.Per the JSON Compilation Database spec, when
fileis relative it must be resolved against that entry'sdirectory. Line 120'sPath(raw).resolve()resolves against the process CWD instead. If fbuild emits any relativefileentries (plausible, as fbuild's Rust emitter follows the standard spec), every such TU silently drops out offiles, and thenrun_static_analysis_against_compile_dbhits Line 148-154 and returns0— reporting "nothing to analyze" as success, which is exactly the skip-masquerading-as-pass failure mode this PR set out to eliminate.Root cause is here at line 120; the empty-set exit at 148-154 is the downstream amplifier. Consider also downgrading the empty-set branch to a non-zero return (or at minimum a WARN on stderr) once the resolution is correct, so a genuine empty DB still gets attention.
🛡️ Proposed fix
for entry in entries: raw = entry.get("file") if not raw: continue + raw_path = Path(raw) + if not raw_path.is_absolute(): + directory = entry.get("directory") + if directory: + raw_path = Path(directory) / raw_path try: - resolved = Path(raw).resolve() + resolved = raw_path.resolve() except OSError: continueAs per coding guidelines: Never use silent fallbacks for missing critical resources - always fail fast with descriptive errors.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/ci-cppcheck.py` around lines 112 - 128, The loop that builds files from the compilation database currently calls Path(raw).resolve(), which resolves relative paths against the process CWD instead of the compilation entry's "directory"; change the resolution to join the entry's "directory" with raw (e.g., Path(entry["directory"]) / raw) and then resolve that combined path before filtering with resolved.relative_to(src_root) in the same loop that reads entries from compile_db.open; additionally, update the downstream behavior in run_static_analysis_against_compile_db so that an empty files list does not silently return 0—either emit a warning/error to stderr or return a non-zero exit code to fail fast when no translation units are found.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ci/util/fbuild_compiledb.py`:
- Around line 77-82: The except block that catches subprocess.CalledProcessError
and FileNotFoundError should first explicitly handle KeyboardInterrupt by adding
an `except KeyboardInterrupt: raise` clause, then log the failure to stderr
instead of stdout; update the handler around the `ensure_compile_commands` call
in fbuild_compiledb.py (the except currently catching
(subprocess.CalledProcessError, FileNotFoundError) as exc) to use `print(...,
file=sys.stderr)` and add `import sys` at top if not present.
- Around line 64-76: The subprocess.run call in ci/util/fbuild_compiledb.py is
passing a redundant/misplaced positional argument (str(project_root)) at the end
of the args list; update the subprocess.run invocation used to run fbuild (the
call that builds the list
["fbuild","build","-e",board_name,"--target","compiledb", str(project_root)]) to
either remove the trailing str(project_root) since cwd=str(project_root) already
sets the working directory, or—if a positional project path is required—move
str(project_root) to immediately after "fbuild" to follow the repository's
canonical pattern; modify only the argument list used in that subprocess.run
call accordingly.
---
Duplicate comments:
In `@ci/ci-cppcheck.py`:
- Around line 112-128: The loop that builds files from the compilation database
currently calls Path(raw).resolve(), which resolves relative paths against the
process CWD instead of the compilation entry's "directory"; change the
resolution to join the entry's "directory" with raw (e.g.,
Path(entry["directory"]) / raw) and then resolve that combined path before
filtering with resolved.relative_to(src_root) in the same loop that reads
entries from compile_db.open; additionally, update the downstream behavior in
run_static_analysis_against_compile_db so that an empty files list does not
silently return 0—either emit a warning/error to stderr or return a non-zero
exit code to fail fast when no translation units are found.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: cb2396c8-b5bf-44b1-b3e7-11a5972bdea1
📒 Files selected for processing (3)
ci/ci-cppcheck.pyci/docs/fbuild-static-analysis-research.mdci/util/fbuild_compiledb.py
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 12976
✅ Thread 1 — def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
...
return parser.parse_args(argv)✅ Thread 2 — Fail-fast on missing compile DB ( if compile_db is None:
print(f"ERROR: ...", file=sys.stderr)
return 1✅ Thread 3 — Relative-path resolution per JSON Compilation Database spec ( if not raw_path.is_absolute():
directory = entry.get("directory") or compile_db.parent
raw_path = Path(directory) / raw_pathCorrectly resolves relative The one non-blocking residual from last time (error path in No remaining concerns. Approving. 🎉 [approve] 🧠 Learnings used |
…ardInterrupt Two CodeRabbit fixes on PR #2307: - Move `str(project_root)` to position 1 (before `build`), matching the canonical FastLED fbuild invocation pattern at `ci/util/fbuild_runner.py:104-114`: `[fbuild, <project_dir>, build, -e <env>, …]`. `cwd=str(project_root)` stays set so config discovery is identical regardless of whether the positional is honored by a given fbuild version. - Route the failure message to `sys.stderr` for stream consistency with the caller in `ci/ci-cppcheck.py`, and add an explicit `KeyboardInterrupt` re-raise ahead of the broader exception tuple so Ctrl-C can never be swallowed if the tuple is extended later. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
ci/ci-cppcheck.py (1)
173-182: Anchor the clang-tidy subprocess to the repo root for consistent tool discovery.In CI workflows,
ci-cppcheck.pyis invoked from thetrusted/subdirectory (not repo root). Thesubprocess.run()call at line 181 currently inherits that working directory. Meanwhile,ensure_compile_commands()explicitly runs fbuild withcwd=str(project_root)(line 75 infbuild_compiledb.py). Addingcwd=str(project_root)to the subprocess call aligns both code paths and ensures clang-tool-chain-tidy can reliably discover repo-root artifacts like.clang-tidy.🔧 Proposed change
- cp = subprocess.run(cmd) + cp = subprocess.run(cmd, cwd=str(project_root)) return cp.returncode🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/ci-cppcheck.py` around lines 173 - 182, The clang-tidy subprocess in ci-cppcheck.py currently calls subprocess.run(cmd) inheriting the caller cwd; update that call to pass cwd=str(project_root) so clang-tool-chain-tidy runs anchored at the repo root (matching ensure_compile_commands() behavior) — locate the subprocess.run(cmd) invocation and add the cwd argument referencing project_root to ensure .clang-tidy and other repo-root artifacts are discovered consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@ci/ci-cppcheck.py`:
- Around line 173-182: The clang-tidy subprocess in ci-cppcheck.py currently
calls subprocess.run(cmd) inheriting the caller cwd; update that call to pass
cwd=str(project_root) so clang-tool-chain-tidy runs anchored at the repo root
(matching ensure_compile_commands() behavior) — locate the subprocess.run(cmd)
invocation and add the cwd argument referencing project_root to ensure
.clang-tidy and other repo-root artifacts are discovered consistently.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 651f1403-baca-48ab-a955-1c683e384d95
📒 Files selected for processing (1)
ci/ci-cppcheck.py
|
@coderabbitai review — commit |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 13534
✅ Fix 1 — ["fbuild", str(project_root), "build", "-e", board_name, "--target", "compiledb"]✅ Fix 2 — Error now routed to print(
f"ensure_compile_commands: failed to generate fbuild compile DB "
f"for '{board_name}': {exc}",
file=sys.stderr,
)✅ Fix 3 — except KeyboardInterrupt:
raise
except (subprocess.CalledProcessError, FileNotFoundError) as exc:
...All six threads are resolved. No remaining concerns. Approving. 🎉 [approve] 🧠 Learnings used |
…ile DB Phase B of #2303: mirror the cppcheck migration (Phase A, #2307) for include-what-you-use. Board-mode IWYU now dispatches on `was_compiled_with_fbuild()` — fbuild-backed boards (esp32c2 today, more on deck) route through `clang-tool-chain-iwyu-tool -p <db-dir>` against fbuild's own compile database, skipping the `pio check --tool=include-what-you-use` pathway and its CMake-configure failure mode. PIO-backed boards continue through `run_iwyu_on_platformio_project` unchanged. Implementation: - New `run_iwyu_on_fbuild_compile_db(compile_db, project_root, args)` shells `uv run clang-tool-chain-iwyu-tool -p <db-dir> <src-files> -- <iwyu-flags>`. Reuses the same `ensure_compile_commands()` helper `ci-cppcheck.py` uses (`ci/util/fbuild_compiledb.py`), so one `fbuild build --target compiledb` invocation serves both tools. - `_load_src_files_from_compile_db()` filters compile-DB entries to `<project_root>/src/*`, matching the legacy `pio check --src-filters=+<src/>` scope. Relative `file` paths are resolved against the entry's `directory` field per the `JSON Compilation Database spec <https://clang.llvm.org/docs/JSONCompilationDatabase.html>`_. - Mapping files (`ci/iwyu/fastled.imp`, `ci/iwyu/stdlib.imp`) are forwarded via `-Xiwyu --mapping_file=<path>` so diagnostics match the PIO pathway exactly. - `parse_args(argv: list[str] | None = None)` for testability, matching the `ci-cppcheck.py` convention landed in #2307. - Missing compile DB on a detected fbuild board fails fast with a descriptive stderr message + exit 1 — no silent SKIP. `ci/iwyu_wrapper.py` (the custom per-file driver) stays in place for the header-scan mode; it's only the board-mode PIO branch that now has an fbuild-aware sibling. Closes #2303. Completes the `clang-tool-chain` integration umbrella: both cppcheck (#2307) and IWYU (this PR) now run from fbuild's compile_commands.json with zero PlatformIO dependency. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Phase A of #2303 — replace the short-term SKIP from #2305 with real static-analysis coverage on fbuild-compiled boards, routed entirely through
clang-tool-chain-tidyagainst fbuild's own compile database. No system-package dependency, nopio check, no PIO project tree.ci/util/fbuild_compiledb.pywrapsfbuild build -e <env> --target compiledb(built into fbuild 2.1+). Emits.build/.fbuild/build/<env>/release/compile_commands.jsonwithout a full compile. Also liftswas_compiled_with_fbuild()out ofci-cppcheck.pysoci-iwyu.pyand future analysis tools can share it.ci/ci-cppcheck.pybranches onwas_compiled_with_fbuild()and invokesuv run clang-tool-chain-tidy -p <db-dir> <src/ files>for fbuild boards. PIO-backed boards continue throughpio checkunchanged.clang-tool-chainlazily validates/fetches its bundled toolchain on first use, so noapt-get installis needed on CI runners. Matches the invocation pattern already used bybash lint --tidy(ci/lint/stage_impls.py:101-114)..clang-tidy(already enablesbugprone-*,clang-analyzer-*,performance-*, selectedmodernize-*/readability-*— the cppcheck-equivalent families). Single source of truth; the script carries no inline--checksoverride.<project_root>/src/, matching the legacypio check --src-filters=+<src/>scope.ci/docs/fbuild-static-analysis-research.mddocuments theclang-tool-chainpackage API (wrappers, Python entry points) and fbuild's compile-DB behavior. Kept in-tree because the IWYU / clang-tidy follow-ups will keep referring to it.Why clang-tool-chain-tidy (and not system cppcheck)
clang-tool-chainis already an installed transitive dependency at 1.2.9 (seeRequired-by: ci, fastled). No new package, no apt/brew install, no per-OS code path.clang-tool-chaindoes not ship a cppcheck wrapper (confirmed in the research memo § 1). Staying inside the toolchain means clang-tidy, whosebugprone-*+clang-analyzer-*families are a strict superset of whatpio check's cppcheck emitted for us in practice.compile_commands.jsondirectly, so thehuge_app.csvfailure mode is structurally gone.Relation to other PRs / issues
clang-tool-chain-iwyu-tool -p <db-dir>pathway, reusing the compile-DB helper added here) is a follow-up PR.Test plan
esp32c2workflow goes green on this branch. Previous master run was red: https://github.com/FastLED/FastLED/actions/runs/24598125268uno,teensy41,esp32dev) continue to runpio checkunchanged — no regression.uv run ruff check ci/ci-cppcheck.py ci/util/fbuild_compiledb.pyanduv run pyrightboth clean.🤖 Generated with Claude Code
Summary by CodeRabbit
Chores
Documentation