cockatrice-custom-tokens/scripts/generate_xml.py

254 lines
12 KiB
Python

#!/usr/bin/env python3
"""Generate Cockatrice XML and stage artwork from sets/*/*.toml."""
import argparse
import datetime
from pathlib import Path
import re
import shutil
import tempfile
import tomllib
from urllib.parse import quote
import uuid
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
IMAGE_SUFFIXES = {'.png', '.jpg', '.jpeg', '.webp', '.gif'}
NAMESPACE = uuid.UUID('ea215c31-f89c-4d3f-8d53-72a15aad0f63')
def text(value, label):
if not isinstance(value, str) or not value.strip():
raise ValueError(f'{label}: expected a nonempty string')
if any(ord(c) < 32 and c not in '\n\r\t' for c in value):
raise ValueError(f'{label}: invalid XML control character')
return value
def filename(value, label):
text(value, label)
if value in ('.', '..') or any(c in value for c in '/\\') or any(ord(c) < 32 for c in value):
raise ValueError(f'{label}: expected a plain filename or name without slashes')
return value
def keys(table, allowed, label):
if not isinstance(table, dict):
raise ValueError(f'{label}: expected a TOML table')
unknown = table.keys() - allowed
if unknown:
raise ValueError(f'{label}: unknown field(s): {", ".join(sorted(unknown))}')
def render(folder):
data = {'tokens': []}
configs = sorted(folder.glob('*.toml'))
if not configs:
raise ValueError(f'{folder}: no TOML source files found')
for config in configs:
if config.is_symlink():
raise ValueError(f'Symlink source: {config}')
try:
with config.open('rb') as stream:
part = tomllib.load(stream)
keys(part, {'set', 'tokens'}, str(config))
if 'set' in part:
if 'set' in data:
raise ValueError('Declare [set] in exactly one TOML file per set')
data['set'] = part['set']
if 'tokens' in part:
if not isinstance(part['tokens'], list):
raise ValueError('tokens must be an array of tables')
data['tokens'].extend(part['tokens'])
except (ValueError, OSError) as error:
raise ValueError(f'{config}: {error}') from error
info = data.get('set', {})
keys(info, {'code', 'name', 'release_date', 'type', 'xml'}, 'set')
code = filename(info.get('code'), 'set.code')
if not re.fullmatch(r'[A-Za-z0-9_-]+', code) or code != folder.name:
raise ValueError(f'set.code must match directory name {folder.name}')
output_name = filename(info.get('xml', f'{code}.xml'), 'set.xml')
if not output_name.endswith('.xml'):
raise ValueError('set.xml must end with .xml')
date = info.get('release_date')
if isinstance(date, str):
date = datetime.date.fromisoformat(date)
if type(date) is not datetime.date:
raise ValueError('set.release_date must be a YYYY-MM-DD date')
root = ET.Element('cockatrice_carddatabase', version='4')
set_node = ET.SubElement(ET.SubElement(root, 'sets'), 'set')
for key, value in {'name': code, 'longname': text(info.get('name'), 'set.name'),
'settype': text(info.get('type', 'Custom'), 'set.type'),
'releasedate': date.isoformat()}.items():
ET.SubElement(set_node, key).text = value
tokens = data.get('tokens')
if not isinstance(tokens, list) or not tokens:
raise ValueError('Add at least one [[tokens]] entry')
cards = ET.SubElement(root, 'cards')
seen = {key: set() for key in ('id', 'name', 'number', 'uuid')}
artwork = {}
for path in sorted(folder.rglob('*')):
if path.is_symlink():
raise ValueError(f'Symlink source: {path}')
if path.is_file() and path.suffix.lower() in IMAGE_SUFFIXES and path.relative_to(folder).parts[0] == 'artwork':
if path.stat().st_size == 0:
raise ValueError(f'Empty artwork: {path}')
artwork[path.relative_to(folder).as_posix()] = path.read_bytes()
for index, token in enumerate(tokens, 1):
label = f'tokens[{index}]'
keys(token, {'id', 'name', 'description', 'artwork', 'number', 'uuid', 'rarity',
'type', 'mana_cost', 'colors', 'power', 'toughness', 'tablerow', 'properties', 'alternatives', 'render'}, label)
identifier = filename(token.get('id'), f'{label}.id')
name = filename(token.get('name'), f'{label}.name')
number = token.get('number', identifier)
if type(number) not in (str, int) or not str(number):
raise ValueError(f'{label}.number must be a nonempty string or integer')
text(str(number), f'{label}.number')
card_uuid = str(uuid.UUID(text(token['uuid'], f'{label}.uuid'))) if 'uuid' in token else str(uuid.uuid5(NAMESPACE, f'{code}/{identifier}'))
for key, value in {'id': identifier, 'name': name, 'number': str(number), 'uuid': card_uuid}.items():
if value in seen[key]:
raise ValueError(f'{label}: duplicate {key}: {value}')
seen[key].add(value)
description = text(token.get('description'), f'{label}.description').strip()
picture = text(token.get('artwork'), f'{label}.artwork')
if 'render' in token:
if (not picture.startswith('artwork/') or '..' in Path(picture).parts
or Path(picture).suffix != '.png' or Path(picture).as_posix() != picture):
raise ValueError(f'{label}: rendered artwork must be a PNG path under artwork/')
if picture in artwork:
raise ValueError(f'{label}: generated artwork would overwrite another image: {picture}')
from render_cards import render_card
artwork[picture] = render_card(folder, token)
if picture not in artwork:
raise ValueError(f'{label}: artwork must name an existing image under artwork/: {picture}')
card = ET.SubElement(cards, 'card')
ET.SubElement(card, 'name').text = name
ET.SubElement(card, 'text').text = description
card_type = text(token.get('type', 'Token'), f'{label}.type')
mana = token.get('mana_cost', '')
colors = token.get('colors', '')
if not isinstance(mana, str) or not isinstance(colors, str):
raise ValueError(f'{label}: mana_cost and colors must be strings')
props = {'layout': 'normal', 'side': 'front', 'type': card_type,
'maintype': card_type.split(' — ')[0], 'manacost': mana, 'cmc': '0',
'colors': colors, 'coloridentity': colors}
for key in ('power', 'toughness'):
if key in token:
if type(token[key]) not in (str, int):
raise ValueError(f'{label}.{key}: expected string or integer')
props[key] = str(token[key])
extra = token.get('properties', {})
if not isinstance(extra, dict):
raise ValueError(f'{label}.properties must be a table')
for key, value in extra.items():
if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_.-]*', key) or type(value) not in (str, int):
raise ValueError(f'{label}: invalid XML property {key}')
props[key] = str(value)
prop_node = ET.SubElement(card, 'prop')
for key, value in props.items():
if value:
text(value, f'{label}.{key}')
ET.SubElement(prop_node, key).text = value
ET.SubElement(card, 'set', rarity=text(token.get('rarity', 'common'), f'{label}.rarity'),
uuid=card_uuid, num=str(number),
picurl='https://assets.dandaedre.com/mtg/cards/' + quote(Path(picture).name)).text = code
alternatives = token.get('alternatives', [])
if not isinstance(alternatives, list):
raise ValueError(f'{label}.alternatives must be an array of tables')
alternative_ids = set()
for alternative in alternatives:
keys(alternative, {'id', 'artwork', 'number', 'uuid', 'rarity'}, f'{label}.alternatives')
alt_id = filename(alternative.get('id'), f'{label}.alternatives.id')
if alt_id in alternative_ids:
raise ValueError(f'{label}: duplicate alternative id: {alt_id}')
alternative_ids.add(alt_id)
alt_picture = text(alternative.get('artwork'), f'{label}.{alt_id}.artwork')
if alt_picture not in artwork:
raise ValueError(f'{label}: missing alternative artwork: {alt_picture}')
alt_number = alternative.get('number', f'{identifier}-{alt_id}')
if type(alt_number) not in (str, int):
raise ValueError(f'{label}: alternative number must be a string or integer')
text(str(alt_number), f'{label}.{alt_id}.number')
alt_uuid = (str(uuid.UUID(text(alternative['uuid'], f'{label}.{alt_id}.uuid')))
if 'uuid' in alternative else str(uuid.uuid5(NAMESPACE, f'{code}/{identifier}/alternatives/{alt_id}')))
for key, value in {'number': str(alt_number), 'uuid': alt_uuid}.items():
if value in seen[key]:
raise ValueError(f'{label}: duplicate {key}: {value}')
seen[key].add(value)
ET.SubElement(card, 'set', rarity=text(alternative.get('rarity', token.get('rarity', 'common')), 'alternative.rarity'),
uuid=alt_uuid, num=str(alt_number),
picurl='https://assets.dandaedre.com/mtg/cards/' + quote(Path(alt_picture).name)).text = code
ET.SubElement(card, 'token').text = '1'
row = token.get('tablerow', 3)
if type(row) is not int or row not in range(4):
raise ValueError(f'{label}.tablerow must be 0, 1, 2, or 3')
ET.SubElement(card, 'tablerow').text = str(row)
ET.indent(root, space=' ')
xml = ET.tostring(root, encoding='utf-8', xml_declaration=True) + b'\n'
return {Path(code) / output_name: xml, **{Path(code) / name: content for name, content in artwork.items()}}
def planned_files(sets):
result, public = {}, set()
folders = sorted(path for path in sets.iterdir() if path.is_dir())
if not folders:
raise ValueError(f'No sets found: {sets}')
for folder in folders:
if folder.is_symlink():
raise ValueError(f'Symlink set: {folder}')
if list(folder.glob('*.xml')):
raise ValueError(f'{folder}: move hand-maintained XML out of sets; edit the TOML sources instead')
try:
generated = render(folder)
except (ValueError, OSError) as error:
raise ValueError(f'{folder}: {error}') from error
for path in generated:
category = 'xml' if path.suffix == '.xml' else 'cards'
public_name = (category, path.name)
if public_name in public:
raise ValueError(f'Duplicate published filename: {path.name}')
public.add(public_name)
result.update(generated)
return result
def generate(sets, output, check=False):
expected = planned_files(sets)
if output.is_symlink():
raise ValueError(f'Symlink output: {output}')
if check:
actual = {}
for path in output.rglob('*'):
if path.is_symlink():
raise ValueError(f'Symlink generated file: {path}')
if path.is_file():
actual[path.relative_to(output)] = path.read_bytes()
if actual != expected:
raise ValueError('Generated XML/artwork are missing or stale; run python3 scripts/build.py')
return
output.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.generate-', dir=output.parent) as work:
staged = Path(work) / 'sets'
staged.mkdir()
for name, content in expected.items():
path = staged / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(content)
if output.exists():
shutil.rmtree(output)
staged.rename(output)
print(f'Generated {len(expected)} XML/artwork files in {output}')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check', action='store_true', help='Fail if generated output is missing or stale')
args = parser.parse_args()
try:
generate(ROOT / 'sets', ROOT / 'dist/sets', args.check)
except (ValueError, OSError) as error:
parser.exit(1, f'ERROR: {error}\n')
if __name__ == '__main__':
main()