Skip to content
Open
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
167 changes: 167 additions & 0 deletions .github/scripts/validate_xml_samples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
#!/usr/bin/env python3
"""Validate the XML samples in the docs against the Mage-OS XSD files.

Usage:
validate_xml_samples.py --source <mageos-magento2 checkout> FILE.md [FILE.md ...]

Every fenced ```xml block that names its schema with xsi:noNamespaceSchemaLocation
is a complete file, so it is validated with xmllint against that schema. Blocks
without a schema location are fragments and are skipped. To skip a complete file
on purpose, for example a sample that shows a mistake, use ```xml no-validate as
the opening fence.

The urn:magento:* locations, including the ones the XSD files use to include each
other, are resolved through a generated XML catalog, the same way Magento's
UrnResolver maps them to files.
"""

import argparse
import os
import re
import subprocess
import sys
import tempfile
from pathlib import Path

OPENING_FENCE = re.compile(r"^(?P<indent> {0,3})(?P<fence>`{3,}|~{3,})(?P<info>.*)$")
SCHEMA_LOCATION = re.compile(r'xsi:noNamespaceSchemaLocation\s*=\s*"(?P<urn>[^"]+)"')
XMLLINT_ERROR = re.compile(r"^(?P<file>[^:]+):(?P<line>\d+): (?P<message>.+)$")

# Library components that have their own URN prefix instead of urn:magento:framework.
FRAMEWORK_LIBRARIES = {
"framework-amqp": "Amqp",
"framework-bulk": "Bulk",
"framework-message-queue": "MessageQueue",
}


def urn_prefixes(source: Path) -> dict:
"""Map each urn:magento:* prefix to the directory it points to."""
framework = source / "lib/internal/Magento/Framework"
prefixes = {"urn:magento:framework:": framework}
for urn_name, directory in FRAMEWORK_LIBRARIES.items():
prefixes[f"urn:magento:{urn_name}:"] = framework / directory
for vendor in sorted((source / "app/code").iterdir()):
if not vendor.is_dir():
continue
for module in sorted(vendor.iterdir()):
if module.is_dir():
prefixes[f"urn:magento:module:{vendor.name}_{module.name}:"] = module
return prefixes


def write_catalog(prefixes: dict, path: Path) -> None:
entries = []
for prefix, directory in prefixes.items():
target = directory.resolve().as_uri() + "/"
entries.append(f' <rewriteURI uriStartString="{prefix}" rewritePrefix="{target}"/>')
entries.append(f' <rewriteSystem systemIdStartString="{prefix}" rewritePrefix="{target}"/>')
path.write_text(
'<?xml version="1.0"?>\n'
'<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">\n'
+ "\n".join(entries)
+ "\n</catalog>\n",
encoding="utf-8",
)


def resolve(urn: str, prefixes: dict):
for prefix, directory in prefixes.items():
if urn.startswith(prefix):
return directory / urn[len(prefix):]
return None


def xml_blocks(path: Path):
"""Yield (first content line number, info string, content) for each fenced xml block."""
lines = path.read_text(encoding="utf-8").splitlines()
index = 0
while index < len(lines):
opening = OPENING_FENCE.match(lines[index])
if not opening:
index += 1
continue
fence = opening.group("fence")
info = opening.group("info").strip()
indent = len(opening.group("indent"))
closing = re.compile(rf"^ {{0,3}}{re.escape(fence[0])}{{{len(fence)},}}\s*$")
end = index + 1
while end < len(lines) and not closing.match(lines[end]):
end += 1
words = info.split()
if words and words[0].lower() == "xml":
body = [line[indent:] if line[:indent].strip() == "" else line for line in lines[index + 1:end]]
yield index + 2, words[1:], "\n".join(body) + "\n"
index = end + 1


def annotate(path: str, line: int, message: str) -> str:
if os.environ.get("GITHUB_ACTIONS") == "true":
return f"::error file={path},line={line}::{message}"
return f"{path}:{line}: {message}"


def validate(markdown: Path, prefixes: dict, catalog: Path, workdir: Path):
"""Return (number of samples checked, list of error lines)."""
checked, errors = 0, []
for first_line, flags, content in xml_blocks(markdown):
if "no-validate" in flags:
continue
location = SCHEMA_LOCATION.search(content)
if not location:
continue
checked += 1
urn = location.group("urn")
schema = resolve(urn, prefixes)
if schema is None or not schema.is_file():
errors.append(annotate(str(markdown), first_line, f"Unknown schema location {urn}"))
continue
sample = workdir / "sample.xml"
sample.write_text(content, encoding="utf-8")
result = subprocess.run(
["xmllint", "--noout", "--nonet", "--schema", str(schema), str(sample)],
capture_output=True,
text=True,
env={**os.environ, "XML_CATALOG_FILES": str(catalog)},
)
if result.returncode == 0:
continue
for raw in result.stderr.splitlines():
match = XMLLINT_ERROR.match(raw)
if "No precomputed value available" in raw:
continue
if match and match.group("file") == str(sample):
line = first_line + int(match.group("line")) - 1
errors.append(annotate(str(markdown), line, match.group("message")))
elif raw.strip() and not raw.endswith("fails to validate") and "^" not in raw:
errors.append(annotate(str(markdown), first_line, raw.strip()))
return checked, errors


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--source", required=True, type=Path, help="Checkout of mage-os/mageos-magento2")
parser.add_argument("files", nargs="+", type=Path, help="Markdown files to check")
args = parser.parse_args()

prefixes = urn_prefixes(args.source)
total, failures = 0, []
with tempfile.TemporaryDirectory() as tmp:
workdir = Path(tmp)
catalog = workdir / "catalog.xml"
write_catalog(prefixes, catalog)
for markdown in args.files:
if markdown.suffix != ".md" or not markdown.is_file():
continue
checked, errors = validate(markdown, prefixes, catalog, workdir)
total += checked
failures.extend(errors)

for failure in failures:
print(failure)
print(f"Checked {total} XML sample(s): {len(failures)} error(s).")
return 1 if failures else 0


if __name__ == "__main__":
sys.exit(main())
69 changes: 69 additions & 0 deletions .github/workflows/xml-samples.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
name: "✅ - Validate XML samples"

on:
push:
branches:
- main
paths:
- "**.md"
- .github/scripts/validate_xml_samples.py
- .github/workflows/xml-samples.yml
pull_request:
paths:
- "**.md"
- .github/scripts/validate_xml_samples.py
- .github/workflows/xml-samples.yml
# A manual run checks every page, not only the changed ones.
workflow_dispatch:

permissions:
contents: read

jobs:
validate:
name: "✅ - Check XML samples against the Mage-OS XSD files"
runs-on: ubuntu-latest
env:
# The Mage-OS release whose XSD files the samples must match. Bump it with each major release.
MAGEOS_REF: "4.0.0"

steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0

- name: "📥 - Fetch the XSD files of Mage-OS ${{ env.MAGEOS_REF }}"
run: |
git -c advice.detachedHead=false clone --quiet --depth 1 --branch "$MAGEOS_REF" --filter=blob:none --sparse \
https://github.com/mage-os/mageos-magento2.git "$RUNNER_TEMP/mageos"
git -C "$RUNNER_TEMP/mageos" sparse-checkout set --no-cone '*.xsd'
echo "Fetched $(git -C "$RUNNER_TEMP/mageos" ls-files '*.xsd' | wc -l) XSD files."

- name: "🔧 - Install xmllint"
run: command -v xmllint || { sudo apt-get update -q && sudo apt-get install -yq libxml2-utils; }

# Pull requests and pushes check only the Markdown files they change, so pages
# that predate this check don't block unrelated work.
- name: "✅ - Validate"
env:
EVENT: ${{ github.event_name }}
BASE_REF: ${{ github.base_ref }}
BEFORE: ${{ github.event.before }}
run: |
case "$EVENT" in
pull_request)
mapfile -t files < <(git diff --name-only --diff-filter=d "origin/$BASE_REF...HEAD" -- '*.md')
;;
push)
git cat-file -e "$BEFORE^{commit}" 2>/dev/null || BEFORE=HEAD~1
mapfile -t files < <(git diff --name-only --diff-filter=d "$BEFORE" HEAD -- '*.md')
;;
*)
mapfile -t files < <(git ls-files '*.md')
;;
esac
if [ "${#files[@]}" -eq 0 ]; then
echo "No Markdown changes to check."
exit 0
fi
python3 .github/scripts/validate_xml_samples.py --source "$RUNNER_TEMP/mageos" "${files[@]}"
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ navigation. This ensures everyone can find your valuable addition.
## 📄 Formatting & Structure

Every document you create should start with a `# Headline` and be followed by a `[TOC]`. This helps in generating the
Table of Contents. We plan to add help in the form of GitHub Actions to point out potential Layout Flaws, misspellings,
Table of Contents.

XML samples that show a whole file, with an `xsi:noNamespaceSchemaLocation`, are validated in CI against the XSD files
of the current Mage-OS release. Run the same check locally with
`python3 .github/scripts/validate_xml_samples.py --source <mageos-magento2 checkout> <page>.md`. To skip a sample on
purpose, for example one that shows a mistake, open its code fence with ` ```xml no-validate `. We plan to add help in the form of GitHub Actions to point out potential Layout Flaws, misspellings,
toxic language, non-inclusive language, or similar issues.

## 🗣 Tone & Voice
Expand Down
Loading
Loading