1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
|
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import logging
import shutil
import sys
from pathlib import Path
from subprocess import CalledProcessError, run
from xml.etree import ElementTree as ET
from scriptlib import SimulTemplateEntity, find_files
SIMUL_TEMPLATES_PATH = Path("simulation/templates")
ENTITY_RELAXNG_FNAME = "entity.rng"
RELAXNG_SCHEMA_ERROR_MSG = """Relax NG schema non existant.
Please create the file: {}
You can do that by running 'pyrogenesis -dumpSchema' in the 'system' directory
"""
XMLLINT_ERROR_MSG = (
"xmllint not found in your PATH, please install it (usually in libxml2 package)"
)
class SingleLevelFilter(logging.Filter):
def __init__(self, passlevel, reject):
self.passlevel = passlevel
self.reject = reject
def filter(self, record):
if self.reject:
return record.levelno != self.passlevel
return record.levelno == self.passlevel
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# create a console handler, seems nicer to Windows and for future uses
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
ch.setFormatter(logging.Formatter("%(levelname)s - %(message)s"))
f1 = SingleLevelFilter(logging.INFO, False)
ch.addFilter(f1)
logger.addHandler(ch)
errorch = logging.StreamHandler(sys.stderr)
errorch.setLevel(logging.WARNING)
errorch.setFormatter(logging.Formatter("%(levelname)s - %(message)s"))
logger.addHandler(errorch)
def main() -> int:
parser = argparse.ArgumentParser(description="Validate templates")
parser.add_argument("-m", "--mod-name", required=True, help="The name of the mod to validate.")
parser.add_argument(
"-r",
"--root",
dest="vfs_root",
default=Path(),
type=Path,
help="The path to mod's root location.",
)
parser.add_argument(
"-s",
"--relaxng-schema",
default=Path() / ENTITY_RELAXNG_FNAME,
type=Path,
help="The path to mod's root location.",
)
parser.add_argument(
"-t", "--templates", nargs="*", help="Optionally, a list of templates to validate."
)
parser.add_argument("-v", "--verbose", help="Be verbose about the output.", default=False)
args = parser.parse_args()
if not args.relaxng_schema.exists():
logging.error(RELAXNG_SCHEMA_ERROR_MSG.format(args.relaxng_schema))
return 1
if not shutil.which("xmllint"):
logging.error(XMLLINT_ERROR_MSG)
return 2
if args.templates:
templates = sorted([(Path(t), None) for t in args.templates])
else:
templates = sorted(
find_files(args.vfs_root, [args.mod_name], SIMUL_TEMPLATES_PATH.as_posix(), "xml")
)
simul_template_entity = SimulTemplateEntity(args.vfs_root, logger)
count, failed = 0, 0
for fp, _ in templates:
if fp.stem.startswith("template_"):
continue
path = fp.as_posix()
if path.startswith(
(
f"{SIMUL_TEMPLATES_PATH.as_posix()}/mixins/",
f"{SIMUL_TEMPLATES_PATH.as_posix()}/special/",
)
):
continue
if args.verbose:
logger.info("Parsing %s...", fp)
count += 1
entity = simul_template_entity.load_inherited(
SIMUL_TEMPLATES_PATH, str(fp.relative_to(SIMUL_TEMPLATES_PATH)), [args.mod_name]
)
xmlcontent = ET.tostring(entity, encoding="unicode")
try:
run(
["xmllint", "--relaxng", str(args.relaxng_schema.resolve()), "-"],
input=xmlcontent,
encoding="utf-8",
capture_output=True,
text=True,
check=True,
)
except CalledProcessError as e:
failed += 1
if e.stderr:
logger.exception(e.stderr)
if e.stdout:
logger.info(e.stdout)
logger.info("Total: %s; failed: %s", count, failed)
return 0
if __name__ == "__main__":
raise SystemExit(main())
|