diff options
| author | kirigayakazima <46666711+kirigayakazima@users.noreply.github.com> | 2026-11-25 20:27:21 +0800 |
|---|---|---|
| committer | kirigayakazima <46666711+kirigayakazima@users.noreply.github.com> | 2026-11-25 20:27:21 +0800 |
| commit | 59eadb0be5ec32363711a447f305a35f36b0da34 (patch) | |
| tree | a3ff36a3d73c5b670ce1e4e3a23ce7b1c3d151fb /tools/script_qtable.py | |
| parent | 0d80bc5df7c873f40965f34f185cb96913786765 (diff) | |
tools: make script_qtable.py --json writes atomic and validate paths and hex stems
Diffstat (limited to 'tools/script_qtable.py')
| -rw-r--r-- | tools/script_qtable.py | 54 |
1 files changed, 44 insertions, 10 deletions
diff --git a/tools/script_qtable.py b/tools/script_qtable.py index 6c29a5260..d2e9096cf 100644 --- a/tools/script_qtable.py +++ b/tools/script_qtable.py | |||
| @@ -22,14 +22,17 @@ import json | |||
| 22 | import os | 22 | import os |
| 23 | import struct | 23 | import struct |
| 24 | import sys | 24 | import sys |
| 25 | import tempfile | ||
| 25 | 26 | ||
| 26 | # -I keeps the script directory off sys.path, so add it explicitly before importing sibling helpers. | 27 | # -I keeps the script directory off sys.path, so add it explicitly before importing sibling helpers. |
| 27 | TOOLS = os.path.dirname(os.path.abspath(__file__)) | 28 | TOOLS = os.path.dirname(os.path.abspath(__file__)) |
| 28 | if TOOLS not in sys.path: | 29 | if TOOLS not in sys.path: |
| 29 | sys.path.insert(0, TOOLS) | 30 | sys.path.insert(0, TOOLS) |
| 30 | 31 | ||
| 32 | from file_mode import published_mode # noqa: E402 | ||
| 31 | import gamedata_index as gi # noqa: E402 | 33 | import gamedata_index as gi # noqa: E402 |
| 32 | import gamedata_maps as gm # noqa: E402 | 34 | import gamedata_maps as gm # noqa: E402 |
| 35 | from replace_retry import replace as replace_retry # noqa: E402 | ||
| 33 | from report_paths import same_report_path # noqa: E402 | 36 | from report_paths import same_report_path # noqa: E402 |
| 34 | 37 | ||
| 35 | HEADER_BYTES = 40 | 38 | HEADER_BYTES = 40 |
| @@ -480,12 +483,11 @@ class _BinFolderSource: | |||
| 480 | if not os.path.isfile(full): | 483 | if not os.path.isfile(full): |
| 481 | continue | 484 | continue |
| 482 | sz = os.path.getsize(full) | 485 | sz = os.path.getsize(full) |
| 483 | try: | 486 | stem = os.path.splitext(name)[0] |
| 484 | off = int(os.path.splitext(name)[0], 16) | 487 | if stem and all(c in "0123456789abcdefABCDEF" for c in stem): |
| 485 | except ValueError: | 488 | hex_rows.append((int(stem, 16), name, sz)) |
| 486 | other_rows.append((name, sz)) | ||
| 487 | else: | 489 | else: |
| 488 | hex_rows.append((off, name, sz)) | 490 | other_rows.append((name, sz)) |
| 489 | hex_rows.sort(key=lambda item: (item[0], item[1])) | 491 | hex_rows.sort(key=lambda item: (item[0], item[1])) |
| 490 | next_off = (hex_rows[-1][0] + 0x10000) if hex_rows else 0 | 492 | next_off = (hex_rows[-1][0] + 0x10000) if hex_rows else 0 |
| 491 | self.rows = [{"off": off, "stored": sz, "size": sz, "_name": name} for off, name, sz in hex_rows] | 493 | self.rows = [{"off": off, "stored": sz, "size": sz, "_name": name} for off, name, sz in hex_rows] |
| @@ -534,6 +536,10 @@ def load_qtable_payload(target: str) -> tuple[bytes, dict]: | |||
| 534 | 536 | ||
| 535 | def check_report_path(out_path: str, target: str, rows: list[dict] | None = None) -> None: | 537 | def check_report_path(out_path: str, target: str, rows: list[dict] | None = None) -> None: |
| 536 | """Refuse a --json destination that is a directory or collides with any input.""" | 538 | """Refuse a --json destination that is a directory or collides with any input.""" |
| 539 | if not out_path.strip(): | ||
| 540 | raise UsageError("--json path must not be empty") | ||
| 541 | if out_path.endswith(("/", "\\")) or (os.sep and out_path.endswith(os.sep)): | ||
| 542 | raise UsageError(f"--json is a directory path: {out_path}") | ||
| 537 | if os.path.isdir(out_path): | 543 | if os.path.isdir(out_path): |
| 538 | raise UsageError(f"--json is a directory: {out_path}") | 544 | raise UsageError(f"--json is a directory: {out_path}") |
| 539 | if os.path.isdir(target): | 545 | if os.path.isdir(target): |
| @@ -589,6 +595,36 @@ def _print_summary(report: dict) -> None: | |||
| 589 | ) | 595 | ) |
| 590 | 596 | ||
| 591 | 597 | ||
| 598 | def _write_json_atomic(path: str, payload: dict) -> None: | ||
| 599 | dest = os.path.realpath(path) | ||
| 600 | parent = os.path.dirname(dest) or "." | ||
| 601 | os.makedirs(parent, exist_ok=True) | ||
| 602 | fd, tmp = tempfile.mkstemp(dir=parent, prefix=".tmp-", suffix=".json") | ||
| 603 | try: | ||
| 604 | try: | ||
| 605 | f = os.fdopen(fd, "w", encoding="utf-8", newline="\n") | ||
| 606 | except BaseException: | ||
| 607 | os.close(fd) | ||
| 608 | raise | ||
| 609 | with f: | ||
| 610 | json.dump(payload, f, indent=1) | ||
| 611 | f.write("\n") | ||
| 612 | f.flush() | ||
| 613 | os.fsync(f.fileno()) | ||
| 614 | os.chmod(tmp, published_mode(dest)) | ||
| 615 | replace_retry(tmp, dest) | ||
| 616 | except BaseException: | ||
| 617 | try: | ||
| 618 | os.chmod(tmp, 0o600) | ||
| 619 | except OSError: | ||
| 620 | pass | ||
| 621 | try: | ||
| 622 | os.unlink(tmp) | ||
| 623 | except OSError: | ||
| 624 | pass | ||
| 625 | raise | ||
| 626 | |||
| 627 | |||
| 592 | def main(argv=None) -> int: | 628 | def main(argv=None) -> int: |
| 593 | ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | 629 | ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 594 | ap.add_argument("target", help="carved script directory, script.rpf archive, or joined .bin file") | 630 | ap.add_argument("target", help="carved script directory, script.rpf archive, or joined .bin file") |
| @@ -600,7 +636,7 @@ def main(argv=None) -> int: | |||
| 600 | try: | 636 | try: |
| 601 | root_h = _parse_hex_u32(a.root_hash) if a.root_hash is not None else None | 637 | root_h = _parse_hex_u32(a.root_hash) if a.root_hash is not None else None |
| 602 | type_h = _parse_hex_u32(a.type_hash) if a.type_hash is not None else None | 638 | type_h = _parse_hex_u32(a.type_hash) if a.type_hash is not None else None |
| 603 | if a.json: | 639 | if a.json is not None: |
| 604 | rows = gm._read_index_rows(a.target) if os.path.isdir(a.target) and os.path.isfile(os.path.join(a.target, "index.json")) else None | 640 | rows = gm._read_index_rows(a.target) if os.path.isdir(a.target) and os.path.isfile(os.path.join(a.target, "index.json")) else None |
| 605 | check_report_path(a.json, a.target, rows=rows) | 641 | check_report_path(a.json, a.target, rows=rows) |
| 606 | blob, meta = load_qtable_payload(a.target) | 642 | blob, meta = load_qtable_payload(a.target) |
| @@ -621,11 +657,9 @@ def main(argv=None) -> int: | |||
| 621 | out = {"location": meta, **report} | 657 | out = {"location": meta, **report} |
| 622 | _print_summary(out) | 658 | _print_summary(out) |
| 623 | 659 | ||
| 624 | if a.json: | 660 | if a.json is not None: |
| 625 | try: | 661 | try: |
| 626 | gm._make_parent(a.json) | 662 | _write_json_atomic(a.json, out) |
| 627 | with open(a.json, "w", encoding="utf-8", newline="\n") as f: | ||
| 628 | json.dump(out, f, indent=1) | ||
| 629 | except OSError as e: | 663 | except OSError as e: |
| 630 | print(f"ERROR: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) | 664 | print(f"ERROR: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) |
| 631 | return 2 | 665 | return 2 |