Skip to content

refactor(ci): decouple IWYU + cppcheck from PIO project tree (#2303) - #2331

Merged
zackees merged 3 commits into
masterfrom
feat/iwyu-fbuild-compiledb-2303
Apr 19, 2026
Merged

zackees merged 3 commits into
masterfrom
feat/iwyu-fbuild-compiledb-2303

Conversation

@zackees

@zackees zackees commented Apr 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Makes fbuild a first-class backend for IWYU and cppcheck static analysis so fbuild-only boards (esp32c2 today, more coming) no longer break CI. Closes the IWYU half of #2303 (the cppcheck half landed in #2307).

  • ci/util/fbuild_adapter.py: add get_compile_commands(board) as the stable, public entry point static-analysis tools use to get an fbuild-produced compile_commands.json.
  • ci/util/fbuild_compiledb.py: probe all three real-world release-dir layouts (.build/pio/<board>/.fbuild/..., <repo>/.fbuild/..., .build/.fbuild/...) instead of only the theoretical one. The prior detector silently missed FastLED-orchestrated fbuild builds.
  • ci/ci-iwyu.py: when was_compiled_with_fbuild() is true, drive IWYU via clang-tool-chain-iwyu-tool -p <db-dir> scoped to src/ TUs (matching ci-cppcheck's scoping) — Windows CreateProcess can't handle the full aggregated argv of a raw ESP32 compile DB. The PIO path is preserved for non-fbuild boards and extended to understand the modern .build/pio/<board>/ layout.

Extension point

Adding future clang-tool-chain-* wrappers (clang-tidy, clang-format-check, clang-query) is ~10 LOC — wire the wrapper name, point it at compile_db.parent via -p, and pass the src-filtered file list. Documented inline in run_iwyu_against_compile_db.

Test plan

  • uv run python ci/ci-iwyu.py esp32c2 exits 0 (was failing with "No platformio.ini found")
  • uv run python ci/ci-cppcheck.py esp32c2 exits 0
  • Synthetic-src-entry probe confirms iwyu-tool actually processes src/ TUs when the compile DB contains them (fbuild's --target compiledb currently emits framework-only on ESP32, so this is a future-proofing measure)
  • PIO-backed boards: was_compiled_with_fbuild() returns False; legacy find_platformio_project_dir() path still dispatches correctly
  • bash lint ci/ci-iwyu.py ci/ci-cppcheck.py ci/util/fbuild_adapter.py ci/util/fbuild_compiledb.py — all checks pass
  • Ruff + pyright clean (no new errors introduced)

Related: #2301 (cppcheck subset), #2302 (esp32c2 regression), #2307 (phase A — cppcheck).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Run IWYU using a generated compile_commands.json so projects built with the fbuild workflow can be analyzed.
  • Chores
    • Improved detection of build/output layouts (multiple fbuild and PlatformIO layouts) when locating build artifacts.
    • More reliable discovery/generation of compilation databases for analysis tools.
    • Tool now reports that automatic --fix is not supported for fbuild-backed builds.

Make fbuild a first-class backend for static analysis so fbuild-only
boards (esp32c2 today, more coming) no longer break IWYU/cppcheck.

- ci/util/fbuild_adapter.py: add get_compile_commands(board) as the
  stable, public entry point for static-analysis tools to obtain an
  fbuild-produced compile_commands.json.
- ci/util/fbuild_compiledb.py: probe all three real-world release-dir
  layouts (.build/pio/<board>/.fbuild/..., <repo>/.fbuild/...,
  .build/.fbuild/...) instead of only the theoretical one. The prior
  detector silently missed FastLED-orchestrated fbuild builds.
- ci/ci-iwyu.py: when was_compiled_with_fbuild() is true, drive IWYU
  via clang-tool-chain-iwyu-tool -p <db-dir> scoped to src/ TUs
  (matching ci-cppcheck's scoping) — Windows CreateProcess can't handle
  the full aggregated argv of a raw ESP32 compile DB. The PIO path is
  preserved verbatim for non-fbuild boards and extended to understand
  the modern .build/pio/<board>/ layout.

Adding future clang-tool-chain wrappers (clang-tidy, clang-format-check,
clang-query) is ~10 LOC — wire the wrapper name, point it at
compile_db.parent via -p, and pass the src-filtered file list.

Verified on esp32c2: both ci-iwyu.py esp32c2 and ci-cppcheck.py esp32c2
now exit 0 without requiring a platformio.ini. Synthetic-src-entry probe
confirms iwyu-tool actually processes src/ TUs when the compile DB
contains them.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 18, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds fbuild-aware compile_commands discovery and IWYU invocation: loads and filters translation units from fbuild-generated compile_commands.json, runs IWYU with mapped flags, and broadens fbuild vs PlatformIO build artifact detection and compile-db retrieval.

Changes

Cohort / File(s) Summary
IWYU CI Integration
ci/ci-iwyu.py
Add _load_src_files_from_compile_db() and run_iwyu_against_compile_db(); update main() to normalize board aliases, detect fbuild-backed boards, obtain/use compile_commands.json, run IWYU (report that --fix is unsupported for fbuild), and expand PlatformIO build-dir lookup (.build/pio/<board> and .build/<board>).
FBuild Compile DB Adapter
ci/util/fbuild_adapter.py
Add get_compile_commands(board, build_root=None) as a stable public accessor that delegates to ensure_compile_commands.
FBuild Compile DB Discovery
ci/util/fbuild_compiledb.py
Add _candidate_fbuild_release_dirs() and _find_existing_compile_db(); make fbuild_release_dir() choose among candidates; change was_compiled_with_fbuild() to scan candidates; update ensure_compile_commands() to return existing DBs from candidates, invoke fbuild ... --target compiledb when missing, and re-scan after generation.

Sequence Diagram

sequenceDiagram
    participant CI as CI Script
    participant Board as Board Resolver
    participant CompDB as Compile DB Discovery
    participant FBuild as FBuild Adapter
    participant SrcFiles as Src Loader
    participant IWYU as IWYU Tool

    CI->>Board: normalize board alias
    CI->>CompDB: was_compiled_with_fbuild(build_root, board)
    alt fbuild-backed
        CI->>FBuild: get_compile_commands(board)
        FBuild->>CompDB: ensure_compile_commands(project_root, build_root, board)
        CompDB-->>FBuild: return compile_commands.json
        FBuild-->>CI: return compile_commands.json
        CI->>SrcFiles: _load_src_files_from_compile_db(compile_db, project_root)
        SrcFiles-->>CI: filtered src/* translation units
        CI->>IWYU: run_iwyu_against_compile_db(compile_db, project_root, args)
        IWYU-->>CI: exit code
    else PlatformIO
        CI->>CI: find build dir (.build/pio/<board> or .build/<board>)
        CI->>IWYU: run IWYU against PlatformIO build
        IWYU-->>CI: exit code
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Poem

🐇 I hopped through build dirs, leaf and log,
Found compile commands beneath the fog,
IWYU reads each source I bring,
Mapping flags and files in spring,
A rabbit cheers for tidy include logs!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main objective: decoupling IWYU and cppcheck from PIO project tree by adding fbuild support. It is concise, specific, and clearly conveys the primary change.
Docstring Coverage ✅ Passed Docstring coverage is 90.91% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/iwyu-fbuild-compiledb-2303

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 (2)
ci/util/fbuild_compiledb.py (1)

33-39: repo_root derivation is fragile — caller could pass an arbitrary build_root.

The name-based heuristic build_root.parent if build_root.name == ".build" else build_root silently collapses two candidates into one when build_root isn't named .build/. For example, if get_compile_commands(board, build_root=Path("/tmp/ci-build")) is ever called, repo_root becomes /tmp/ci-build, so the standalone-CLI candidate at line 37 degenerates to the same location as line 38's fallback, and the real <repo>/.fbuild/... layout will never be probed.

Since fbuild_adapter.get_compile_commands() already computes project_root independently, a more robust signature would pass project_root through to this helper rather than re-deriving it from build_root's name. Low priority given current call sites all use .build/, but worth a follow-up to avoid surprises as callers multiply.

🤖 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 33 - 39, The repo_root derivation
using build_root.name is fragile; change the helper that builds the candidate
paths (the code computing repo_root and returning the three paths) to accept an
explicit project_root (or project_root: Path | None) and use project_root as
repo_root when provided instead of the name-based heuristic, falling back to the
existing build_root.parent logic only if project_root is None; update callers
(notably fbuild_adapter.get_compile_commands) to pass its computed project_root
into this helper so the standalone CLI candidate and fallback no longer collapse
when build_root isn't named ".build".
ci/util/fbuild_adapter.py (1)

33-33: Default parameter value conflicts with repo Python guideline.

build_root: Path | None = None uses a default, but the repo guideline states parameters must not have defaults. Consider making build_root required (callers already know their .build/ directory) or splitting into two entry points.

Noting that existing helpers in this file (fbuild_build_and_upload, fbuild_build_only) already violate the same rule, so this may be a codebase-wide exception — but since this is a new public API, it's worth aligning before downstream tools adopt the signature.

As per coding guidelines: "All function parameters MUST have explicit type annotations and MUST NOT have default values".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/util/fbuild_adapter.py` at line 33, The function get_compile_commands
currently declares an optional default parameter build_root: Path | None = None
which violates the repo guideline that parameters must not have default values;
change the signature of get_compile_commands to require build_root (e.g.,
build_root: Path | None without a default) so callers must pass the build root,
or alternatively provide two explicit entry points (one requiring build_root and
one short wrapper) and update any call sites; also align related helpers
fbuild_build_and_upload and fbuild_build_only to the same rule if they are part
of the public API.
🤖 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-iwyu.py`:
- Around line 534-539: The except block for subprocess.CalledProcessError is
unreachable because subprocess.run is called without check=True; update the call
to subprocess.run(cmd, check=True) so it will raise CalledProcessError on
non-zero exits, then add an except KeyboardInterrupt: handler before the except
subprocess.CalledProcessError as e: handler to ensure Ctrl-C isn't swallowed; in
the CalledProcessError handler log/print the error.returncode (and/or error) and
return e.returncode as before.
- Around line 805-819: The bare except Exception swallows real failures from
create_board and masks board-resolution errors; change the fallback to fail fast
by either catching only specific expected errors (e.g., ImportError or a
create_board-specific error) or re-raising a descriptive error. Concretely, keep
the KeyboardInterrupt handling, then replace the broad except Exception with
either: (a) except ImportError as e / except SomeBoardResolutionError as e and
handle those cases explicitly, or (b) catch Exception as e and raise a new
RuntimeError(f"Failed to resolve board '{args.board}': {e}") from e so failures
in create_board (referenced symbol: create_board, canonical_board_name,
args.board) are not silently ignored and downstream checks like
was_compiled_with_fbuild(...) receive correct canonical names.

---

Nitpick comments:
In `@ci/util/fbuild_adapter.py`:
- Line 33: The function get_compile_commands currently declares an optional
default parameter build_root: Path | None = None which violates the repo
guideline that parameters must not have default values; change the signature of
get_compile_commands to require build_root (e.g., build_root: Path | None
without a default) so callers must pass the build root, or alternatively provide
two explicit entry points (one requiring build_root and one short wrapper) and
update any call sites; also align related helpers fbuild_build_and_upload and
fbuild_build_only to the same rule if they are part of the public API.

In `@ci/util/fbuild_compiledb.py`:
- Around line 33-39: The repo_root derivation using build_root.name is fragile;
change the helper that builds the candidate paths (the code computing repo_root
and returning the three paths) to accept an explicit project_root (or
project_root: Path | None) and use project_root as repo_root when provided
instead of the name-based heuristic, falling back to the existing
build_root.parent logic only if project_root is None; update callers (notably
fbuild_adapter.get_compile_commands) to pass its computed project_root into this
helper so the standalone CLI candidate and fallback no longer collapse when
build_root isn't named ".build".
🪄 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: f5b5e5c4-2915-4bd7-a181-1c42e036ad10

📥 Commits

Reviewing files that changed from the base of the PR and between 2230aa4 and 354e7e6.

📒 Files selected for processing (3)
  • ci/ci-iwyu.py
  • ci/util/fbuild_adapter.py
  • ci/util/fbuild_compiledb.py

Comment thread ci/ci-iwyu.py Resolved
Comment thread ci/ci-iwyu.py Resolved
…ution errors

Two CodeRabbit findings on #2331:

1. run_iwyu_against_compile_db: subprocess.run was called without
   check=True, so the CalledProcessError handler was unreachable —
   non-zero exits silently returned the code with no diagnostic. Add
   check=True so the handler runs, and add a KeyboardInterrupt branch
   above it (matching the existing pattern around create_board) so
   Ctrl-C isn't swallowed by the broader except.

2. main(): the bare `except Exception: canonical_board_name = args.board`
   silently masked every failure of ci.boards.create_board (ImportError,
   unknown board, registry bug). Re-raise as RuntimeError with context
   so the failure surfaces at the call site instead of feeding a bad
   canonical name to was_compiled_with_fbuild().

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.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
ci/ci-iwyu.py (1)

859-870: ⚠️ Potential issue | 🟡 Minor

Include modern .build/pio/* boards in the “Available boards” output.

The resolver checks .build/pio/<board>, but the failure message only lists immediate .build children, so modern PIO builds show pio instead of the available board names.

🧹 Proposed fix
         print(f"Board {args.board} not found in {build}")
         print("Available boards:")
         for d in build.iterdir():
             if d.is_dir():
                 print(f"  {d.name}")
+        pio_root = build / "pio"
+        if pio_root.exists():
+            for d in pio_root.iterdir():
+                if d.is_dir():
+                    print(f"  pio/{d.name}")
         return 1
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/ci-iwyu.py` around lines 859 - 870, The available-boards printout only
lists immediate children of build, missing boards under the PIO layout; update
the logic around candidate_dirs/board_dir (and the failure branch that uses
build.iterdir()) to also include entries from build / "pio" when printing
available boards (e.g., iterate both build.iterdir() and (build /
"pio").iterdir() if the pio dir exists) so that .build/pio/* board names are
shown when args.board lookup fails.
🧹 Nitpick comments (1)
ci/ci-iwyu.py (1)

21-21: Use the fbuild adapter as the public compile DB entry point.

This path still reaches into ci.util.fbuild_compiledb.ensure_compile_commands(...), even though this PR introduces ci.util.fbuild_adapter.get_compile_commands(board) as the stable static-analysis API. Keeping IWYU on the adapter avoids re-coupling this script to fbuild layout details.

♻️ Proposed refactor
-from ci.util.fbuild_compiledb import ensure_compile_commands, was_compiled_with_fbuild
+from ci.util.fbuild_adapter import get_compile_commands
+from ci.util.fbuild_compiledb import was_compiled_with_fbuild
...
-        compile_db = ensure_compile_commands(_PROJECT_ROOT, build, canonical_board_name)
+        compile_db = get_compile_commands(canonical_board_name)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/ci-iwyu.py` at line 21, The script currently imports and calls
ci.util.fbuild_compiledb.ensure_compile_commands(...) (and also references
was_compiled_with_fbuild), but the new public API is
ci.util.fbuild_adapter.get_compile_commands(board); change the import to
get_compile_commands from ci.util.fbuild_adapter and replace uses of
ensure_compile_commands(...) with get_compile_commands(board) (keeping
was_compiled_with_fbuild only if still needed), ensuring you pass the same
board/context argument and adapt any return handling to the adapter's return
shape.
🤖 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-iwyu.py`:
- Around line 845-854: The print that warns "--fix is not yet supported for
fbuild-backed boards" is currently gated by "result_code == 0" so the note is
omitted when IWYU reports violations; remove that guard and print the warning
whenever "args.fix" is true (i.e., evaluate "if args.fix:" alone), keeping the
same stderr output and then proceed to "return result_code"; this change touches
the block around "if args.fix and result_code == 0:" in ci/ci-iwyu.py—replace
that condition with "if args.fix:" so the message is always emitted when --fix
is requested.
- Around line 496-500: The loop that builds mapping_args currently skips missing
built-in IWYU mapping files (fastled.imp, stdlib.imp) which silently changes
behavior; change it to fail fast: for each name in ("fastled.imp", "stdlib.imp")
compute p = project_root / "ci" / "iwyu" / name, and if p.exists() is False
raise or sys.exit with a descriptive error that includes the missing filename
and its expected path (referencing mapping_args, project_root, and the name
variable) instead of silently continuing; only extend mapping_args when the file
exists.
- Around line 518-535: The call to subprocess.run in run_iwyu_against_compile_db
(the block building cmd and calling subprocess.run(cmd, check=True)) can raise
FileNotFoundError if the external `uv` binary is missing; wrap the
subprocess.run call in a try/except that catches FileNotFoundError and fails
cleanly with a clear diagnostic (e.g., use processLogger.error or raise
SystemExit with a message explaining that `uv`/clang-tool-chain-iwyu-tool is not
found and suggesting installing or using system include-what-you-use), so the
failure is reported instead of crashing silently.

---

Outside diff comments:
In `@ci/ci-iwyu.py`:
- Around line 859-870: The available-boards printout only lists immediate
children of build, missing boards under the PIO layout; update the logic around
candidate_dirs/board_dir (and the failure branch that uses build.iterdir()) to
also include entries from build / "pio" when printing available boards (e.g.,
iterate both build.iterdir() and (build / "pio").iterdir() if the pio dir
exists) so that .build/pio/* board names are shown when args.board lookup fails.

---

Nitpick comments:
In `@ci/ci-iwyu.py`:
- Line 21: The script currently imports and calls
ci.util.fbuild_compiledb.ensure_compile_commands(...) (and also references
was_compiled_with_fbuild), but the new public API is
ci.util.fbuild_adapter.get_compile_commands(board); change the import to
get_compile_commands from ci.util.fbuild_adapter and replace uses of
ensure_compile_commands(...) with get_compile_commands(board) (keeping
was_compiled_with_fbuild only if still needed), ensuring you pass the same
board/context argument and adapt any return handling to the adapter's return
shape.
🪄 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: 88d66d86-9a03-4e83-9bf3-33ff03a8935a

📥 Commits

Reviewing files that changed from the base of the PR and between 354e7e6 and 8e39b5e.

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

Comment thread ci/ci-iwyu.py
Comment on lines +496 to +500
mapping_args: list[str] = []
for name in ("fastled.imp", "stdlib.imp"):
p = project_root / "ci" / "iwyu" / name
if p.exists():
mapping_args.extend(["-Xiwyu", f"--mapping_file={p}"])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fail fast when built-in IWYU mapping files are missing.

Silently dropping fastled.imp or stdlib.imp changes IWYU behavior and can make CI results misleading.

🛡️ Proposed fix
     mapping_args: list[str] = []
     for name in ("fastled.imp", "stdlib.imp"):
         p = project_root / "ci" / "iwyu" / name
-        if p.exists():
-            mapping_args.extend(["-Xiwyu", f"--mapping_file={p}"])
+        if not p.exists():
+            print(f"ERROR: required IWYU mapping file not found: {p}", file=sys.stderr)
+            return 1
+        mapping_args.extend(["-Xiwyu", f"--mapping_file={p}"])

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-iwyu.py` around lines 496 - 500, The loop that builds mapping_args
currently skips missing built-in IWYU mapping files (fastled.imp, stdlib.imp)
which silently changes behavior; change it to fail fast: for each name in
("fastled.imp", "stdlib.imp") compute p = project_root / "ci" / "iwyu" / name,
and if p.exists() is False raise or sys.exit with a descriptive error that
includes the missing filename and its expected path (referencing mapping_args,
project_root, and the name variable) instead of silently continuing; only extend
mapping_args when the file exists.

Comment thread ci/ci-iwyu.py
Comment on lines +518 to +535
cmd: list[str] = [
"uv",
"run",
"clang-tool-chain-iwyu-tool",
"-p",
str(compile_db.parent),
"-j",
jobs,
*files,
"--",
] + iwyu_tail

print(
f"Running clang-tool-chain-iwyu-tool against {len(files)} src/ files "
f"using compile DB: {compile_db}"
)
try:
result = subprocess.run(cmd, check=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Expected: `check_iwyu_available` has a system IWYU success path, while
# `run_iwyu_against_compile_db` invokes `uv run clang-tool-chain-iwyu-tool`.
rg -nP -C4 'def\s+check_iwyu_available|include-what-you-use|clang-tool-chain-iwyu-tool|uv' -- ci/ci-iwyu.py

Repository: FastLED/FastLED

Length of output: 5699


Add FileNotFoundError handling to prevent silent crashes when uv is unavailable.

The preflight check can succeed via system include-what-you-use, but run_iwyu_against_compile_db() unconditionally requires uv run clang-tool-chain-iwyu-tool. If uv is missing, fbuild board mode will raise an unhandled FileNotFoundError instead of failing with a clear diagnostic message.

Proposed fix
     try:
         result = subprocess.run(cmd, check=True)
         return result.returncode
     except KeyboardInterrupt as ki:
         from ci.util.global_interrupt_handler import handle_keyboard_interrupt
 
         handle_keyboard_interrupt(ki)
         raise
+    except FileNotFoundError as e:
+        print(
+            "ERROR: fbuild IWYU mode requires `uv run clang-tool-chain-iwyu-tool`, "
+            f"but the command could not be started: {e}",
+            file=sys.stderr,
+        )
+        return 1
     except subprocess.CalledProcessError as e:
         print(f"clang-tool-chain-iwyu-tool failed with return code {e.returncode}")
         return e.returncode
🧰 Tools
🪛 Ruff (0.15.10)

[warning] 518-528: Consider iterable unpacking instead of concatenation

Replace with iterable unpacking

(RUF005)


[error] 535-535: subprocess call: check for execution of untrusted input

(S603)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/ci-iwyu.py` around lines 518 - 535, The call to subprocess.run in
run_iwyu_against_compile_db (the block building cmd and calling
subprocess.run(cmd, check=True)) can raise FileNotFoundError if the external
`uv` binary is missing; wrap the subprocess.run call in a try/except that
catches FileNotFoundError and fails cleanly with a clear diagnostic (e.g., use
processLogger.error or raise SystemExit with a message explaining that
`uv`/clang-tool-chain-iwyu-tool is not found and suggesting installing or using
system include-what-you-use), so the failure is reported instead of crashing
silently.

Comment thread ci/ci-iwyu.py Resolved
zackees added a commit that referenced this pull request Apr 18, 2026
… path

The esbuild alias `three=./vendor/three/three.module.js` and the direct
relative imports in app.ts and fastled_background_worker.ts (both of
which use `./vendor/three/build/three.module.js`) both pointed at
paths that were never populated — the original vendor commit 7d5bb4e
committed only `vendor/three/examples/jsm/` and missed the runtime
module. Every WASM CI build has been failing at the esbuild step with
"Could not resolve ./vendor/three/three.module.js".

Fixes by:
  - Committing three.module.js (three.js v0.170.0, MIT) under
    vendor/three/build/, matching the actual import paths.
  - Adding an unignore rule so vendor/three/build/ isn't swept by the
    project-wide build/ ignore (follows the existing precedent for
    !src/fl/build/).
  - Updating the esbuild alias to the same path so bare `three` imports
    from examples/jsm files resolve to the identical module instance as
    the direct relative imports (no double-bundle).
  - Vendoring LICENSE alongside for attribution.

Verified locally: bash compile wasm --examples AudioUrl now produces
fastled.js + fastled.wasm + index.html (previously the final esbuild
step failed, leaving those artifacts missing and breaking the
"Check for required artifacts" step in build.yml).

Unblocks CI for #2331, #2332, #2335, and every future PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Apr 18, 2026
Every WASM CI build was failing at the esbuild bundling step with
"Could not resolve ./vendor/three/three.module.js (originally three)"
because the path the existing alias in ci/esbuild_frontend.py has
always pointed at was never populated. The original vendor commit
7d5bb4e committed only vendor/three/examples/jsm/ and missed the
runtime module.

The project's security-safe CI workflow copies only src/, examples/,
and a handful of root manifests from PR head into the trusted tree —
it does not copy ci/ or .gitignore, which means a fix that lives
only under ci/ cannot unblock PRs at all.

Fix, entirely under src/:

  - Vendor three.js v0.170.0 (MIT) at
    src/platforms/wasm/compiler/vendor/three/three.module.js —
    exactly the path the existing esbuild alias already points to,
    so bare `from 'three'` imports in examples/jsm/* resolve cleanly.
  - Retarget the three direct-relative imports (app.ts,
    fastled_background_worker.ts, scene.js) from
    ./vendor/three/build/three.module.js → ./vendor/three/three.module.js
    so every consumer resolves to the same on-disk file, which also
    means esbuild bundles three.js exactly once (no double-bundle,
    no instanceof surprises across worker/main bundles).
  - Ship three.js LICENSE alongside for MIT attribution.

No ci/ changes, no .gitignore changes — the fix is self-contained in
src/ and will survive the workflow's safe-file merge.

Verified locally: bash compile wasm --examples AudioUrl now emits
fastled.js, fastled.wasm, and index.html. Previously failed with
esbuild exit 1, leaving those artifacts missing and breaking the
"Check for required artifacts" step in build.yml.

Unblocks #2331, #2335, and master CI.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rd listing

Three CodeRabbit findings on the prior revision:

1. Use ci.util.fbuild_adapter.get_compile_commands() instead of reaching
   into ci.util.fbuild_compiledb.ensure_compile_commands(). That adapter
   is this PR's stated "stable, public entry point for static-analysis
   tools"; the first consumer (IWYU) should validate it by using it.

2. Drop `result_code == 0` guard on the --fix-unsupported warning. The
   comment says "fail loudly rather than silently no-op", but the guard
   suppressed the warning whenever IWYU reported violations — exactly
   the case the user is most likely to have run --fix for. Fire the
   warning whenever --fix is requested on an fbuild board.

3. Include .build/pio/<board>/ entries in the "Available boards" print
   when board lookup fails. The resolver checks both .build/<board> and
   .build/pio/<board>, but the failure message only listed immediate
   .build/ children — so modern PIO-layout boards showed as a single
   "pio" entry instead of each board name.

Skipped two defensive-polish items (missing fastled.imp/stdlib.imp,
missing `uv` binary) — files exist in-repo and `uv` is a hard project
requirement; silent skip / crash is acceptable pending a real failure.

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.

♻️ Duplicate comments (3)
ci/ci-iwyu.py (3)

846-854: ⚠️ Potential issue | 🟡 Minor

Make the fbuild --fix note result-neutral.

This now prints for every --fix run, so “violations were reported” is inaccurate when IWYU exits cleanly.

🧹 Proposed wording tweak
             print(
                 "NOTE: --fix is not yet supported for fbuild-backed boards; "
-                "violations were reported but not auto-fixed.",
+                "IWYU was run in report-only mode; no changes were auto-fixed.",
                 file=sys.stderr,
             )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/ci-iwyu.py` around lines 846 - 854, The current message printed inside the
if args.fix block is misleading because it says “violations were reported” even
when IWYU exits cleanly; update the print call in the if args.fix branch to a
result-neutral note (e.g., “NOTE: --fix is not yet supported for fbuild-backed
boards; no automatic fixes will be applied.”) so it does not assert that
violations occurred; locate the if args.fix block and modify the string passed
to print accordingly.

497-501: ⚠️ Potential issue | 🟡 Minor

Fail fast when required IWYU mappings are missing.

Silently skipping fastled.imp or stdlib.imp changes IWYU results while still returning a normal CI status.

🛡️ Proposed fix
     mapping_args: list[str] = []
     for name in ("fastled.imp", "stdlib.imp"):
         p = project_root / "ci" / "iwyu" / name
-        if p.exists():
-            mapping_args.extend(["-Xiwyu", f"--mapping_file={p}"])
+        if not p.exists():
+            print(f"ERROR: required IWYU mapping file not found: {p}", file=sys.stderr)
+            return 1
+        mapping_args.extend(["-Xiwyu", f"--mapping_file={p}"])

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-iwyu.py` around lines 497 - 501, The current loop that builds
mapping_args (variable mapping_args and the for loop over
("fastled.imp","stdlib.imp") with p = project_root / "ci" / "iwyu" / name and
p.exists() check) silently skips missing mapping files; instead, fail fast:
after computing p for each name, if p.exists() is False raise a clear
RuntimeError (or call sys.exit with non-zero) naming the missing mapping file
and its expected path so CI fails and the error is descriptive; keep extending
mapping_args only when the file exists.

535-545: ⚠️ Potential issue | 🟠 Major

Handle missing uv in the fbuild IWYU path.

check_iwyu_available() can succeed via system IWYU, but this branch still launches uv; if uv is absent, fbuild board mode crashes instead of returning a clear CI diagnostic.

🛡️ Proposed fix
     try:
         result = subprocess.run(cmd, check=True)
         return result.returncode
     except KeyboardInterrupt as ki:
         from ci.util.global_interrupt_handler import handle_keyboard_interrupt
 
         handle_keyboard_interrupt(ki)
         raise
+    except FileNotFoundError as e:
+        print(
+            "ERROR: fbuild IWYU mode requires `uv run clang-tool-chain-iwyu-tool`, "
+            f"but the command could not be started: {e}",
+            file=sys.stderr,
+        )
+        return 1
     except subprocess.CalledProcessError as e:
         print(f"clang-tool-chain-iwyu-tool failed with return code {e.returncode}")
         return e.returncode

As per coding guidelines: “Never use silent fallbacks for missing critical resources - always fail fast with descriptive errors”.

Run this read-only check to confirm the availability check can pass independently of the fbuild uv invocation:

#!/bin/bash
# Expected: check_iwyu_available has a system IWYU success path, while
# run_iwyu_against_compile_db invokes `uv run clang-tool-chain-iwyu-tool`.
rg -nP -C4 'def\s+check_iwyu_available|include-what-you-use|clang-tool-chain-iwyu-tool|subprocess\.run\(cmd' -- ci/ci-iwyu.py
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/ci-iwyu.py` around lines 535 - 545, check_iwyu_available can return
success via system IWYU, but run_iwyu_against_compile_db still blindly invokes
the fbuild "uv" path and crashes if 'uv' is missing; update
run_iwyu_against_compile_db (the branch that builds cmd containing "uv run
clang-tool-chain-iwyu-tool" and calls subprocess.run(cmd, ...)) to first verify
'uv' exists (e.g. shutil.which('uv')) and if not present raise/return a clear CI
error message and non-zero code, or alternatively catch FileNotFoundError around
subprocess.run and convert it to a descriptive error/return code — ensure the
diagnostic mentions the missing 'uv' executable and that system IWYU was used in
check_iwyu_available so the failure is explicit.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@ci/ci-iwyu.py`:
- Around line 846-854: The current message printed inside the if args.fix block
is misleading because it says “violations were reported” even when IWYU exits
cleanly; update the print call in the if args.fix branch to a result-neutral
note (e.g., “NOTE: --fix is not yet supported for fbuild-backed boards; no
automatic fixes will be applied.”) so it does not assert that violations
occurred; locate the if args.fix block and modify the string passed to print
accordingly.
- Around line 497-501: The current loop that builds mapping_args (variable
mapping_args and the for loop over ("fastled.imp","stdlib.imp") with p =
project_root / "ci" / "iwyu" / name and p.exists() check) silently skips missing
mapping files; instead, fail fast: after computing p for each name, if
p.exists() is False raise a clear RuntimeError (or call sys.exit with non-zero)
naming the missing mapping file and its expected path so CI fails and the error
is descriptive; keep extending mapping_args only when the file exists.
- Around line 535-545: check_iwyu_available can return success via system IWYU,
but run_iwyu_against_compile_db still blindly invokes the fbuild "uv" path and
crashes if 'uv' is missing; update run_iwyu_against_compile_db (the branch that
builds cmd containing "uv run clang-tool-chain-iwyu-tool" and calls
subprocess.run(cmd, ...)) to first verify 'uv' exists (e.g. shutil.which('uv'))
and if not present raise/return a clear CI error message and non-zero code, or
alternatively catch FileNotFoundError around subprocess.run and convert it to a
descriptive error/return code — ensure the diagnostic mentions the missing 'uv'
executable and that system IWYU was used in check_iwyu_available so the failure
is explicit.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 25e5a5eb-e9af-40b0-b2f5-0c626db436e6

📥 Commits

Reviewing files that changed from the base of the PR and between 8e39b5e and 4232803.

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

@zackees
zackees merged commit 5b7a1db into master Apr 19, 2026
59 of 78 checks passed
zackees added a commit that referenced this pull request Apr 19, 2026
#2331

Two outstanding nitpicks from the original #2331 review that were deferred
pending follow-up. Both tighten up the public API the IWYU/cppcheck front-
ends use.

1. ci/util/fbuild_adapter.py — drop default `build_root: Path | None = None`
   on `get_compile_commands`. Repo style: parameters don't have defaults.
   Sole caller (ci/ci-iwyu.py) already passes build_root explicitly, so
   making it required is a no-op at call sites. The doc now explains
   why the default was removed.

2. ci/util/fbuild_compiledb.py — replace the fragile
   `repo_root = build_root.parent if build_root.name == ".build" else
   build_root` heuristic in `_candidate_fbuild_release_dirs` with an
   explicit `project_root` parameter. The heuristic silently collapsed
   two of the three candidates into one whenever a caller passed a
   build_root not literally named ".build/" (a surprise waiting to
   happen once callers multiply).

   Plumb `project_root` through the public API:
   - `fbuild_release_dir`     (project_root, build_root, board_name)
   - `was_compiled_with_fbuild` (project_root, build_root, board_name)
   - internal `_find_existing_compile_db` and `ensure_compile_commands`

   Callers updated:
   - ci/ci-iwyu.py: pass `_PROJECT_ROOT` (already defined locally)
   - ci/ci-cppcheck.py: pass `project_root` (already computed locally)
   - ci/util/fbuild_adapter.py: already computes project_root for
     `ensure_compile_commands`; no change beyond the default removal.

Imports and `--help` verified on both ci-iwyu.py and ci-cppcheck.py.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant