diff --git a/tools/src/wtotools/cli/__init__.py b/tools/src/wtotools/cli/__init__.py new file mode 100644 index 0000000..b25d216 --- /dev/null +++ b/tools/src/wtotools/cli/__init__.py @@ -0,0 +1,24 @@ +"""Command line entry point for the development-side tools. + +Each group of commands lives in its own module and registers itself here: +- exe_commands: check-patches, patch-exe +- build_commands: build-gui +- script_commands: build-script-checker, check-scripts + +Run `wtotools --help` for the arguments of one command. +""" +from __future__ import annotations + +import argparse + +from . import build_commands, exe_commands, script_commands + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="wtotools", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + commands = parser.add_subparsers(dest="command", required=True) + for group in (exe_commands, build_commands, script_commands): + group.register(commands) + args = parser.parse_args(argv) + return args.handler(args) diff --git a/tools/src/wtotools/cli/__main__.py b/tools/src/wtotools/cli/__main__.py new file mode 100644 index 0000000..0476def --- /dev/null +++ b/tools/src/wtotools/cli/__main__.py @@ -0,0 +1,3 @@ +from . import main + +raise SystemExit(main()) diff --git a/tools/src/wtotools/cli/build_commands.py b/tools/src/wtotools/cli/build_commands.py new file mode 100644 index 0000000..8fa195a --- /dev/null +++ b/tools/src/wtotools/cli/build_commands.py @@ -0,0 +1,64 @@ +"""Commands that produce deployable files. + + wtotools build-gui --stock --out [--client client] [--force] + +Inputs, all under the client folder: +- overrides/ edit records for stock files (see wtotools.build.overrides) +- gui/ our own files, laid out exactly as their path inside gui.vromfs.bin + +The stock archive is only read. The output must be a different file, and an existing output +is replaced only with --force. +""" +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +from ..build import BuildError, OverrideError, build_script_archive, load_overrides +from ..vromfs.errors import VromfsFormatError + +GUI_ARCHIVE = "gui.vromfs.bin" +DEFAULT_CLIENT = Path("client") + + +def register(commands: argparse._SubParsersAction) -> None: + gui = commands.add_parser("build-gui", help="build gui.vromfs.bin from the stock one plus the client folder") + gui.add_argument("--stock", type=Path, required=True, help="the stock gui.vromfs.bin to read") + gui.add_argument("--out", type=Path, required=True, help="where to write the built archive") + gui.add_argument("--client", type=Path, default=DEFAULT_CLIENT, help="folder with overrides/ and gui/") + gui.add_argument("--force", action="store_true", help="overwrite an existing output file") + gui.set_defaults(handler=_build_gui) + + +def _build_gui(args: argparse.Namespace) -> int: + if args.out.resolve() == args.stock.resolve(): + print("refusing to write over the stock archive; choose a different --out", file=sys.stderr) + return 2 + if args.out.exists() and not args.force: + print(f"{args.out} already exists; pass --force to overwrite", file=sys.stderr) + return 2 + + try: + overrides = load_overrides(args.client / "overrides") + added = _added_files(args.client / "gui") + built, report = build_script_archive(GUI_ARCHIVE, args.stock.read_bytes(), overrides, added) + except (BuildError, OverrideError, VromfsFormatError) as error: + print(f"build failed, nothing was written: {error}", file=sys.stderr) + return 1 + + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_bytes(built) + print(report.summary) + for path in report.overridden: + print(f" edited {path}") + for path in report.added: + print(f" added {path}") + print(f"wrote {args.out}") + return 0 + + +def _added_files(root: Path) -> dict[str, bytes]: + if not root.is_dir(): + return {} + return {path.relative_to(root).as_posix(): path.read_bytes() for path in sorted(root.rglob("*")) if path.is_file()} diff --git a/tools/src/wtotools/cli.py b/tools/src/wtotools/cli/exe_commands.py similarity index 84% rename from tools/src/wtotools/cli.py rename to tools/src/wtotools/cli/exe_commands.py index f008940..6a99bb0 100644 --- a/tools/src/wtotools/cli.py +++ b/tools/src/wtotools/cli/exe_commands.py @@ -1,7 +1,7 @@ -"""Command line entry point for the development-side tools. +"""Commands that work on the game executable. wtotools check-patches --exe [--patches exe-patches] - wtotools patch-exe --exe --out [--patches exe-patches] + wtotools patch-exe --exe --out [--patches exe-patches] [--force] The input executable is only ever read. `patch-exe` refuses to write over its input and refuses an existing output unless --force is given, so it cannot modify a game install by @@ -13,17 +13,14 @@ import argparse import sys from pathlib import Path -from .exepatch import apply_writes, changed_ranges, load_patches, plan_patches -from .exepatch.assemble import disagreement -from .pe import PeImage +from ..exepatch import apply_writes, changed_ranges, load_patches, plan_patches +from ..exepatch.assemble import disagreement +from ..pe import PeImage DEFAULT_PATCHES = Path("exe-patches") -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(prog="wtotools", description=__doc__) - commands = parser.add_subparsers(dest="command", required=True) - +def register(commands: argparse._SubParsersAction) -> None: check = commands.add_parser("check-patches", help="locate and verify every patch, write nothing") _add_common(check) check.set_defaults(handler=_check_patches) @@ -34,9 +31,6 @@ def main(argv: list[str] | None = None) -> int: patch.add_argument("--force", action="store_true", help="overwrite an existing output file") patch.set_defaults(handler=_patch_exe) - args = parser.parse_args(argv) - return args.handler(args) - def _add_common(parser: argparse.ArgumentParser) -> None: parser.add_argument("--exe", type=Path, required=True, help="the game executable to read") @@ -84,7 +78,3 @@ def _patch_exe(args: argparse.Namespace) -> int: args.out.write_bytes(patched) print(f"wrote {args.out}") return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/src/wtotools/cli/script_commands.py b/tools/src/wtotools/cli/script_commands.py new file mode 100644 index 0000000..1ad7e22 --- /dev/null +++ b/tools/src/wtotools/cli/script_commands.py @@ -0,0 +1,49 @@ +"""Commands for syntax checking game scripts. + + wtotools build-script-checker [--source build/quirrel-source] [--out build/quirrel-check] + wtotools check-scripts [--checker build/quirrel-check/sq.exe] ... +""" +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +from ..scriptcheck import CheckerBuildError, build_checker, check_scripts, find_scripts + +DEFAULT_SOURCE = Path("build/quirrel-source") +DEFAULT_OUT = Path("build/quirrel-check") + + +def register(commands: argparse._SubParsersAction) -> None: + build = commands.add_parser("build-script-checker", help="compile the Quirrel syntax checker with MSVC") + build.add_argument("--source", type=Path, default=DEFAULT_SOURCE, help="Quirrel source checkout") + build.add_argument("--out", type=Path, default=DEFAULT_OUT, help="where to put sq.exe") + build.set_defaults(handler=_build) + + check = commands.add_parser("check-scripts", help="syntax-check .nut files") + check.add_argument("paths", type=Path, nargs="+", help=".nut files or folders containing them") + check.add_argument("--checker", type=Path, default=DEFAULT_OUT / "sq.exe", help="the compiled checker") + check.set_defaults(handler=_check) + + +def _build(args: argparse.Namespace) -> int: + try: + checker = build_checker(args.source, args.out) + except CheckerBuildError as error: + print(error, file=sys.stderr) + return 1 + print(f"built {checker}") + return 0 + + +def _check(args: argparse.Namespace) -> int: + if not args.checker.is_file(): + print(f"checker not found at {args.checker}; run build-script-checker first", file=sys.stderr) + return 2 + files = find_scripts(args.paths) + failures = check_scripts(args.checker, files) + for failure in failures: + print(f"FAIL {failure.path}\n {failure.message}") + print(f"{len(files) - len(failures)}/{len(files)} file(s) pass syntax and static checks") + return 1 if failures else 0 diff --git a/tools/src/wtotools/scriptcheck/__init__.py b/tools/src/wtotools/scriptcheck/__init__.py new file mode 100644 index 0000000..71e1e6e --- /dev/null +++ b/tools/src/wtotools/scriptcheck/__init__.py @@ -0,0 +1,14 @@ +"""Syntax checking for game scripts (.nut), development side only. + +The game's script language is Quirrel. We compile the upstream Quirrel command line tool +once and run it in `-syntax-check` mode, which parses a file to a syntax tree without +resolving imports, so our scripts can be checked without the game's native modules. + +Modules: +- build: compile the checker from a Quirrel source checkout with MSVC +- check: run the checker over script files and collect the failures +""" +from .build import CheckerBuildError, build_checker +from .check import ScriptFailure, check_scripts, find_scripts + +__all__ = ["CheckerBuildError", "ScriptFailure", "build_checker", "check_scripts", "find_scripts"] diff --git a/tools/src/wtotools/scriptcheck/build.py b/tools/src/wtotools/scriptcheck/build.py new file mode 100644 index 0000000..06eabbe --- /dev/null +++ b/tools/src/wtotools/scriptcheck/build.py @@ -0,0 +1,84 @@ +"""Compile the Quirrel command line tool (`sq`) from a source checkout. + +The source list is read from the checkout's own CMakeLists.txt files, so a newer Quirrel +checkout builds without editing this file. CMake itself is not needed: MSVC's `cl` is +driven directly through a response file. + +The checkout is expected at build/quirrel-source (git-ignored); docs/implementation notes records +which commit it is pinned to. +""" +from __future__ import annotations + +import re +import subprocess +from pathlib import Path + +DEFAULT_VCVARS = Path("C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Auxiliary/Build/vcvars64.bat") +CHECKER_NAME = "sq.exe" + +# (folder, CMake variable) pairs whose files make up the command line tool. +_SOURCE_LISTS = ( + ("squirrel", "SQUIRREL_SRC"), + ("squirrel/compiler", "COMPILER_SRC"), + ("sqstdlib", "SQSTDLIB_SRC"), + ("sqmodules", "SQMODULES_SRC"), +) +# Chosen by an if() in CMake rather than listed: we build without variable tracing. +_EXTRA_SOURCES = ("squirrel/vartracestub.cpp", "sq/sq.cpp", "sq/sq_test_natives.cpp") +_INCLUDE_DIRS = ("include", "internal", "squirrel", "squirrel/compiler", "helpers", "sqrat/include", "sqmodules", ".") +_FLAGS = ( + "/nologo", "/utf-8", "/EHsc", "/std:c++17", "/O1", "/MP", + "/D_SQ64", "/DSQ_VAR_TRACE_ENABLED=0", "/D_CRT_SECURE_NO_WARNINGS", + "/wd4244", "/wd4018", "/wd4267", +) + + +class CheckerBuildError(Exception): + pass + + +def build_checker(source: Path, out_dir: Path, vcvars: Path = DEFAULT_VCVARS) -> Path: + """Compile `sq.exe` into `out_dir` and return its path. Raises CheckerBuildError.""" + if not vcvars.is_file(): + raise CheckerBuildError(f"MSVC environment script not found: {vcvars}") + sources = collect_sources(source) + out_dir.mkdir(parents=True, exist_ok=True) + + response = out_dir / "sources.rsp" + response.write_text("\n".join(_response_lines(source, sources)) + "\n", encoding="utf-8") + # A single string, not a list: cmd.exe needs the inner quotes verbatim, and /s makes it + # strip only the outermost pair. + command = f'cmd /d /s /c "call "{vcvars}" >nul && cl @sources.rsp"' + completed = subprocess.run(command, cwd=out_dir, capture_output=True, text=True) + checker = out_dir / CHECKER_NAME + if completed.returncode != 0 or not checker.is_file(): + tail = "\n".join((completed.stdout + completed.stderr).splitlines()[-30:]) + raise CheckerBuildError(f"compiling the checker failed (exit {completed.returncode}):\n{tail}") + return checker + + +def collect_sources(source: Path) -> list[Path]: + files: list[Path] = [] + for folder, variable in _SOURCE_LISTS: + files.extend(_cmake_list(source / folder, variable)) + files.extend(source / item for item in _EXTRA_SOURCES) + missing = [path for path in files if not path.is_file()] + if missing: + raise CheckerBuildError(f"source checkout is incomplete, missing: {', '.join(map(str, missing[:5]))}") + return files + + +def _cmake_list(folder: Path, variable: str) -> list[Path]: + cmake = folder / "CMakeLists.txt" + if not cmake.is_file(): + raise CheckerBuildError(f"not a Quirrel source checkout: {cmake} is missing") + match = re.search(rf"set\({variable}\s+([^)]*)\)", cmake.read_text("utf-8")) + if match is None: + raise CheckerBuildError(f"{cmake} does not define {variable}") + return [folder / name for name in match[1].split()] + + +def _response_lines(source: Path, sources: list[Path]) -> list[str]: + includes = [f'/I"{(source / item).resolve()}"' for item in _INCLUDE_DIRS] + files = [f'"{path.resolve()}"' for path in sources] + return [*_FLAGS, *includes, *files, f"/Fe:{CHECKER_NAME}"] diff --git a/tools/src/wtotools/scriptcheck/check.py b/tools/src/wtotools/scriptcheck/check.py new file mode 100644 index 0000000..fd91ff2 --- /dev/null +++ b/tools/src/wtotools/scriptcheck/check.py @@ -0,0 +1,46 @@ +"""Run the Quirrel syntax checker over script files. + +Each file is parsed and run through Quirrel's static analyzer (`-syntax-check -sa`), in its +own process so a failure is attributed to exactly one file and one bad file cannot hide the +others. Analyzer warnings (unused bindings, suspicious expressions) count as failures: the +files we check are our own, and we keep them clean. + +Not covered: names that are not defined anywhere. Quirrel reports those only when it fully +compiles a file, and full compilation resolves imports, which needs the game's native modules. +""" +from __future__ import annotations + +import subprocess +from dataclasses import dataclass +from pathlib import Path + + +@dataclass(frozen=True) +class ScriptFailure: + path: Path + message: str + + +def check_scripts(checker: Path, files: list[Path]) -> list[ScriptFailure]: + """Return one ScriptFailure per file that does not parse; an empty list means all passed.""" + failures: list[ScriptFailure] = [] + for path in files: + completed = subprocess.run([str(checker), "-syntax-check", "-sa", str(path)], capture_output=True, text=True) + output = (completed.stderr + completed.stdout).strip() + if completed.returncode != 0 or _reports_problem(output): + failures.append(ScriptFailure(path, output or f"exit code {completed.returncode}")) + return failures + + +def _reports_problem(output: str) -> bool: + # sq.exe exits with 0 even when parsing fails; it then prints "Error [...]" on stderr. + # Analyzer findings start with "WARNING:". + return any(line.startswith(("Error [", "WARNING:")) for line in output.splitlines()) + + +def find_scripts(roots: list[Path]) -> list[Path]: + """Expand directories into the .nut files under them; files are taken as given.""" + found: list[Path] = [] + for root in roots: + found.extend(sorted(root.rglob("*.nut")) if root.is_dir() else [root]) + return found