Repository navigation
Enforce zccache strict paths in Meson builds - #2385
Conversation
📝 WalkthroughWalkthroughAdds Meson private-include path normalization (convert backslashes, resolve to absolute POSIX paths) for Meson-generated scratch Changes
Sequence DiagramsequenceDiagram
participant Build as Build Script
participant Meson as Meson/Ninja
participant Artifacts as build.ninja / compile_commands.json
participant Normalizer as Normalization Handler
participant zccache as zccache
participant Compiler as Compiler
Build->>Meson: setup_meson_build()
Meson->>Artifacts: Emit build artifacts with private -I*.p flags
Build->>Normalizer: _normalize_meson_private_paths(build_dir)
Normalizer->>Artifacts: Read files, find -I*.p flags
Normalizer->>Artifacts: Resolve non-absolute -> absolute (POSIX), convert '\' -> '/'
Normalizer->>Artifacts: Write back only if changed
Build->>zccache: Set ZCCACHE_STRICT_PATHS=absolute in env
Compiler->>zccache: zccache validates/uses normalized paths in strict mode
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 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 docstrings
🧪 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 (2)
ci/wasm_build.py (1)
72-77: Consider promoting_normalize_meson_private_include_pathsto a public API.This helper imports a private (
_-prefixed) symbol fromci.meson.build_config. Cross-module consumption of a private name coupleswasm_build.pyto an internal implementation detail — ifbuild_config.pyever renames or removes that function, this call site silently breaks.Recommend renaming the target function to
normalize_meson_private_include_paths(drop the underscore) inci/meson/build_config.pyand updating both call sites, making the contract explicit.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/wasm_build.py` around lines 72 - 77, The call site imports the private helper _normalize_meson_private_include_paths; change the helper's name to normalize_meson_private_include_paths in its module and update all call sites (including the caller that currently calls _normalize_meson_private_include_paths) to use normalize_meson_private_include_paths so the API is explicit and non-underscore-prefixed; ensure the renamed function signature and return behavior remain the same and run tests to verify nothing else relies on the old private name.ci/tests/test_meson_include_paths.py (1)
52-55: Use explicit loops in changed Python helpers.The new list comprehensions conflict with the repository Python guideline.
Proposed cleanup
def _tokens_from_entry(entry: dict[str, object]) -> list[str]: raw_args = entry.get("arguments") if isinstance(raw_args, list): - return [str(arg) for arg in raw_args] + tokens: list[str] = [] + for arg in raw_args: + tokens.append(str(arg)) + return tokens- parts = [part for part in re.split(r"/+", path) if part] + parts: list[str] = [] + for part in re.split(r"/+", path): + if part: + parts.append(part) if "." in parts or ".." in parts: return "dot path component"As per coding guidelines, "Use explicit loops instead of list comprehensions for code clarity and debuggability".
Also applies to: 96-105
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/tests/test_meson_include_paths.py` around lines 52 - 55, Replace the list comprehension in _tokens_from_entry with an explicit loop: when raw_args is a list, create an empty list, iterate over raw_args, append str(arg) for each element, and return that list (and ensure the function still returns an empty list or None per existing behavior when raw_args is not a list); apply the same change to the similar helper block around lines 96-105 so all list comprehensions are converted to explicit for-loops while preserving types and return values.
🤖 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/meson/build_config.py`:
- Around line 339-381: The current normalization logic for build_ninja and
compile_commands silently ignores OSErrors and JSON decode errors; update the
functions that use build_ninja, compile_commands and _normalize_text (and any
caller relying on changed_any) to fail fast instead: when build_ninja.read_text
or write_text raises OSError, raise a descriptive exception (include the
filename and operation) instead of passing; when
compile_commands.read_text/json.loads raises OSError or json.JSONDecodeError,
raise a descriptive exception rather than setting data=None; when writing back
normalized JSON fails, raise a descriptive error; ensure the function's return
contract is updated so callers receive an explicit error state (or propagate the
exception) so upstream code cannot continue with unnormalized paths.
In `@ci/tests/test_meson_include_paths.py`:
- Around line 49-84: The extractor misses attached forms of several strict path
flags; update _ATTACHED_PATH_PREFIXES (or build an equivalent list) so it
includes attached prefixes for every path-bearing flag checked by zccache strict
mode (e.g., add '-isystem', '-iquote', '-include-pch' alongside '-I', '-F',
'/I'), and keep the existing detection logic in _extract_strict_path_flags
(which uses token.startswith(prefix) and token[len(prefix):]) so tokens like
'-isystemC:/bad' or '-include-pchC:/bad' are recognized and appended to out;
ensure changes reference the symbols _ATTACHED_PATH_PREFIXES,
_SEPARATE_PATH_FLAGS, _extract_strict_path_flags, and _tokens_from_entry.
---
Nitpick comments:
In `@ci/tests/test_meson_include_paths.py`:
- Around line 52-55: Replace the list comprehension in _tokens_from_entry with
an explicit loop: when raw_args is a list, create an empty list, iterate over
raw_args, append str(arg) for each element, and return that list (and ensure the
function still returns an empty list or None per existing behavior when raw_args
is not a list); apply the same change to the similar helper block around lines
96-105 so all list comprehensions are converted to explicit for-loops while
preserving types and return values.
In `@ci/wasm_build.py`:
- Around line 72-77: The call site imports the private helper
_normalize_meson_private_include_paths; change the helper's name to
normalize_meson_private_include_paths in its module and update all call sites
(including the caller that currently calls
_normalize_meson_private_include_paths) to use
normalize_meson_private_include_paths so the API is explicit and
non-underscore-prefixed; ensure the renamed function signature and return
behavior remain the same and run tests to verify nothing else relies on the old
private name.
🪄 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: cdab1beb-84c7-4b21-afba-fab8f46bf41f
📒 Files selected for processing (10)
ci/meson/build_config.pyci/meson/native/meson.buildci/meson/runner.pyci/meson/shared/meson.buildci/meson/wasm/meson.buildci/tests/test_meson_include_paths.pyci/wasm_build.pyexamples/meson.buildtests/meson.buildtests/profile/meson.build
|
Addressed the CodeRabbit review comments in
Verified locally:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/meson/build_config.py`:
- Around line 313-395: normalize_meson_private_include_paths currently only
processes compile_commands.json "command" strings and uses
_MESON_PRIVATE_INCLUDE_RE which requires literal quotes, so unquoted -I*.p
tokens and the "arguments" array form are skipped; update
_MESON_PRIVATE_INCLUDE_RE to match both quoted and unquoted -I...*.p tokens
(make the surrounding quotes optional and allow no-whitespace path capture) and
extend normalize_meson_private_include_paths to also handle entries with an
"arguments" list by iterating over each element, normalizing any string elements
via _normalize_text (same logic as used for "command"), updating the list when
changed, and writing the modified JSON back (preserving the current error
handling and changed_any behavior), using the existing helpers _replacement and
_normalize_text.
🪄 Autofix (Beta)
✅ Autofix completed
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: b3af38ae-3f71-4e38-98cf-656b96670f25
📒 Files selected for processing (3)
ci/meson/build_config.pyci/tests/test_meson_include_paths.pyci/wasm_build.py
🚧 Files skipped from review as they are similar to previous changes (1)
- ci/wasm_build.py
| _MESON_PRIVATE_INCLUDE_RE = re.compile(r'("-I)([^"]+\.p)(")') | ||
|
|
||
|
|
||
| def _is_forward_slash_absolute(path: str) -> bool: | ||
| return path.startswith("/") or re.match(r"^[A-Za-z]:/", path) is not None | ||
|
|
||
|
|
||
| def normalize_meson_private_include_paths(build_dir: Path) -> bool: | ||
| """Normalize Meson's private ``-I*.p`` scratch includes for zccache strict mode.""" | ||
|
|
||
| changed_any = False | ||
|
|
||
| def _replacement(match: re.Match[str]) -> str: | ||
| prefix, raw_path, suffix = match.groups() | ||
| normalized = raw_path.replace("\\", "/") | ||
| if _is_forward_slash_absolute(normalized): | ||
| absolute = normalized | ||
| else: | ||
| absolute = (build_dir / normalized).resolve().as_posix() | ||
| if absolute == raw_path: | ||
| return match.group(0) | ||
| return f"{prefix}{absolute}{suffix}" | ||
|
|
||
| def _normalize_text(content: str) -> str: | ||
| return _MESON_PRIVATE_INCLUDE_RE.sub(_replacement, content) | ||
|
|
||
| build_ninja = build_dir / "build.ninja" | ||
| if build_ninja.exists(): | ||
| try: | ||
| content = build_ninja.read_text(encoding="utf-8") | ||
| except OSError as e: | ||
| raise RuntimeError( | ||
| f"Could not read {build_ninja} while normalizing Meson strict paths" | ||
| ) from e | ||
| else: | ||
| normalized = _normalize_text(content) | ||
| if normalized != content: | ||
| try: | ||
| build_ninja.write_text(normalized, encoding="utf-8") | ||
| changed_any = True | ||
| except OSError as e: | ||
| raise RuntimeError( | ||
| f"Could not write {build_ninja} after normalizing Meson strict paths" | ||
| ) from e | ||
|
|
||
| compile_commands = build_dir / "compile_commands.json" | ||
| if compile_commands.exists(): | ||
| try: | ||
| data = json.loads(compile_commands.read_text(encoding="utf-8")) | ||
| except OSError as e: | ||
| raise RuntimeError( | ||
| f"Could not read {compile_commands} while normalizing Meson strict paths" | ||
| ) from e | ||
| except json.JSONDecodeError as e: | ||
| raise RuntimeError( | ||
| f"Could not parse {compile_commands} while normalizing Meson strict paths" | ||
| ) from e | ||
| if isinstance(data, list): | ||
| changed_json = False | ||
| for entry in data: | ||
| if not isinstance(entry, dict): | ||
| continue | ||
| entry_dict = cast(dict[str, object], entry) | ||
| command = entry_dict.get("command") | ||
| if not isinstance(command, str): | ||
| continue | ||
| normalized = _normalize_text(command) | ||
| if normalized != command: | ||
| entry_dict["command"] = normalized | ||
| changed_json = True | ||
| if changed_json: | ||
| try: | ||
| compile_commands.write_text( | ||
| json.dumps(data, indent=2) + "\n", | ||
| encoding="utf-8", | ||
| ) | ||
| changed_any = True | ||
| except OSError as e: | ||
| raise RuntimeError( | ||
| f"Could not write {compile_commands} after normalizing Meson strict paths" | ||
| ) from e | ||
|
|
||
| return changed_any |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check whether any local Meson-generated compile DBs in this tree use the
# "arguments" array form or carry unquoted -I*.p tokens that the current
# regex would miss.
fd -t f compile_commands.json .build 2>/dev/null | while read -r f; do
echo "=== $f ==="
python3 - "$f" <<'PY'
import json, re, sys
p = sys.argv[1]
with open(p, encoding="utf-8") as fh:
data = json.load(fh)
fmt_args = sum(1 for e in data if isinstance(e, dict) and isinstance(e.get("arguments"), list))
fmt_cmd = sum(1 for e in data if isinstance(e, dict) and isinstance(e.get("command"), str))
print(f"entries: {len(data)} arguments-form: {fmt_args} command-form: {fmt_cmd}")
unquoted_p = re.compile(r'(?<!["\'])(-I[^\s"\']+\.p)')
samples = []
for e in data:
cmd = e.get("command") if isinstance(e, dict) else None
if isinstance(cmd, str):
for m in unquoted_p.findall(cmd):
samples.append(m)
if len(samples) >= 5: break
if len(samples) >= 5: break
print("unquoted -I*.p samples:", samples)
PY
done
# Also sanity-check build.ninja for unquoted -I*.p occurrences.
fd -t f build.ninja .build 2>/dev/null | while read -r f; do
echo "=== $f ==="
rg -nP '(?<!["\x27])-I[^\s"\x27]+\.p' "$f" | head -n 5
doneRepository: FastLED/FastLED
Length of output: 41
🏁 Script executed:
# Find Meson configuration files and build-related tests
fd -t f -e meson.build -e meson_options.txt . 2>/dev/null | head -20Repository: FastLED/FastLED
Length of output: 41
🏁 Script executed:
# Search for references to compile_commands.json in the codebase
rg -l 'compile_commands' --type py --type json --type yamlRepository: FastLED/FastLED
Length of output: 257
🏁 Script executed:
# Look for test files related to the normalization function
fd -t f -name '*test*' . | rg -i 'meson|normal'Repository: FastLED/FastLED
Length of output: 289
🏁 Script executed:
# Search for handling of "arguments" array in compile_commands context
rg -i 'arguments' --type py | grep -i 'compile\|command'Repository: FastLED/FastLED
Length of output: 4107
🏁 Script executed:
# Check if there are any existing tests for normalize_meson_private_include_paths
rg -A 5 'normalize_meson_private_include_paths' --type pyRepository: FastLED/FastLED
Length of output: 1705
🏁 Script executed:
cat -n ci/tests/test_meson_include_paths.pyRepository: FastLED/FastLED
Length of output: 8496
🏁 Script executed:
# Also check the actual code location more carefully
sed -n '313,395p' ci/meson/build_config.py | cat -nRepository: FastLED/FastLED
Length of output: 3900
🏁 Script executed:
# Check if there are any references to "arguments" in compile_commands context
rg -B 3 -A 3 '"arguments"' ci/util/fbuild_compiledb.pyRepository: FastLED/FastLED
Length of output: 41
Normalizer incompletely handles compile_commands.json "arguments" form and quoted-only -I*.p flags.
The test suite (ci/tests/test_meson_include_paths.py) explicitly handles both "command" and "arguments" forms in compile_commands.json entries (see _tokens_from_entry lines 64–74 and the test_extract_strict_path_flags_includes_attached_forms test), but the normalizer only inspects the "command" field. When Meson emits the "arguments" array form, the normalizer silently skips the entry since entry_dict.get("command") returns None, while the test framework would later detect any path violations and fail. Additionally, the regex r'("-I)([^"]+\.p)(")' requires literal quote wrapping, so unquoted -I*.p tokens in build.ninja or command strings are not matched.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@ci/meson/build_config.py` around lines 313 - 395,
normalize_meson_private_include_paths currently only processes
compile_commands.json "command" strings and uses _MESON_PRIVATE_INCLUDE_RE which
requires literal quotes, so unquoted -I*.p tokens and the "arguments" array form
are skipped; update _MESON_PRIVATE_INCLUDE_RE to match both quoted and unquoted
-I...*.p tokens (make the surrounding quotes optional and allow no-whitespace
path capture) and extend normalize_meson_private_include_paths to also handle
entries with an "arguments" list by iterating over each element, normalizing any
string elements via _normalize_text (same logic as used for "command"), updating
the list when changed, and writing the modified JSON back (preserving the
current error handling and changed_any behavior), using the existing helpers
_replacement and _normalize_text.
|
Note Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it. Fixes Applied SuccessfullyFixed 1 file(s) based on 1 unresolved review comment. Files modified:
Commit: The changes have been pushed to the Time taken: |
Summary
ZCCACHE_STRICT_PATHS=absolutefor Meson/zccache builds so mixed separator or relative compiler paths fail locally instead of regressing silently..pinclude paths in generated Ninja/compile database files after setup/reconfigure.-I,/I,-include, and related forms.Issue #2376 status
The merged dependency updates make the original
#pragma oncefailure stop reproducing on currentmaster:bash test --cpppassed before this patch. However, running with zccache strict mode still failed on currentmasterbecause Meson emitted private scratch includes likeci/meson/native\fastled.dll.p. This PR makes strict mode part of the Meson/zccache path and fixes the remaining path hygiene problem.Fixes #2376.
Testing
uv run zccache --version->zccache 1.3.7master:bash test --cpp-> passed 302/302master:ZCCACHE_STRICT_PATHS=absolute bash test --cpp --clean --force-> failed on zccache strict path rejection for Meson private.pincludeZCCACHE_STRICT_PATHS=absolute bash test --cpp --force --no-parallel-> passed 327/327uv run pytest ci/tests/test_meson_include_paths.py -v-> passeduv run test.py --examples Fire2023 --full --forcewith strict paths -> passedgit diff --check-> cleanSummary by CodeRabbit