Skip to content

feat(ci): route static analysis through clang-tool-chain-tidy + fbuild compile DB (phase A of #2303) - #2307

Merged
zackees merged 3 commits into
masterfrom
feat-fbuild-clang-tool-chain-integration
Apr 18, 2026
Merged

zackees merged 3 commits into
masterfrom
feat-fbuild-clang-tool-chain-integration

Conversation

@zackees

@zackees zackees commented Apr 18, 2026 •

Copy link
Copy Markdown
Member

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-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 so ci-iwyu.py and future analysis tools can share it.
  • ci/ci-cppcheck.py 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 on CI runners. Matches the invocation pattern already used by bash lint --tidy (ci/lint/stage_impls.py:101-114).
  • Check selection is governed by the repo-root .clang-tidy (already enables bugprone-*, clang-analyzer-*, performance-*, selected modernize-* / readability-* — the cppcheck-equivalent families). Single source of truth; the script carries no inline --checks override.
  • Source filter preserved: the compile-DB loader filters entries to files under <project_root>/src/, matching the legacy pio check --src-filters=+<src/> scope.
  • Research memo ci/docs/fbuild-static-analysis-research.md documents the clang-tool-chain package 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-chain is already an installed transitive dependency at 1.2.9 (see Required-by: ci, fastled). No new package, no apt/brew install, no per-OS code path.
  • Same toolchain regardless of runner OS — Windows / macOS / Linux all go through the same bundled clang-tidy binary.
  • clang-tool-chain does not ship a cppcheck wrapper (confirmed in the research memo § 1). Staying inside the toolchain means clang-tidy, whose bugprone-* + clang-analyzer-* families are a strict superset of what pio check's cppcheck emitted for us in practice.
  • No CMake-configure coupling — clang-tidy reads compile_commands.json directly, so the huge_app.csv failure mode is structurally gone.

Relation to other PRs / issues

# State Relation
#2305 Open Short-term SKIP. Superseded by this PR — once this lands, the SKIP branch is dead code. Close #2305 when this merges.
#2301 Open Closed by this PR (fbuild static-analysis support).
#2302 Open Closed by this PR (esp32c2 regression).
#2303 Open Phase A. Phase B (IWYU migration onto the same clang-tool-chain-iwyu-tool -p <db-dir> pathway, reusing the compile-DB helper added here) is a follow-up PR.

Test plan

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores

    • CI now detects boards built with the alternative build system, obtains a compilation database when available, and runs clang-tool-chain based static analysis on project source files instead of skipping those boards.
  • Documentation

    • Added research and guidance on using build-system-generated compilation databases with clang tooling and recommended CI integration steps.

@coderabbitai

coderabbitai Bot commented Apr 18, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Detects fbuild-compiled boards, obtains or generates fbuild's compile_commands.json, filters translation units to files under src/, and runs clang-tool-chain-tidy -p <compile_db.parent>; failure to obtain the DB prints to stderr and exits 1, empty src set exits 0.

Changes

Cohort / File(s) Summary
fbuild compile database utilities
ci/util/fbuild_compiledb.py
New module with fbuild_release_dir(), was_compiled_with_fbuild(), and ensure_compile_commands() to locate or invoke fbuild ... --target compiledb and return the compile_commands.json path or None.
Static analysis integration
ci/ci-cppcheck.py
Added json import, updated `parse_args(argv: list[str]
Documentation / Research
ci/docs/fbuild-static-analysis-research.md
New research doc describing fbuild compile DB generation, clang-tool-chain CLI behavior, observed file locations, and a proposed integration plan for IWYU/clang tooling using fbuild's compile DB.

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
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly Related Issues

Possibly Related PRs

Poem

🐇 I dug through build dirs, sniffed compile commands fine,
I gathered src/ whispers, then lined them in a line.
I called tidy gently, watched the lints take flight,
CI sipped carrot tea — the rabbit danced with delight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 77.78% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(ci): route static analysis through clang-tool-chain-tidy + fbuild compile DB (phase A of #2303)' directly and clearly describes the main change: routing static analysis through a new tool (clang-tool-chain-tidy) using fbuild's compile database.
Linked Issues check ✅ Passed The PR successfully addresses the coding requirements from #2305: detects fbuild-compiled boards, implements the real analysis solution (clang-tool-chain-tidy via compile DB) instead of skipping, and filters source files to src/ scope as intended.
Out of Scope Changes check ✅ Passed All changes are scoped to the stated objectives: new fbuild compile DB helper module, cppcheck script refactoring for clang-tool-chain-tidy routing, and supporting documentation. No unrelated alterations detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat-fbuild-clang-tool-chain-integration

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 (or console) 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: redundant project_root (positional arg + cwd=).

subprocess.run passes str(project_root) as the PROJECT_DIR positional to fbuild AND sets cwd=str(project_root). Per the fbuild CLI (documented in the research doc), PROJECT_DIR is optional — fbuild resolves its project from the cwd when not provided. Passing both introduces redundancy; one source of truth is clearer. The --target compiledb flag 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

📥 Commits

Reviewing files that changed from the base of the PR and between a6e9513 and 7d3380e.

📒 Files selected for processing (5)
  • .github/workflows/build_template.yml
  • .github/workflows/build_template_custom_board.yml
  • ci/ci-cppcheck.py
  • ci/docs/fbuild-static-analysis-research.md
  • ci/util/fbuild_compiledb.py

Comment thread ci/ci-cppcheck.py Resolved
Comment thread ci/ci-cppcheck.py Resolved
@zackees zackees changed the title feat(ci): route cppcheck through fbuild compile_commands.json (phase A of #2303) feat(ci): route static analysis through clang-tool-chain-tidy + fbuild compile DB (phase A of #2303) Apr 18, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_args should accept an optional list[str] for testability.

Per coding guidelines, parse_args functions MUST accept an optional list[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 0 when 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 when entries is empty/unparseable, and only return 0 when entries existed but none were under src/. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d3380e and b9dc3ac.

📒 Files selected for processing (1)
  • ci/ci-cppcheck.py

Comment thread ci/ci-cppcheck.py Resolved
zackees added a commit that referenced this pull request Apr 18, 2026
…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]>
@zackees
zackees force-pushed the feat-fbuild-clang-tool-chain-integration branch from 3f2b84f to 54dde64 Compare April 18, 2026 14:44
@zackees

zackees commented Apr 18, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review — latest commit addresses both your earlier concerns: parse_args now accepts argv: list[str] | None for testability, and the fbuild missing-compile-DB path now fails fast with sys.stderr and exit code 1 (no more silent SKIP). Please re-review.

@coderabbitai

coderabbitai Bot commented Apr 18, 2026

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== ci/ci-cppcheck.py ==="
cat ci/ci-cppcheck.py

echo ""
echo "=== ci/util/fbuild_compiledb.py ==="
cat ci/util/fbuild_compiledb.py

Length of output: 12300


@zackees: Both fixes are confirmed in the latest code:

✅ Fix 1 — parse_args testability (Line 14, ci/ci-cppcheck.py)

def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    ...
    return parser.parse_args(argv)

The signature and pass-through to parser.parse_args(argv) are correct and align with the project-wide convention from the coding guidelines.

✅ Fix 2 — Fail-fast on missing compile DB (ci/ci-cppcheck.py)

if compile_db is None:
    print(
        f"ERROR: could not obtain fbuild compile_commands.json ...",
        file=sys.stderr,
    )
    return 1

Properly routes the error to sys.stderr and returns exit code 1. No more silent SKIP.


One minor residual item worth a quick look:

In ci/util/fbuild_compiledb.py, the failure message inside ensure_compile_commands still goes to stdout:

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.stderr

Since this is an error path (and the caller now treats None as a hard failure), it would be more consistent to also direct this to sys.stderr. Low priority, but worth fixing for log-scraping clarity.

Otherwise the logic looks solid: the compile_db.parent → -p routing is correct, _load_src_files_from_compile_db properly scopes to src/, and the was_compiled_with_fbuild detection matches the expected artifact layout.


🧠 Learnings used
Learnt from: CR
Repo: FastLED/FastLED PR: 0
File: .cursorrules:0-0
Timestamp: 2026-04-11T06:15:07.646Z
Learning: Applies to **/*.py : parse_args functions MUST accept an optional list[str] parameter for testing flexibility
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between b9dc3ac and 3f2b84f.

📒 Files selected for processing (1)
  • ci/ci-cppcheck.py

Comment thread ci/ci-cppcheck.py Resolved
…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]>
@zackees

zackees commented Apr 18, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review — latest commit 36d8eb9bd addresses your relative-path concern on the compile-DB loader: file fields are now resolved against the entry's directory per the JSON Compilation Database spec, with compile_db.parent as a safe fallback. All three prior review threads are resolved. Please re-review and clear the CHANGES_REQUESTED state if you have no remaining concerns.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
ci/ci-cppcheck.py (1)

112-128: ⚠️ Potential issue | 🟠 Major

Relative file entries are still resolved against CWD, not the entry's directory — and the downstream return 0 on empty set masks it.

Per the JSON Compilation Database spec, when file is relative it must be resolved against that entry's directory. Line 120's Path(raw).resolve() resolves against the process CWD instead. If fbuild emits any relative file entries (plausible, as fbuild's Rust emitter follows the standard spec), every such TU silently drops out of files, and then run_static_analysis_against_compile_db hits Line 148-154 and returns 0 — 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:
             continue

As 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f2b84f and 54dde64.

📒 Files selected for processing (3)
  • ci/ci-cppcheck.py
  • ci/docs/fbuild-static-analysis-research.md
  • ci/util/fbuild_compiledb.py

Comment thread ci/util/fbuild_compiledb.py Resolved
Comment thread ci/util/fbuild_compiledb.py Resolved
@coderabbitai

coderabbitai Bot commented Apr 18, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== ci/ci-cppcheck.py ==="
cat ci/ci-cppcheck.py

echo ""
echo "=== ci/util/fbuild_compiledb.py ==="
cat ci/util/fbuild_compiledb.py

Length of output: 12976


@zackees: All three review threads are confirmed resolved in the latest commit.

✅ Thread 1 — parse_args testability (ci/ci-cppcheck.py Line 14)

def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    ...
    return parser.parse_args(argv)

✅ Thread 2 — Fail-fast on missing compile DB (ci/ci-cppcheck.py)

if compile_db is None:
    print(f"ERROR: ...", file=sys.stderr)
    return 1

✅ Thread 3 — Relative-path resolution per JSON Compilation Database spec (ci/ci-cppcheck.py _load_src_files_from_compile_db)

if not raw_path.is_absolute():
    directory = entry.get("directory") or compile_db.parent
    raw_path = Path(directory) / raw_path

Correctly resolves relative file entries against the entry's own directory field (with compile_db.parent as the safe fallback), exactly as the spec requires. The OSError/ValueError guards for resolve() and relative_to() are a nice touch.


The one non-blocking residual from last time (error path in ensure_compile_commands still printing to stdout instead of sys.stderr) remains, but it was never a blocking thread — feel free to address it in a follow-up if/when it causes log-scraping noise.

No remaining concerns. Approving. 🎉

[approve]


🧠 Learnings used
Learnt from: CR
Repo: FastLED/FastLED PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-04-18T01:38:53.187Z
Learning: Run `/code-review` after making code changes to any files

…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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 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.py is invoked from the trusted/ subdirectory (not repo root). The subprocess.run() call at line 181 currently inherits that working directory. Meanwhile, ensure_compile_commands() explicitly runs fbuild with cwd=str(project_root) (line 75 in fbuild_compiledb.py). Adding cwd=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

📥 Commits

Reviewing files that changed from the base of the PR and between 54dde64 and 36d8eb9.

📒 Files selected for processing (1)
  • ci/ci-cppcheck.py

@zackees

zackees commented Apr 18, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review — commit 4a585c278 addresses both new concerns: project_root moved before build per canonical fbuild pattern, error routed to sys.stderr, and KeyboardInterrupt now re-raised ahead of the broader exception tuple. All 6 review threads resolved. Please re-review and clear CHANGES_REQUESTED if nothing else is outstanding.

@coderabbitai

coderabbitai Bot commented Apr 18, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== ci/ci-cppcheck.py ==="
cat ci/ci-cppcheck.py

echo ""
echo "=== ci/util/fbuild_compiledb.py ==="
cat ci/util/fbuild_compiledb.py

Length of output: 13534


@zackees: All three concerns are confirmed resolved in commit 4a585c278.

✅ Fix 1 — project_root before build per canonical fbuild pattern (ci/util/fbuild_compiledb.py)

["fbuild", str(project_root), "build", "-e", board_name, "--target", "compiledb"]

✅ Fix 2 — Error now routed to sys.stderr (ci/util/fbuild_compiledb.py)

print(
    f"ensure_compile_commands: failed to generate fbuild compile DB "
    f"for '{board_name}': {exc}",
    file=sys.stderr,
)

✅ Fix 3 — KeyboardInterrupt re-raised ahead of the broader exception tuple (ci/util/fbuild_compiledb.py)

except KeyboardInterrupt:
    raise
except (subprocess.CalledProcessError, FileNotFoundError) as exc:
    ...

All six threads are resolved. No remaining concerns. Approving. 🎉

[approve]


🧠 Learnings used
Learnt from: CR
Repo: FastLED/FastLED PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-04-18T01:38:53.187Z
Learning: Run `/code-review` after making code changes to any files

@zackees
zackees merged commit a516094 into master Apr 18, 2026
58 of 79 checks passed
@zackees zackees moved this to Triage in FastLED Tracker Apr 18, 2026
zackees added a commit that referenced this pull request Apr 19, 2026
…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]>
@zackees
zackees deleted the feat-fbuild-clang-tool-chain-integration branch November 5, 2026 05:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Triage

Development

Successfully merging this pull request may close these issues.

1 participant