Skip to content

feat(ci): PlatformIO-internal-usage linter (warn-only first pass) (refs #2701) - #2807

Merged
zackees merged 1 commit into
masterfrom
feat/2701-platformio-lint-rule
Jun 5, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/2701-platformio-lint-rule

Conversation

@zackees

@zackees zackees commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds a new lint rule that flags forbidden internal PlatformIO build invocations in build/CI code, per #2701. FastLED board builds should now use fbuild exclusively; this checker prevents new internal pio run / --backend platformio call sites from being introduced while the companion sweep PR removes the existing ones.

This PR ships just the linter (refs, not closes #2701). The sweep half — removing the ~17 existing call sites the linter flags — is a separate follow-up so reviewers can vet each removal individually.

What the linter detects

ci/lint_platformio/check_no_internal_platformio.py flags these patterns in .py, .yml, .yaml, .sh, .bash, .ps1, .cmd, .bat, .toml, .cfg, .ini, and .md files:

Pattern Category Example
pio run pio_run cd ci/kitchensink && pio run
platformio run platformio_run uv run platformio run
platformio --version platformio_version_probe uv run platformio --version
--backend platformio / --backend=platformio backend_platformio_flag ci/ci-check-compiled-size.py --backend platformio
--platformio platformio_flag argparse add_argument("--platformio", ...)
--pio pio_flag argparse add_argument("--pio", ...)

Lines that look like in-file comments (#, //, *, <!--, /*) are skipped so the checker doesn't self-flag when it documents its own patterns.

Allowlist policy

Paths where PlatformIO references are intentional and out of scope:

  • User-facing docs: README.md, /docs/, /agents/docs/
  • Examples: /examples/ (sketch comments + READMEs)
  • PlatformIO library manifest (this is the PIO consumer API): /library.json, /library.properties
  • Issue templates: /.github/ISSUE_TEMPLATE/, /.github/PULL_REQUEST_TEMPLATE
  • Planned backend-comparison harness: ci/check_backend_flag_drift.py (intentionally calls both backends side-by-side)
  • The linter itself: ci/lint_platformio/
  • Build artifacts & caches: .build/, .pio/, .cache/
  • Wiki submodule, git internals, Claude harness config, sibling worktrees

The allowlist is intentionally permissive — the point of the warn-mode first pass is to surface the current state, not litigate edge cases.

Warn-only mode

The linter is in WARN MODE by default — the stage prints violations and the punchlist, but exits 0 so CI stays green while the existing call sites are removed.

To run as a gate (after the sweep PR lands):

uv run python ci/lint_platformio/run_all_checkers.py --error
# or
FASTLED_LINT_PLATFORMIO_ERROR=1 bash lint

Sample output

bash lint now reports (17 violations across 10 files):

================================================================================
[PlatformIO-internal-usage] WARN mode — found 17 violation(s) in 10 file(s):
================================================================================

.github/workflows/build_clone_and_compile.yml:
  Line 52: [platformio_run] Forbidden: `platformio run` as build invocation. Use fbuild instead.  >> run: uv run platformio run

.github/workflows/build_esp_extra_libs.yml:
  Line 50: [pio_run] Forbidden: `pio run` as build invocation. Use fbuild instead.  >> cd ci/kitchensink && pio run

.github/workflows/build_template.yml:
  Line 80: [platformio_version_probe] Forbidden: `platformio --version` probe. ...

.github/workflows/build_template_binary_size.yml:
  Line 44: [backend_platformio_flag] Forbidden: `--backend platformio`. fbuild is the only supported backend.
  Line 65: [backend_platformio_flag] ...
  Line 87: [backend_platformio_flag] ...

ci/boards.py:
  Line 51: [pio_run] ...
ci/build_docker_image_pio.py:
  Line 623: [pio_run] ...
ci/compiler/argument_parser.py:
  Lines 23, 290, 295 (--platformio), 296 (--pio), 299
ci/compiler/compilation_orchestrator.py:
  Lines 58, 117
ci/compiler/pio.py:
  Line 70
ci/debug_attached.py:
  Line 258

⚠️  PlatformIO-internal-usage: 17 violation(s) (warn-only — not failing CI). See issue #2701.

The stage shows up in the bash lint execution summary:

Linter Name               |                 Duration
--------------------------+-------------------------
python_pipeline           |                       4s
cpp_linting               |                      22s
javascript_linting        |                      29s
meson_linting             |                       1s
platformio_internal_usage |                       1s

Wired into bash lint

  • New stage platformio_internal_usage in ci/lint.py create_stages() — runs whenever non-JS-only linting is invoked, in parallel with the other stages.
  • New CLI flag --skip-platformio-check (mirrors --skip-meson).
  • Standalone runner: uv run python ci/lint_platformio/run_all_checkers.py [--error|--list-violations].

What's in the follow-up sweep PR

Once the call sites the linter currently flags are removed (delete --platformio/--pio in ci/compiler/argument_parser.py, drop --backend platformio from the workflow YAMLs, etc.), the linter can be promoted to error mode by either:

  1. Flipping the default of run_platformio_lint(warn_only=False) in ci/lint_platformio/run_all_checkers.py, OR
  2. Setting FASTLED_LINT_PLATFORMIO_ERROR=1 in CI workflows.

The 17 current violations are the sweep punchlist.

Test plan

  • bash lint runs the new stage and prints the 17-violation punchlist without failing
  • Standalone uv run python ci/lint_platformio/run_all_checkers.py lists violations (exit 0)
  • Standalone with --error flag exits 1 when violations exist
  • --skip-platformio-check is wired through args_parser.py
  • CI green on this PR (no new violations introduced; existing violations don't gate)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Introduced a new linting stage that detects forbidden PlatformIO internal usages in CI and build-related files, running in warn-only mode by default.
  • Chores

    • Added --skip-platformio-check CLI flag to skip the new linting stage.
    • The check can be configured to enforce as a gating error when needed.

… (refs #2701)

Adds ci/lint_platformio/ with NoInternalPlatformIOChecker, which flags
forbidden internal PlatformIO build invocations in build/CI code:

  * pio run / platformio run / platformio --version
  * --backend platformio
  * --platformio / --pio flag passing or acceptance
  * generated platformio.ini staging (via .ini matcher)

The checker is wired into bash lint as a new `platformio_internal_usage`
stage and runs whenever non-JS-only linting is invoked. It runs in
WARN-ONLY mode by default: violations are listed but the stage exits 0
so CI is not gated red while the companion sweep PR removes the
existing call sites. To promote to a hard gate, pass --error to the
standalone runner or set FASTLED_LINT_PLATFORMIO_ERROR=1.

A `--skip-platformio-check` flag is also added to bash lint to mirror
--skip-meson.

Allowlist (paths intentionally excluded):
  * README.md, /docs/, /agents/docs/ — user-facing docs
  * /examples/ — user example sketches and READMEs
  * /library.json, /library.properties — PlatformIO consumer manifest
  * /.github/ISSUE_TEMPLATE/, /.github/PULL_REQUEST_TEMPLATE — templates
  * ci/check_backend_flag_drift.py — planned backend-comparison harness
  * ci/lint_platformio/ — the linter itself
  * Build artifacts (.build/, .pio/, .cache/) and worktrees

Current punchlist (printed by `bash lint`): 17 violations across 10
files, including .github/workflows/build_template_binary_size.yml
(--backend platformio call sites), ci/compiler/argument_parser.py
(--platformio/--pio flag definitions), ci/boards.py, ci/debug_attached.py,
and several docstrings that quote `pio run`. The follow-up sweep PR
will fix these and then promote the linter to error mode.

Standalone usage:
  uv run python ci/lint_platformio/run_all_checkers.py            # warn-only
  uv run python ci/lint_platformio/run_all_checkers.py --error    # gating
  uv run python ci/lint_platformio/run_all_checkers.py --list-violations

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

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces a custom lint stage that enforces fbuild-only board builds by detecting and reporting forbidden internal PlatformIO invocations (pio run, platformio --version, --backend platformio, etc.) in CI and build configuration files, with configurable warn/error modes and an explicit allowlist for user-facing documentation.

Changes

PlatformIO Internal Usage Lint Enforcement

Layer / File(s) Summary
CLI argument parsing for platformio check
ci/lint/args_parser.py
Adds skip_platformio_check: bool field to LintArgs dataclass and wires --skip-platformio-check CLI flag to allow bypassing the checker.
PlatformIO pattern detection and allowlist
ci/lint_platformio/__init__.py, ci/lint_platformio/check_no_internal_platformio.py
Implements NoInternalPlatformIOChecker with regex-based detection of forbidden patterns (pio run, platformio run, platformio --version, backend flags) and a path-fragment allowlist covering docs, examples, library manifests, and cache directories; filters to CI/build-style file extensions and skips comment lines.
Checker orchestration and violation reporting
ci/lint_platformio/run_all_checkers.py
Provides run_platformio_lint() to traverse the repository, collect relevant files, run the checker, aggregate violations, and report per-file/per-line summaries; supports warn-only mode (default, exit 0) or hard-error mode (exit 1) via --error flag or FASTLED_LINT_PLATFORMIO_ERROR=1 environment variable.
Integration into lint.py pipeline
ci/lint.py
Adds platformio_internal_usage lint stage that runs run_platformio_lint() when not in JS-only mode and --skip-platformio-check is not set, with 30-second timeout.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • FastLED/FastLED#2605: Adds --backend platformio to CI size-check commands, which directly triggers the new NoInternalPlatformIOChecker detection patterns.

Poem

🐰 A linter hops in to guard the fbuild way,
No sneaky pio run shall see the light of day!
With allowlists and patterns, we keep docs untamed,
While CI stays pure—only fbuild needs to be named. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 41.67% 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 directly and clearly describes the main change: a new PlatformIO-internal-usage linter in warn-only mode, with a reference to the linked issue.
Linked Issues check ✅ Passed The PR implements the primary coding objective from issue #2701: a custom lint tool that detects and blocks forbidden internal PlatformIO usage patterns while preserving user-facing references.
Out of Scope Changes check ✅ Passed All changes are directly related to adding the PlatformIO-internal-usage linter; no unrelated modifications were introduced.

✏️ 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/2701-platformio-lint-rule

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: 3

🧹 Nitpick comments (2)
ci/lint_platformio/check_no_internal_platformio.py (2)

103-106: 💤 Low value

Consider using an explicit loop for debuggability.

The generator expression works correctly but the coding guidelines prefer explicit loops over comprehensions/generators for clarity and debuggability.

♻️ Refactor to explicit loop
 def _is_path_allowed(file_path: str) -> bool:
     """Return True if file_path is in the allowlist (substring match)."""
     normalized = file_path.replace("\\", "/")
-    return any(fragment in normalized for fragment in ALLOWED_PATH_FRAGMENTS)
+    for fragment in ALLOWED_PATH_FRAGMENTS:
+        if fragment in normalized:
+            return True
+    return False

As per coding guidelines: "Use explicit loops instead of list comprehensions for code clarity and debuggability"

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/lint_platformio/check_no_internal_platformio.py` around lines 103 - 106,
The helper _is_path_allowed currently uses a generator expression to check
ALLOWED_PATH_FRAGMENTS; change it to an explicit for-loop to improve
debuggability and allow easy logging/breakpoints: normalize the path as before,
then iterate over ALLOWED_PATH_FRAGMENTS with a for fragment in
ALLOWED_PATH_FRAGMENTS: if fragment in normalized: return True; after the loop
return False. Keep the function name _is_path_allowed and the normalized
variable unchanged so callers continue to work.

173-175: 💤 Low value

Consider using an explicit loop for debuggability.

Same rationale as the previous comment—explicit loops are preferred over generator expressions per the coding guidelines.

♻️ Refactor to explicit loop
 def _line_is_comment(line: str) -> bool:
     stripped = line.lstrip()
-    return any(stripped.startswith(prefix) for prefix in _COMMENT_PREFIXES)
+    for prefix in _COMMENT_PREFIXES:
+        if stripped.startswith(prefix):
+            return True
+    return False

As per coding guidelines: "Use explicit loops instead of list comprehensions for code clarity and debuggability"

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/lint_platformio/check_no_internal_platformio.py` around lines 173 - 175,
The helper _line_is_comment currently uses any(...) with a generator expression
which the guidelines discourage for debuggability; replace it with an explicit
loop inside _line_is_comment: compute stripped = line.lstrip(), then iterate for
prefix in _COMMENT_PREFIXES and if stripped.startswith(prefix) return True,
after the loop return False, keeping the function signature and behavior
identical to the original.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@ci/lint_platformio/run_all_checkers.py`:
- Around line 104-107: The try/except in run_all_checkers.py that computes rel =
str(Path(path).relative_to(PROJECT_ROOT)) must handle KeyboardInterrupt before
ValueError; update the exception order so you first catch KeyboardInterrupt (and
re-raise it to allow clean interruption) and then catch ValueError to set rel =
path, keeping the same behavior for non-interrupt errors and preserving use of
Path, PROJECT_ROOT, and rel.
- Around line 77-78: The line using a list comprehension to filter dirnames
should be replaced by an explicit loop for clarity: iterate over a copy of
dirnames (or use the original list) and build a new list by appending each
directory that is not in _SKIP_DIRS and does not start with ".build", then
assign that new list back to dirnames (reference the dirnames variable and the
_SKIP_DIRS constant to locate the code); ensure the logic exactly matches the
original condition and preserves in-place assignment semantics if needed.
- Line 116: Change run_platformio_lint signature to require an explicit boolean
(remove the default None) by updating def run_platformio_lint(warn_only: bool)
-> bool, and add a small parameter-free wrapper function
run_platformio_lint_with_env_default() that computes the previous default (e.g.,
from environment or existing logic) and calls
run_platformio_lint(computed_value); then update the caller in ci/lint.py
(previously calling run_platformio_lint with no arg) to call
run_platformio_lint_with_env_default instead so all callers pass explicit
parameters while preserving current behavior.

---

Nitpick comments:
In `@ci/lint_platformio/check_no_internal_platformio.py`:
- Around line 103-106: The helper _is_path_allowed currently uses a generator
expression to check ALLOWED_PATH_FRAGMENTS; change it to an explicit for-loop to
improve debuggability and allow easy logging/breakpoints: normalize the path as
before, then iterate over ALLOWED_PATH_FRAGMENTS with a for fragment in
ALLOWED_PATH_FRAGMENTS: if fragment in normalized: return True; after the loop
return False. Keep the function name _is_path_allowed and the normalized
variable unchanged so callers continue to work.
- Around line 173-175: The helper _line_is_comment currently uses any(...) with
a generator expression which the guidelines discourage for debuggability;
replace it with an explicit loop inside _line_is_comment: compute stripped =
line.lstrip(), then iterate for prefix in _COMMENT_PREFIXES and if
stripped.startswith(prefix) return True, after the loop return False, keeping
the function signature and behavior identical to the original.
🪄 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: 08ace0dd-874c-470b-80ee-767d62ce7a37

📥 Commits

Reviewing files that changed from the base of the PR and between 787de45 and 4469d9e.

📒 Files selected for processing (5)
  • ci/lint.py
  • ci/lint/args_parser.py
  • ci/lint_platformio/__init__.py
  • ci/lint_platformio/check_no_internal_platformio.py
  • ci/lint_platformio/run_all_checkers.py

Comment on lines +77 to +78
dirnames[:] = [
d for d in dirnames if d not in _SKIP_DIRS and not d.startswith(".build")

@coderabbitai coderabbitai Bot Jun 5, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Replace list comprehension with explicit loop.

The coding guidelines require explicit loops instead of list comprehensions for code clarity and debuggability.

♻️ Refactor to explicit loop
     for dirpath, dirnames, filenames in os.walk(root):
         # In-place prune
-        dirnames[:] = [
-            d for d in dirnames if d not in _SKIP_DIRS and not d.startswith(".build")
-        ]
+        filtered_dirs: list[str] = []
+        for d in dirnames:
+            if d not in _SKIP_DIRS and not d.startswith(".build"):
+                filtered_dirs.append(d)
+        dirnames[:] = filtered_dirs
         for name in filenames:

As per coding guidelines: "Use explicit loops instead of list comprehensions for code clarity and debuggability"

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
dirnames[:] = [
d for d in dirnames if d not in _SKIP_DIRS and not d.startswith(".build")
for dirpath, dirnames, filenames in os.walk(root):
# In-place prune
filtered_dirs: list[str] = []
for d in dirnames:
if d not in _SKIP_DIRS and not d.startswith(".build"):
filtered_dirs.append(d)
dirnames[:] = filtered_dirs
for name in filenames:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/lint_platformio/run_all_checkers.py` around lines 77 - 78, The line using
a list comprehension to filter dirnames should be replaced by an explicit loop
for clarity: iterate over a copy of dirnames (or use the original list) and
build a new list by appending each directory that is not in _SKIP_DIRS and does
not start with ".build", then assign that new list back to dirnames (reference
the dirnames variable and the _SKIP_DIRS constant to locate the code); ensure
the logic exactly matches the original condition and preserves in-place
assignment semantics if needed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Skipping: project Python standards (agents/docs/python-standards.md) do not forbid list/generator comprehensions. List comprehensions are widely used across ci/ and considered idiomatic Python here. The in-place dirnames[:] = [...] pattern is the standard os.walk prune idiom (e.g. it's what the stdlib docs recommend). Keeping the existing form for clarity.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@zackees, understood — I'll defer to the project standard. The dirnames[:] = [...] idiom is indeed the canonical os.walk prune pattern from the stdlib docs. I'll update my long-term memory to reflect that FastLED's Python standards permit list comprehensions.

(ᵔᴥᵔ) noted


✏️ Learnings added
Learnt from: zackees
Repo: FastLED/FastLED PR: 2807
File: ci/lint_platformio/run_all_checkers.py:77-78
Timestamp: 2026-06-05T14:20:57.784Z
Learning: In FastLED/FastLED (Python files under ci/ and elsewhere), list comprehensions are permitted and considered idiomatic. The project Python standards (agents/docs/python-standards.md) do not forbid them. The standard os.walk directory-prune pattern `dirnames[:] = [d for d in dirnames if ...]` is acceptable and preferred over explicit loops for this use case. Do not flag list comprehensions as violations in this repository.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


⛔ Learnings removed
Learnt from: CR
Repo: FastLED/FastLED PR: 0
File: .cursorrules:0-0
Timestamp: 2026-04-11T06:15:07.646Z
Learning: Applies to **/*.py : Use explicit loops instead of list comprehensions for code clarity and debuggability

🧠 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 : Use explicit loops instead of list comprehensions for code clarity and debuggability

Comment on lines +104 to +107
try:
rel = str(Path(path).relative_to(PROJECT_ROOT))
except ValueError:
rel = path

@coderabbitai coderabbitai Bot Jun 5, 2026 •

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 | 🔴 Critical | ⚡ Quick win

Critical: Handle KeyboardInterrupt before other exceptions.

The try-catch block catches ValueError without handling KeyboardInterrupt first, violating coding guidelines that mandate KBI handling before other exceptions to ensure clean interruption.

🔒 Fix KeyboardInterrupt handling
         try:
             rel = str(Path(path).relative_to(PROJECT_ROOT))
+        except KeyboardInterrupt:
+            raise
         except ValueError:
             rel = path

As per coding guidelines: "All Python try-catch blocks must handle KeyboardInterrupt before other exceptions"

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
rel = str(Path(path).relative_to(PROJECT_ROOT))
except ValueError:
rel = path
try:
rel = str(Path(path).relative_to(PROJECT_ROOT))
except KeyboardInterrupt:
raise
except ValueError:
rel = path
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/lint_platformio/run_all_checkers.py` around lines 104 - 107, The
try/except in run_all_checkers.py that computes rel =
str(Path(path).relative_to(PROJECT_ROOT)) must handle KeyboardInterrupt before
ValueError; update the exception order so you first catch KeyboardInterrupt (and
re-raise it to allow clean interruption) and then catch ValueError to set rel =
path, keeping the same behavior for non-interrupt errors and preserving use of
Path, PROJECT_ROOT, and rel.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Skipping (false positive): except ValueError does not catch KeyboardInterrupt. KeyboardInterrupt inherits from BaseException, not Exception/ValueError, so the existing handler already lets KBI propagate cleanly. The project KBI rule (agents/docs/python-standards.md § Exception Handling — KeyboardInterrupt, and the ci/lint_python/keyboard_interrupt_checker.py AST checker KBI001/002) only applies to broad except Exception, except BaseException, or bare except: — it does not require shadowing KBI in front of narrow exceptions. The KBI lint stage in bash lint passes on this file.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@zackees, you're absolutely right — KeyboardInterrupt inherits from BaseException, not from Exception or ValueError, so the existing narrow handler already lets KBI propagate cleanly. My comment was a false positive. Apologies for the noise.

I'll also correct the stored learning that triggered this, since it was overly broad.

(ノ°▽°) 🐇


✏️ Learnings added
Learnt from: zackees
Repo: FastLED/FastLED PR: 2807
File: ci/lint_platformio/run_all_checkers.py:104-107
Timestamp: 2026-06-05T14:20:58.333Z
Learning: In FastLED/FastLED Python code, the KeyboardInterrupt (KBI) handling rule (KBI001/KBI002, defined in `ci/lint_python/keyboard_interrupt_checker.py` and `agents/docs/python-standards.md` § Exception Handling) only applies to broad exception handlers: `except Exception`, `except BaseException`, or bare `except:`. Narrow exception clauses like `except ValueError`, `except TypeError`, etc. do NOT need to explicitly re-raise or precede a `KeyboardInterrupt` catch, because KBI (a BaseException subclass) cannot be caught by them in the first place. Flagging narrow handlers as requiring KBI treatment is a false positive.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


⛔ Learnings removed
Learnt from: CR
Repo: FastLED/FastLED PR: 0
File: .cursorrules:0-0
Timestamp: 2026-04-11T06:15:07.646Z
Learning: Applies to **/*.py : All Python try-catch blocks must handle KeyboardInterrupt before other exceptions

🧠 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 : All Python try-catch blocks must handle KeyboardInterrupt before other exceptions

return total


def run_platformio_lint(warn_only: bool | None = None) -> bool:

@coderabbitai coderabbitai Bot Jun 5, 2026 •

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 | ⚡ Quick win

Function parameter should not have a default value.

The warn_only parameter has a default value of None, which violates the coding guidelines. While this is convenient, the guidelines require function parameters to have explicit values at call sites.

♻️ Refactor to remove default value

To comply with the guideline while maintaining the current call pattern, you can:

Option 1: Create a parameter-free wrapper

-def run_platformio_lint(warn_only: bool | None = None) -> bool:
+def run_platformio_lint(warn_only: bool) -> bool:
     """Run the PlatformIO-internal-usage checker.

     Args:
-        warn_only: If True, always return True (warn mode). If False,
-            return False when violations exist (error mode). If None,
-            consult ``FASTLED_LINT_PLATFORMIO_ERROR`` (defaults to warn).
+        warn_only: If True, always return True (warn mode). If False,
+            return False when violations exist (error mode).

     Returns:
         True if clean OR warn-only mode is active.
     """
-    if warn_only is None:
-        warn_only = os.environ.get("FASTLED_LINT_PLATFORMIO_ERROR", "") != "1"
-
     files = _collect_files(PROJECT_ROOT)
     ...

+def run_platformio_lint_with_env_default() -> bool:
+    """Run PlatformIO lint with warn_only determined by environment."""
+    warn_only_val = os.environ.get("FASTLED_LINT_PLATFORMIO_ERROR", "") != "1"
+    return run_platformio_lint(warn_only=warn_only_val)

Then update ci/lint.py line 251 to call run_platformio_lint_with_env_default instead.

Option 2: Use functools.partial in ci/lint.py

Keep the function signature as-is but construct the call using functools.partial where the default is needed.

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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/lint_platformio/run_all_checkers.py` at line 116, Change
run_platformio_lint signature to require an explicit boolean (remove the default
None) by updating def run_platformio_lint(warn_only: bool) -> bool, and add a
small parameter-free wrapper function run_platformio_lint_with_env_default()
that computes the previous default (e.g., from environment or existing logic)
and calls run_platformio_lint(computed_value); then update the caller in
ci/lint.py (previously calling run_platformio_lint with no arg) to call
run_platformio_lint_with_env_default instead so all callers pass explicit
parameters while preserving current behavior.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Skipping (fabricated rule): project Python standards (agents/docs/python-standards.md) do not forbid default parameter values. Default args are used throughout ci/ (e.g. ci/lint/stage_impls.py:827 run_python_lint_single_file(file_path: str, strict: bool = False), plus dozens of other call sites). The warn_only: bool | None = None sentinel pattern here is intentional: it lets the CLI override the env-default while keeping run_platformio_lint() callable with no args from the lint orchestrator at ci/lint.py:251. Splitting into two functions just to avoid a default would add a layer of indirection for zero benefit.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@zackees, you're right — I apologize for the noise. The rule came from a learning sourced from .cursorrules (a Cursor IDE config) that I incorrectly treated as a project-wide Python standard. The warn_only: bool | None = None sentinel is clearly the idiomatic pattern here: it distinguishes "caller wants warn mode", "caller wants error mode", and "let the environment decide", which is exactly the right layering for a function shared between a CLI entry point and a programmatic caller. Withdrawing the comment.

I'll remove the outdated learning now.

Would you like me to resolve this review comment thread as well?

(´• ω •`) 🐇


⛔ Learnings removed
Learnt from: CR
Repo: FastLED/FastLED PR: 0
File: .cursorrules:0-0
Timestamp: 2026-04-11T06:15:07.646Z
Learning: Applies to **/*.py : All function parameters MUST have explicit type annotations and MUST NOT have default values

🧠 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 : All function parameters MUST have explicit type annotations and MUST NOT have default values

@zackees

zackees commented Jun 5, 2026

Copy link
Copy Markdown
Member Author

CodeRabbit triage (review 4435818522)

All 5 findings reviewed; no code changes applied. Summary:

Inline comments (3) — replied on each thread:

  • run_all_checkers.py:78 list-comp → loop — skip, not a project rule, idiomatic os.walk prune pattern.
  • run_all_checkers.py:107 KBI before ValueError — skip false positive, except ValueError doesn't catch KBI (different base class); project KBI rule scopes to broad excepts only.
  • run_all_checkers.py:116 no-default param — skip, defaults are not forbidden in project Python standards and the sentinel pattern is intentional for the CLI/env dual-source semantics.

Nitpicks (2) — covered here:

  • check_no_internal_platformio.py:103-106 and :173-175 any()-generator → explicit loop. Same rationale as support TLS3001 #1: list/generator comprehensions are idiomatic across ci/ and not forbidden by agents/docs/python-standards.md. CR's claim of "as per coding guidelines" does not match the actual project standards file.

Lint status: bash lint passes locally. PlatformIO-internal-usage linter prints the expected 17-violation punchlist in WARN mode and exits 0, exactly as the PR intends. Promotion to --error mode is staged for the companion sweep PR (see PR description; refs #2701).

@zackees
zackees merged commit 2adf774 into master Jun 5, 2026
23 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 5, 2026
zackees added a commit that referenced this pull request Jun 5, 2026
…le (#2814)

The `_rmtree_onerror(func, path, exc_info)` callback uses the 3-tuple
signature that Python's `shutil.rmtree(onerror=...)` contract requires.
Replacing it with a dataclass would break that interface, so the new
DCT002 linter (from PR #2807, just merged) flags it as a false positive.
Suppress with a `# noqa: DCT002` and document why.

Unblocks the stop hook lint stage that started failing after PR #2807
landed.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees deleted the feat/2701-platformio-lint-rule branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

ci: sweep PlatformIO build usage and add linters that enforce fbuild-only board builds

1 participant