Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .codacy.yml
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
2 changes: 2 additions & 0 deletions .distignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/phpcs-failure.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions .github/labeler.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
144 changes: 144 additions & 0 deletions .github/scripts/codacy-configs.py
Original file line number Diff line number Diff line change
@@ -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 # nosemgrep

# 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

# 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 = " <!-- BEGIN GENERATED RULES: python .github/scripts/codacy-configs.py phpcs -->"
END = " <!-- END GENERATED RULES -->"
# 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 # nosemgrep
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} <element key={quoteattr(str(k))} value={quoteattr(str(v))}/>" for k, v in value.items()]
elif isinstance(value, list):
items = [f"{pad} <element value={quoteattr(str(v))}/>" for v in value]
else:
return [f"{pad}<property name={quoteattr(name)} value={quoteattr(str(value))}/>"]
return [f'{pad}<property name={quoteattr(name)} type="array">', *items, f"{pad}</property>"]


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]}</{key}>" for key in ("severity", "type") if key in settings]
if "message" in settings:
inner.append(f" <message>{escape(settings['message'])}</message>")
if settings.get("properties"):
inner.append(" <properties>")
for name, value in settings["properties"].items():
inner += property_xml(name, value, " ")
inner.append(" </properties>")
if not inner:
return [f" <rule ref={quoteattr(code)}/>"]
return [f" <rule ref={quoteattr(code)}>", *inner, " </rule>"]


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("<?php\n", encoding="utf-8")
report = SCRIPTS / "phpcs-ruleset-dump.php"
command = ["php", "vendor/bin/phpcs", "--standard=phpcs-wordpress.xml", "-q", "--no-colors"]
dump = json.loads(run([*command, f"--report={report}", str(probe)]))
lines: list[str] = []
for sniff in sorted(dump["sniffs"]):
if sniff.split(".", 1)[0] not in CODACY_PHPCS_STANDARDS:
continue
lines += rule_xml(sniff, dump["rules"].get(sniff, {}))
for code, settings in sorted(dump["rules"].items()):
if code.startswith(sniff + ".") and code.count(".") == MESSAGE_CODE_DOTS and settings:
lines += rule_xml(code, settings)
return "\n".join(lines)


def update_phpcs(*, check: bool) -> 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())
56 changes: 56 additions & 0 deletions .github/scripts/phpcs-ruleset-dump.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php
/**
* A PHPCS report that prints the loaded ruleset's final state as JSON instead of findings:
* every registered sniff, and every rule-level setting (properties, severity, type, message)
* after all includes, exclusions, and overrides.
*
* .github/scripts/codacy-configs.py runs it to copy the WordPress standards' settings into phpcs.xml.
*/

declare(strict_types=1);

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Reports\Report;

class RulesetDumpReport implements Report
{
private static bool $done = false;

public function generateFileReport($report, File $phpcsFile, $showSources = false, $width = 80)
{
if (self::$done) {
return false;
}
self::$done = true;
$ruleset = $phpcsFile->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;
}
}
7 changes: 5 additions & 2 deletions .github/workflows/wp-compatibility-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion .mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 6 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading