Files
AVA2/tools/pack_assets.py
T

160 lines
5.0 KiB
Python
Executable File

#!/usr/bin/env python3
"""
AVA2 Cross-Platform Asset Packaging Tool
Scans, validates, packages, and verifies official AVA2/Metin2 client assets for distribution.
Generates an asset_manifest.json with SHA-256 integrity checksums.
"""
import os
import sys
import json
import hashlib
import shutil
import argparse
from pathlib import Path
DEFAULT_ASSET_DIRS = [
"mark",
"locale",
"uiscript",
"textureset",
"sound",
"runtime",
"upstream/python-root",
]
# Optional large 3D asset directory
OPTIONAL_ASSET_DIRS = [
"ymir work",
"bgm",
]
def compute_sha256(filepath):
h = hashlib.sha256()
with open(filepath, "rb") as f:
while chunk := f.read(65536):
h.update(chunk)
return h.hexdigest()
def package_assets(source_dir, output_dir, manifest_path=None, include_heavy=False):
source_path = Path(source_dir).resolve()
dest_path = Path(output_dir).resolve()
dest_path.mkdir(parents=True, exist_ok=True)
scan_dirs = list(DEFAULT_ASSET_DIRS)
if include_heavy:
scan_dirs.extend(OPTIONAL_ASSET_DIRS)
manifest = {
"version": "1.0.0",
"source": str(source_path),
"total_files": 0,
"total_bytes": 0,
"files": {}
}
print(f"[*] Packaging assets from {source_path} -> {dest_path}")
packaged_count = 0
total_bytes = 0
for rel_dir in scan_dirs:
src_dir_path = source_path / rel_dir
if not src_dir_path.exists():
continue
print(f" -> Scanning {rel_dir}...")
for root, dirs, files in os.walk(src_dir_path):
# Exclude build and hidden artifacts
dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "build", ".git")]
for file in files:
if file.startswith(".") or file.endswith(".pyc") or file.endswith(".tmp"):
continue
full_path = Path(root) / file
rel_to_source = full_path.relative_to(source_path)
target_file = dest_path / rel_to_source
target_file.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(full_path, target_file)
file_size = full_path.stat().st_size
file_hash = compute_sha256(full_path)
manifest["files"][str(rel_to_source).replace("\\", "/")] = {
"size": file_size,
"sha256": file_hash
}
packaged_count += 1
total_bytes += file_size
manifest["total_files"] = packaged_count
manifest["total_bytes"] = total_bytes
if manifest_path:
out_manifest = Path(manifest_path)
else:
out_manifest = dest_path / "asset_manifest.json"
out_manifest.parent.mkdir(parents=True, exist_ok=True)
with open(out_manifest, "w", encoding="utf-8") as f:
json.dump(manifest, f, indent=2, sort_keys=True)
print(f"[+] Packaged {packaged_count} files ({total_bytes / (1024*1024):.2f} MB)")
print(f"[+] Manifest written to {out_manifest}")
return manifest
def verify_assets(manifest_path, target_dir):
with open(manifest_path, "r", encoding="utf-8") as f:
manifest = json.load(f)
target_path = Path(target_dir).resolve()
print(f"[*] Verifying {manifest.get('total_files', 0)} assets in {target_path}...")
errors = []
verified = 0
for rel_path, meta in manifest.get("files", {}).items():
fp = target_path / rel_path
if not fp.exists():
errors.append(f"Missing file: {rel_path}")
continue
if fp.stat().st_size != meta["size"]:
errors.append(f"Size mismatch: {rel_path} (expected {meta['size']}, got {fp.stat().st_size})")
continue
actual_hash = compute_sha256(fp)
if actual_hash != meta["sha256"]:
errors.append(f"Hash mismatch: {rel_path}")
continue
verified += 1
if errors:
print(f"[-] Verification FAILED: {len(errors)} errors found:")
for err in errors[:10]:
print(f" - {err}")
return False
else:
print(f"[+] Verification SUCCESS: All {verified} files verified 100% OK!")
return True
def main():
parser = argparse.ArgumentParser(description="AVA2 Cross-Platform Asset Packaging Tool")
parser.add_argument("--source", default=".", help="Source client directory")
parser.add_argument("--output", default="dist/assets", help="Output packaged directory")
parser.add_argument("--manifest", default=None, help="Manifest output path")
parser.add_argument("--include-heavy", action="store_true", help="Include large 3D models and BGM")
parser.add_argument("--verify", default=None, help="Verify target directory against specified manifest")
args = parser.parse_args()
if args.verify:
success = verify_assets(args.verify, args.output)
sys.exit(0 if success else 1)
else:
package_assets(args.source, args.output, args.manifest, args.include_heavy)
if __name__ == "__main__":
main()