Add json2bin support for different processing modes for optional fields

This commit is contained in:
Rachel 2023-11-03 22:25:03 -07:00
parent b31e95b6ef
commit 771e19e1d0
2 changed files with 20 additions and 6 deletions

View File

@ -3,7 +3,7 @@ import pathlib
import subprocess
from argparse import ArgumentParser
from enum import Enum, Flag
from enum import Enum, Flag, auto
from types import FunctionType, LambdaType
@ -21,6 +21,12 @@ ARGPARSER.add_argument('--output-dir', required=True,
help='Output directory where generated files will be written')
class OptionalBehavior(Enum):
DISALLOW = 0
SKIP = auto()
PAD = auto()
class Parser():
__slots__ = ('registry', 'padding_index', 'field_index', 'alignment_index')
@ -52,7 +58,7 @@ class Parser():
size: int | tuple[int,int],
func: FunctionType | LambdaType,
const_type: type[Enum] | None = None,
optional: bool = False) -> 'Parser':
optional: OptionalBehavior = OptionalBehavior.DISALLOW) -> 'Parser':
'''
Register a function for processing a given key within the JSON
structure, along with a size of the field in bytes and any
@ -114,10 +120,14 @@ class Parser():
data_key = key[5:] # first 4 characters are a key-prefix
data_val = self._walk(data, data_key.split('.'))
if data_val == {} or data_val is None:
if optional:
if optional == OptionalBehavior.DISALLOW:
print(json.dumps(data, indent=4))
raise KeyError(data_key)
elif optional == OptionalBehavior.SKIP:
continue
elif optional == OptionalBehavior.PAD:
binary.extend((0).to_bytes(size, 'little'))
continue
print(json.dumps(data, indent=4))
raise KeyError(data_key)
binary.extend(parse_func(data_val, size, const_type))
return binary

View File

@ -11,9 +11,11 @@ from consts.pokemon import (
species
)
def table_line(move_id: int, level: int) -> bytes:
return ((move_id & 0x01FF) | ((level & 0x7F) << 9)).to_bytes(2, 'little', signed=False)
def parse_level_up_moves(table: dict, _size: int, _enum: None):
out = []
for key, value in table.items():
@ -31,7 +33,7 @@ def parse_level_up_moves(table: dict, _size: int, _enum: None):
SCHEMA = j2b.Parser() \
.register_name(lambda s: s) \
.register('learnset.level_up', 0, parse_level_up_moves, optional=True) \
.register('learnset.level_up', 0, parse_level_up_moves, optional=j2b.OptionalBehavior.SKIP) \
.pad(2, 0xff) \
.align(4)
@ -60,6 +62,8 @@ FORM_INDICES = {
'MOW': 507,
},
}
def indexer(file_path: pathlib.Path) -> int:
name = file_path.parent.stem.upper()
if name == '000': return 0