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
7 changes: 7 additions & 0 deletions .codacy.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
---
# Codacy configuration
#
# With each tool's "Configuration file" setting on, Codacy reads phpcs.xml, phpmd.xml,
# eslint.config.mjs, .stylelintrc.json, .markdownlint.json, biome.json, .pylintrc, and bandit.yml.
# 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,
# eslint.wordpress.config.mjs, stylelint-wordpress.json) and the same Biome, Pylint, and Bandit
# files. See CONTRIBUTING.md.

engines:
# Lizard reads the lock files as source code and reports their length.
Expand Down
6 changes: 6 additions & 0 deletions .distignore
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,18 @@
/composer.json
/composer.lock
/eslint.config.mjs
/eslint.wordpress.config.mjs
/phpcs.xml
/bandit.yml
/biome.json
/phpcs-wordpress.xml
/phpmd.xml
/phpmd-extra.xml
/phpstan.neon
/package.json
/package-lock.json
/phpunit.xml
/stylelint-wordpress.json
/psalm.xml
/rector.php
/tslint.json
Expand Down
7 changes: 7 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,26 @@
/.yamllint.yml export-ignore
/composer.json export-ignore
/eslint.config.mjs export-ignore
/eslint.wordpress.config.mjs export-ignore
/composer.lock export-ignore
/CHANGELOG.md export-ignore
/CONTRIBUTING.md export-ignore
/GEMINI.md export-ignore
/package.json export-ignore
/package-lock.json export-ignore
/phpcs.xml export-ignore
/bandit.yml export-ignore
/.pylintrc export-ignore
/biome.json 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
/README.md export-ignore
/rector.php export-ignore
/stylelint-wordpress.json export-ignore
/SECURITY.md export-ignore
/stubs export-ignore
/tests export-ignore
Expand Down
4 changes: 2 additions & 2 deletions .github/ISSUE_TEMPLATE/lint-failure.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ The Python tools are installed from `.github/lint-requirements.txt`, which pins
- **Ruff** (`ruff check` and `ruff format --check`) on `.github/scripts`, with the rules in `.ruff.toml`.
- **mypy** in strict mode on `.github/scripts`, configured in `.mypy.ini`.
- **markdownlint** on every Markdown file that git does not ignore (`npm run lint:md`), with the rules in `.markdownlint.json`.
- **ESLint** with the WordPress JavaScript coding standards (`npm run lint:js`), configured in `eslint.config.mjs`.
- **Stylelint** on the plugin's CSS files (`npm run lint:css`), with the rules in `.stylelintrc.json`.
- **ESLint** with the WordPress JavaScript coding standards (`npm run lint:js`), configured in `eslint.wordpress.config.mjs` (the WordPress standards plus `eslint.config.mjs`, which Codacy reads).
- **Stylelint** on the plugin's CSS files (`npm run lint:css`), with the rules in `stylelint-wordpress.json` (`.stylelintrc.json`, which Codacy reads, is generated from it: `python .github/scripts/codacy-configs.py stylelint`).

### Next Steps

Expand Down
7 changes: 7 additions & 0 deletions .github/labeler.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,12 @@ testing:
- any-glob-to-any-file: stubs/**/*
- any-glob-to-any-file: phpunit.xml
- any-glob-to-any-file: phpcs.xml
- any-glob-to-any-file: bandit.yml
- any-glob-to-any-file: .pylintrc
- any-glob-to-any-file: biome.json
- 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 All @@ -67,6 +72,8 @@ testing:
- any-glob-to-any-file: .mypy.ini
- any-glob-to-any-file: .ruff.toml
- any-glob-to-any-file: eslint.config.mjs
- any-glob-to-any-file: eslint.wordpress.config.mjs
- any-glob-to-any-file: .github/lint-requirements.txt
- any-glob-to-any-file: .stylelintrc.json
- any-glob-to-any-file: stylelint-wordpress.json
- any-glob-to-any-file: .yamllint.yml
2 changes: 2 additions & 0 deletions .github/lint-requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# Linters that the lint job of wp-compatibility-test.yml installs.
# Renovate keeps the versions current.
actionlint-py==1.7.12.25
bandit==1.9.4
mypy==2.4.1
pylint==4.1.4
ruff==0.17.5
yamllint==1.38.0
zizmor==1.32.0
154 changes: 154 additions & 0 deletions .github/scripts/codacy-configs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
#!/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",
"SlevomatCodingStandard",
"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;
}
}
Loading
Loading