Repository navigation
Rebuild the XML reference pages from the XSD files and validate samples in CI #109
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
DavidLambauer
wants to merge
7
commits into
main
Choose a base branch
from
docs/xml-reference-from-xsd
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+3,125
−1,526
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c9a25fd
Validate XML samples against the Mage-OS XSD files in CI
DavidLambauer 1ed41b6
Rename the cron_jobs.xml page to crontab.xml
DavidLambauer 97ab3b8
Rebuild the XML reference pages from the Mage-OS 4.0.0 XSD files
DavidLambauer 4dddd10
Correct the plugin sortOrder description and the events.xml related l…
DavidLambauer 96f628c
Limit the XML sample workflow to read-only repository access
DavidLambauer 4b623ff
Correct the XML reference pages after testing them on Mage-OS 4.0.0
DavidLambauer 74eb176
Say when an encrypted configuration value is returned decrypted
DavidLambauer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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[@]}" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.