132 lines
6.2 KiB
Python
132 lines
6.2 KiB
Python
"""Add reviewed gameplay assets to the pinned working GUI pack without replacing it."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path, PurePosixPath
|
|
import re
|
|
import urllib.request
|
|
import zipfile
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
SHARED = ROOT / 'network/resource-pack/shared'
|
|
GLYPHS = ROOT / 'JarvisConnector/src/main/resources/item-card-glyphs.json'
|
|
|
|
|
|
def entries(path):
|
|
result = {}
|
|
with zipfile.ZipFile(path) as archive:
|
|
for info in archive.infolist():
|
|
if info.is_dir():
|
|
continue
|
|
name = info.filename
|
|
if name in result or name.startswith('/') or '..' in PurePosixPath(name).parts or '\\' in name:
|
|
raise ValueError('Unsafe or duplicate pack entry: ' + name)
|
|
result[name] = archive.read(info)
|
|
if 'pack.mcmeta' not in result:
|
|
raise ValueError('Missing pack.mcmeta')
|
|
return result
|
|
|
|
|
|
def validate(files, glyphs):
|
|
font = json.loads(files['assets/dunerealms/font/card_art.json'])
|
|
available = set()
|
|
for provider in font['providers']:
|
|
if provider['type'] != 'bitmap':
|
|
continue
|
|
namespace, path = provider['file'].split(':', 1)
|
|
texture = f'assets/{namespace}/textures/{path}'
|
|
if not files.get(texture, b'').startswith(b'\x89PNG\r\n\x1a\n'):
|
|
raise ValueError('Missing card texture: ' + texture)
|
|
available.update(ord(char) for row in provider['chars'] for char in row)
|
|
if set(glyphs.values()) - available:
|
|
raise ValueError('Unmapped card glyphs')
|
|
for name, payload in files.items():
|
|
if name.startswith('assets/dunerealms/models/') and name.endswith('.json'):
|
|
for ref in json.loads(payload).get('textures', {}).values():
|
|
if not isinstance(ref, str) or ref.startswith('#'):
|
|
continue
|
|
namespace, leaf = ref.split(':', 1) if ':' in ref else ('minecraft', ref)
|
|
if namespace == 'dunerealms' and f'assets/{namespace}/textures/{leaf}.png' not in files:
|
|
raise ValueError('Missing model texture: ' + ref)
|
|
if name.startswith('assets/dunerealms/items/') and name.endswith('.json'):
|
|
def models(value):
|
|
if isinstance(value, dict):
|
|
if value.get('type') in ('model', 'minecraft:model') and isinstance(value.get('model'), str):
|
|
yield value['model']
|
|
for child in value.values():
|
|
yield from models(child)
|
|
elif isinstance(value, list):
|
|
for child in value:
|
|
yield from models(child)
|
|
for ref in models(json.loads(payload)):
|
|
namespace, leaf = ref.split(':', 1) if ':' in ref else ('minecraft', ref)
|
|
if namespace == 'dunerealms' and f'assets/{namespace}/models/{leaf}.json' not in files:
|
|
raise ValueError('Missing item model: ' + ref)
|
|
|
|
|
|
def build(baseline, output, shared=SHARED, glyph_path=GLYPHS):
|
|
baseline, output = Path(baseline), Path(output)
|
|
if baseline.resolve() == output.resolve():
|
|
raise ValueError('Output must differ from baseline')
|
|
original = entries(baseline)
|
|
files = dict(original)
|
|
overlay = {}
|
|
for source in sorted(Path(shared).rglob('*')):
|
|
if source.is_file():
|
|
name = source.relative_to(shared).as_posix()
|
|
if not name.startswith('assets/dunerealms/'):
|
|
raise ValueError('Only namespaced gameplay assets are allowed')
|
|
payload = source.read_bytes()
|
|
if name in original and original[name] != payload:
|
|
raise ValueError('Overlay would replace an existing asset: ' + name)
|
|
overlay[name] = payload
|
|
files.update(overlay)
|
|
glyphs = json.loads(Path(glyph_path).read_text())
|
|
validate(files, glyphs)
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
with zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_STORED) as archive:
|
|
for name, payload in sorted(files.items()):
|
|
info = zipfile.ZipInfo(name, (2026, 11, 29, 0, 0, 0))
|
|
info.create_system = 0
|
|
archive.writestr(info, payload)
|
|
actual = entries(output)
|
|
validate(actual, glyphs)
|
|
if actual != files or any(actual[name] != payload for name, payload in original.items()):
|
|
raise ValueError('Written archive changed existing GUI assets')
|
|
data = output.read_bytes()
|
|
manifest = {'filename': output.name, 'sha1': hashlib.sha1(data).hexdigest(),
|
|
'sha256': hashlib.sha256(data).hexdigest(), 'bytes': len(data),
|
|
'baselineSha256': hashlib.sha256(baseline.read_bytes()).hexdigest(),
|
|
'entries': len(actual), 'overlayEntries': len(overlay), 'cardMappings': len(glyphs)}
|
|
output.with_suffix('.manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
|
return manifest
|
|
|
|
|
|
def pinned_baseline(config, cache):
|
|
text = Path(config).read_text()
|
|
block = re.search(r'^world:\s*\n((?:[ \t]+[^\n]*\n)+)', text, re.M)
|
|
if not block:
|
|
raise ValueError('Missing world pack pin')
|
|
fields = dict(re.findall(r'^\s+(url|sha1):\s*(\S+)', block.group(1), re.M))
|
|
url, expected = fields['url'], fields['sha1']
|
|
if not url.startswith('https://www.dunerealms.com/downloads/') or not re.fullmatch('[0-9a-f]{40}', expected):
|
|
raise ValueError('Invalid baseline URL or hash')
|
|
with urllib.request.urlopen(url, timeout=90) as response:
|
|
payload = response.read()
|
|
if hashlib.sha1(payload).hexdigest() != expected:
|
|
raise ValueError('Published GUI pack differs from pin')
|
|
cache = Path(cache)
|
|
cache.parent.mkdir(parents=True, exist_ok=True)
|
|
cache.write_bytes(payload)
|
|
return cache
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
sources = parser.add_mutually_exclusive_group(required=True)
|
|
sources.add_argument('--baseline', type=Path)
|
|
sources.add_argument('--from-gui-config', type=Path)
|
|
parser.add_argument('--output', type=Path, required=True)
|
|
args = parser.parse_args()
|
|
source = args.baseline or pinned_baseline(args.from_gui_config, args.output.parent / 'baseline-gui.zip')
|
|
print(json.dumps(build(source, args.output), indent=2))
|

Staff