From 45333bf431f0d6cf56b9af12cc1282057ffc1754 Mon Sep 17 00:00:00 2001 From: Peter Downey Date: Wed, 25 Nov 2026 02:38:44 -0500 Subject: [PATCH 1/2] Keep the lint files Codacy reads to packages Codacy installs Codacy reads phpcs.xml and phpmd.xml, but it installs no WordPress coding standards, no PHPCSExtra, and only PHPMD 2, so every analysis failed for both tools and Codacy checked no PHP with them. - PHPCS: phpcs-wordpress.xml is the former phpcs.xml, which composer and CI run. phpcs.xml holds the rules from PHPCS's own standards and VariableAnalysis that the WordPress standards apply, with their settings and the tab width, plus PHPCompatibilityWP. - PHPMD: LongMethodName, a PHPMD 3 rule, moves to phpmd-extra.xml; composer and CI pass both files. .github/scripts/codacy-configs.py regenerates phpcs.xml's rules from phpcs-wordpress.xml, and CI fails when they are out of date. Co-Authored-By: Claude Opus 5.5 --- .codacy.yml | 5 + .distignore | 2 + .gitattributes | 2 + .github/ISSUE_TEMPLATE/phpcs-failure.md | 2 +- .github/labeler.yml | 2 + .github/scripts/codacy-configs.py | 144 ++++++ .github/scripts/phpcs-ruleset-dump.php | 56 +++ .github/workflows/wp-compatibility-test.yml | 7 +- .mypy.ini | 2 +- CONTRIBUTING.md | 8 +- composer.json | 6 +- phpcs-wordpress.xml | 213 ++++++++ phpcs.xml | 516 +++++++++++++++----- phpmd-extra.xml | 23 + phpmd.xml | 11 +- 15 files changed, 854 insertions(+), 145 deletions(-) create mode 100755 .github/scripts/codacy-configs.py create mode 100644 .github/scripts/phpcs-ruleset-dump.php create mode 100644 phpcs-wordpress.xml create mode 100644 phpmd-extra.xml diff --git a/.codacy.yml b/.codacy.yml index dda7592..280ceb2 100644 --- a/.codacy.yml +++ b/.codacy.yml @@ -1,5 +1,10 @@ --- # Codacy configuration +# +# With each tool's "Configuration file" setting on, Codacy reads phpcs.xml, phpmd.xml, and +# .markdownlint.json. Codacy installs no WordPress standards or packages, so those files hold only +# what it can run; CI runs the full configurations (phpcs-wordpress.xml, phpmd.xml with phpmd-extra.xml). +# See CONTRIBUTING.md. engines: # Lizard reads the lock files as source code and reports their length. diff --git a/.distignore b/.distignore index c5962ac..ae4480b 100644 --- a/.distignore +++ b/.distignore @@ -65,7 +65,9 @@ /package.json /package-lock.json /phpcs.xml +/phpcs-wordpress.xml /phpmd.xml +/phpmd-extra.xml /phpstan.neon /phpunit.xml /psalm.xml diff --git a/.gitattributes b/.gitattributes index 6f1fd0a..7988813 100644 --- a/.gitattributes +++ b/.gitattributes @@ -19,7 +19,9 @@ /package.json export-ignore /package-lock.json export-ignore /phpcs.xml export-ignore +/phpcs-wordpress.xml export-ignore /phpmd.xml export-ignore +/phpmd-extra.xml export-ignore /phpstan.neon export-ignore /phpunit.xml export-ignore /psalm.xml export-ignore diff --git a/.github/ISSUE_TEMPLATE/phpcs-failure.md b/.github/ISSUE_TEMPLATE/phpcs-failure.md index 1c76cc9..fd818e5 100644 --- a/.github/ISSUE_TEMPLATE/phpcs-failure.md +++ b/.github/ISSUE_TEMPLATE/phpcs-failure.md @@ -32,7 +32,7 @@ If PHPCS reached analysis, inspect its output for violations of the configured s 5. **PHPCompatibilityWP**: Rules configured for PHP 8.3 and later 6. **Modernize and NormalizedArrays**: Selected modernization and array checks -The root `phpcs.xml` is authoritative for exclusions and individual rules, +The root `phpcs-wordpress.xml` is authoritative for exclusions and individual rules (`phpcs.xml`, which Codacy reads, is generated from it), including two PSR-2 declaration rules. This is not a full PSR-12 scan. The locked stable compatibility rules miss some newer APIs; inspect the workflow's compatibility-control diagnostics before drawing a PHP-minimum conclusion. diff --git a/.github/labeler.yml b/.github/labeler.yml index a99a942..88fa88c 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -64,7 +64,9 @@ testing: - any-glob-to-any-file: tests/**/* - any-glob-to-any-file: phpunit.xml - any-glob-to-any-file: phpcs.xml + - any-glob-to-any-file: phpcs-wordpress.xml - any-glob-to-any-file: phpmd.xml + - any-glob-to-any-file: phpmd-extra.xml - any-glob-to-any-file: phpstan.neon - any-glob-to-any-file: psalm.xml - any-glob-to-any-file: rector.php diff --git a/.github/scripts/codacy-configs.py b/.github/scripts/codacy-configs.py new file mode 100755 index 0000000..489be63 --- /dev/null +++ b/.github/scripts/codacy-configs.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Regenerate the lint configuration files that Codacy reads from the full ones that CI runs. + +Codacy reads phpcs.xml and .stylelintrc.json, but it installs no WordPress coding standards, no +PHPCSExtra, and none of the WordPress Stylelint packages, so a file that names them makes the +tool fail. The full standards stay in phpcs-wordpress.xml and stylelint-wordpress.json, which +composer, npm, and CI run; this script copies into the Codacy files every rule of the full +standards that Codacy can run, with the settings the full standards give it. + + python .github/scripts/codacy-configs.py phpcs [--check] + python .github/scripts/codacy-configs.py stylelint [--check] + +With --check, nothing is written; the script fails when the file is out of date. phpcs needs +`composer install`; stylelint needs `npm ci`. +""" + +from __future__ import annotations + +import argparse +import json +import shutil +import subprocess # nosec B404 +import sys +import tempfile +from pathlib import Path +from typing import Any +from xml.sax.saxutils import escape, quoteattr # nosec B406 + +# Bandit: every subprocess call in this file runs a fixed argument list without a shell, and +# xml.sax.saxutils only escapes the text this file writes; nothing here parses XML. + +ROOT = Path(__file__).resolve().parents[2] +SCRIPTS = Path(__file__).resolve().parent + +# PHPCS standards that Codacy installs. PHPCompatibilityWP is referenced as a whole standard in +# phpcs.xml's hand-written part, so its sniffs are not listed one by one. +CODACY_PHPCS_STANDARDS = ("Generic", "PEAR", "PSR1", "PSR2", "PSR12", "Squiz", "Zend", "VariableAnalysis") +BEGIN = " " +END = " " +# A message code (Standard.Category.Sniff.Code) has three dots; a sniff code has two. +MESSAGE_CODE_DOTS = 3 + + +def run(command: list[str]) -> str: + """Run a command from the repository root and return its standard output.""" + result = subprocess.run( # nosec B603 + command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", check=False + ) + if not result.stdout.strip(): + sys.exit(f"{' '.join(command)} printed nothing:\n{result.stderr}") + return result.stdout + + +def property_xml(name: str, value: object, pad: str) -> list[str]: + """Write one PHPCS sniff property, a scalar or an array.""" + if isinstance(value, dict): + items = [f"{pad} " for k, v in value.items()] + elif isinstance(value, list): + items = [f"{pad} " for v in value] + else: + return [f"{pad}"] + return [f'{pad}', *items, f"{pad}"] + + +def rule_xml(code: str, settings: dict[str, Any]) -> list[str]: + """Write one PHPCS rule with its severity, type, message, and properties.""" + inner = [f" <{key}>{settings[key]}" for key in ("severity", "type") if key in settings] + if "message" in settings: + inner.append(f" {escape(settings['message'])}") + if settings.get("properties"): + inner.append(" ") + for name, value in settings["properties"].items(): + inner += property_xml(name, value, " ") + inner.append(" ") + if not inner: + return [f" "] + return [f" ", *inner, " "] + + +def phpcs_rules() -> str: + """Return the rules of phpcs-wordpress.xml that come from standards Codacy installs.""" + with tempfile.TemporaryDirectory() as tmp: + probe = Path(tmp) / "probe.php" + probe.write_text(" bool: + """Rewrite the generated part of phpcs.xml.""" + path = ROOT / "phpcs.xml" + text = path.read_text(encoding="utf-8") + head, rest = text.split(BEGIN + "\n", 1) + _, tail = rest.split(END, 1) + return write(path, text, f"{head}{BEGIN}\n{phpcs_rules()}\n{END}{tail}", check=check) + + +def update_stylelint(*, check: bool) -> bool: + """Rewrite .stylelintrc.json with the plain Stylelint rules of stylelint-wordpress.json.""" + npx = shutil.which("npx") or "npx" + sample = min(path for path in ROOT.glob("**/*.css") if not {"node_modules", "vendor"} & set(path.parts)) + command = [npx, "--no-install", "stylelint", "--config", "stylelint-wordpress.json", "--print-config"] + resolved = json.loads(run([*command, sample.relative_to(ROOT).as_posix()])) + # Rules with a "/" come from plugins, which Codacy does not install. + rules = {name: value for name, value in sorted(resolved["rules"].items()) if "/" not in name} + path = ROOT / ".stylelintrc.json" + text = path.read_text(encoding="utf-8") if path.exists() else "" + return write(path, text, json.dumps({"rules": rules}, indent=2) + "\n", check=check) + + +def write(path: Path, old: str, new: str, *, check: bool) -> bool: + """Write a regenerated file, or with check only report whether it is up to date.""" + if old == new: + return True + if check: + print(f"{path.name} is out of date: run python .github/scripts/codacy-configs.py", file=sys.stderr) + return False + path.write_text(new, encoding="utf-8", newline="\n") + print(f"updated {path.name}") + return True + + +def main() -> int: + """Regenerate or check one Codacy configuration file.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("tool", choices=("phpcs", "stylelint")) + parser.add_argument("--check", action="store_true", help="fail when the file is out of date; write nothing") + args = parser.parse_args() + update = update_phpcs if args.tool == "phpcs" else update_stylelint + return 0 if update(check=args.check) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/phpcs-ruleset-dump.php b/.github/scripts/phpcs-ruleset-dump.php new file mode 100644 index 0000000..a6d4222 --- /dev/null +++ b/.github/scripts/phpcs-ruleset-dump.php @@ -0,0 +1,56 @@ +ruleset; + $out = ['sniffs' => array_keys($ruleset->sniffCodes), 'rules' => []]; + foreach ($ruleset->ruleset as $code => $settings) { + $entry = []; + foreach ($settings['properties'] ?? [] as $name => $value) { + $entry['properties'][$name] = is_array($value) && array_key_exists('value', $value) ? $value['value'] : $value; + } + foreach (['severity', 'type', 'message'] as $key) { + if (isset($settings[$key])) { + $entry[$key] = $settings[$key]; + } + } + $out['rules'][$code] = $entry; + } + echo json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL; + return true; + } + + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources = false, + $width = 80, + $interactive = false, + $toScreen = true + ) { + echo $cachedData; + } +} diff --git a/.github/workflows/wp-compatibility-test.yml b/.github/workflows/wp-compatibility-test.yml index a94ff34..179fa96 100644 --- a/.github/workflows/wp-compatibility-test.yml +++ b/.github/workflows/wp-compatibility-test.yml @@ -263,7 +263,10 @@ jobs: - name: Run PHPCS id: run_phpcs run: | - vendor/bin/phpcs --standard=phpcs.xml + # phpcs-wordpress.xml is the full standard. phpcs.xml, which Codacy reads, copies the rules + # Codacy can run from it; fail when that copy is out of date. + vendor/bin/phpcs --standard=phpcs-wordpress.xml + python3 .github/scripts/codacy-configs.py phpcs --check # Static scanner controls; never execute these incompatible PHP fixtures. CONTROL_DIR="$RUNNER_TEMP/optimizer-compat-controls" @@ -622,7 +625,7 @@ jobs: run: | # Use WordPress-specific PHPMD configuration (WordPress snake_case compatible) echo "Using WordPress-specific PHPMD configuration (WordPress snake_case compatible)..." - vendor/bin/phpmd analyze . --no-progress --format text --ruleset phpmd.xml --exclude vendor --exclude tests --exclude stubs --exclude .private --exclude node_modules + vendor/bin/phpmd analyze . --no-progress --format text --ruleset phpmd.xml --ruleset phpmd-extra.xml --exclude vendor --exclude tests --exclude stubs --exclude .private --exclude node_modules - name: Preserve diagnostic summary id: preserve_diagnostics diff --git a/.mypy.ini b/.mypy.ini index c3f94f4..b16fb11 100644 --- a/.mypy.ini +++ b/.mypy.ini @@ -3,4 +3,4 @@ strict = True warn_unreachable = True scripts_are_modules = True -files = .github/scripts/check-plugin-package.py, .github/scripts/check-wordpress-tested-up-to.py, .github/scripts/test-automation.py +files = .github/scripts/check-plugin-package.py, .github/scripts/codacy-configs.py, .github/scripts/check-wordpress-tested-up-to.py, .github/scripts/test-automation.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3403423..6a427c7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -96,9 +96,11 @@ enginescript-site-optimizer/ |-- SECURITY.md # Security policy |-- LICENSE # GPL license |-- composer.json # PHP dependencies and check scripts -|-- phpcs.xml # PHPCS configuration +|-- phpcs-wordpress.xml # PHPCS configuration (composer phpcs, CI) +|-- phpcs.xml # The part Codacy can run, generated from phpcs-wordpress.xml |-- phpstan.neon # PHPStan configuration -|-- phpmd.xml # PHPMD configuration +|-- phpmd.xml # PHPMD configuration (Codacy reads it with PHPMD 2) +|-- phpmd-extra.xml # PHPMD 3 rules (composer phpmd and CI pass both files) |-- psalm.xml # Psalm configuration |-- phpunit.xml # PHPUnit configuration |-- .distignore # Files left out of the release package @@ -107,6 +109,8 @@ enginescript-site-optimizer/ The release package holds the main plugin file, `uninstall.php`, `readme.txt`, `LICENSE`, `includes/`, and `languages/`. When you add a top-level file or directory, add it to `.distignore` and `.gitattributes` unless it must ship; `.github/scripts/check-plugin-package.py` fails when the package lists disagree. +Codacy reads `phpcs.xml`, and `phpmd.xml`, but it installs no WordPress coding standards, no PHPCSExtra, and only PHPMD 2. Keep those files to what Codacy installs; the full configurations add the rest. After changing `phpcs-wordpress.xml`, or updating their packages, regenerate the Codacy copies with `python .github/scripts/codacy-configs.py phpcs`. CI fails when they are out of date. + ## Making Changes ### Before You Start diff --git a/composer.json b/composer.json index d1a4908..7dc158a 100644 --- a/composer.json +++ b/composer.json @@ -33,9 +33,9 @@ "rector/rector": "^2.6" }, "scripts": { - "phpcs": "phpcs --standard=phpcs.xml", - "phpcs:fix": "phpcbf --standard=phpcs.xml", - "phpmd": "phpmd analyze . --no-progress --format text --ruleset phpmd.xml --exclude vendor --exclude tests --exclude stubs --exclude .private --exclude node_modules", + "phpcs": "phpcs --standard=phpcs-wordpress.xml", + "phpcs:fix": "phpcbf --standard=phpcs-wordpress.xml", + "phpmd": "phpmd analyze . --no-progress --format text --ruleset phpmd.xml --ruleset phpmd-extra.xml --exclude vendor --exclude tests --exclude stubs --exclude .private --exclude node_modules", "psalm": "psalm --config=psalm.xml --show-info=true", "psalm:taint": "psalm --config=psalm.xml --taint-analysis", "phpstan": "phpstan analyze --memory-limit=1G", diff --git a/phpcs-wordpress.xml b/phpcs-wordpress.xml new file mode 100644 index 0000000..b75c976 --- /dev/null +++ b/phpcs-wordpress.xml @@ -0,0 +1,213 @@ + + + WordPress coding standards + + + . + + + */vendor/* + */.private/* + */node_modules/* + */tests/* + */.git/* + */.github/* + */build/* + */dist/* + */plugin-check-build/* + */stubs/* + *.css + *.js + + + + + + + + + + + + + + + + + + + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + 5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + *\.php$ + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/phpcs.xml b/phpcs.xml index b75c976..9e5b488 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -1,6 +1,17 @@ - - WordPress coding standards + + The parts of phpcs-wordpress.xml that Codacy can run. + + . @@ -19,184 +30,433 @@ *.css *.js - - - - + + + *\.php$ + - - - - - - - - - - + + - + + + + + + 1 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + 5 - - 5 + + error + The "goto" language construct should not be used. - - 5 + + + + + + 1 + + + - - 5 + + + + + + - - 5 + + + + + + - - 5 + + + + + + + + + + + + + + + - - 5 + + + 0 - + 5 - + 5 + warning - + 5 + warning - - 5 + + + + + + - - 5 + + + + 0 - + 5 - + 5 - - 5 + + + + + + 0 - - 5 + + 0 - - 5 + + 0 - - 5 + + 0 - - 5 + + + 0 - - 5 + + 0 - + + 5 - - 5 + + + + 0 - - 5 + + 0 + + + 0 - + + + + + 5 - + + + 5 - - - - - - - - - - - - - - + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + 0 + + + + 0 + + + + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + 0 + + + 0 + + + + 0 + + + 0 + + + 0 + + + - + + + - - - - - - - - + + 0 + + + + + 0 + + + 0 + + + 0 + + + + - + - - - - - - + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 5 + error + `eval()` is a security risk, please refrain from using it. + + + + - - - - + + - - - + + 0 + + + 5 + + + + + + + 5 + + + 5 + + - - - - + + - - - - - - - - - *\.php$ - - - - - - - - 0 + + 3 - - - + + 5 - - - - - - - + diff --git a/phpmd-extra.xml b/phpmd-extra.xml new file mode 100644 index 0000000..42e1c66 --- /dev/null +++ b/phpmd-extra.xml @@ -0,0 +1,23 @@ + + + + Rules that phpmd.xml leaves out because Codacy runs it with PHPMD 2. Composer and CI pass both files. + + */vendor/* + */.private/* + */node_modules/* + */tests/* + */stubs/* + + + + + + + + + diff --git a/phpmd.xml b/phpmd.xml index 5249870..2e45668 100644 --- a/phpmd.xml +++ b/phpmd.xml @@ -41,7 +41,9 @@ - + @@ -53,13 +55,6 @@ - - - - - - - From 88620b9d781257832b83d6c4c95bff01511ed124 Mon Sep 17 00:00:00 2001 From: Peter Downey Date: Wed, 25 Nov 2026 02:42:42 -0500 Subject: [PATCH 2/2] Note why the generator script's subprocess call and import are safe Codacy's Opengrep reports a subprocess call without a static string and the xml import as it does for any script; both are false positives here (a fixed argument list, and escaping only). nosemgrep notes sit beside the existing nosec notes, matching enginescript-site-exporter. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/codacy-configs.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/scripts/codacy-configs.py b/.github/scripts/codacy-configs.py index 489be63..21f9d10 100755 --- a/.github/scripts/codacy-configs.py +++ b/.github/scripts/codacy-configs.py @@ -24,10 +24,10 @@ import tempfile from pathlib import Path from typing import Any -from xml.sax.saxutils import escape, quoteattr # nosec B406 +from xml.sax.saxutils import escape, quoteattr # nosec B406 # nosemgrep -# Bandit: every subprocess call in this file runs a fixed argument list without a shell, and -# xml.sax.saxutils only escapes the text this file writes; nothing here parses XML. +# Bandit and Opengrep: every subprocess call in this file runs a fixed argument list without a +# shell, and xml.sax.saxutils only escapes the text this file writes; nothing here parses XML. ROOT = Path(__file__).resolve().parents[2] SCRIPTS = Path(__file__).resolve().parent @@ -43,7 +43,7 @@ def run(command: list[str]) -> str: """Run a command from the repository root and return its standard output.""" - result = subprocess.run( # nosec B603 + result = subprocess.run( # nosec B603 # nosemgrep command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", check=False ) if not result.stdout.strip():