haldis/app/hlds/__init__.py

55 lines
1.4 KiB
Python
Raw Normal View History

2019-12-01 01:04:13 +01:00
#!/usr/bin/env python3
2020-01-24 15:47:29 +01:00
from glob import glob
from os import path, walk
2019-12-01 01:04:13 +01:00
from tatsu import parse as tatsu_parse
2020-01-24 15:47:29 +01:00
import itertools
2020-01-25 01:33:23 +01:00
from .models import Location
2019-12-01 01:04:13 +01:00
# TODO Use proper way to get resources, see https://stackoverflow.com/a/10935674
with open(path.join(path.dirname(__file__), "hlds.tatsu")) as fh:
2020-01-24 15:47:29 +01:00
GRAMMAR = fh.read()
2019-12-01 01:04:13 +01:00
2020-01-24 14:47:53 +01:00
def kind_comparer(compare_to):
2020-01-24 15:47:29 +01:00
return lambda item: item["kind"] == compare_to
2020-01-24 14:47:53 +01:00
2019-12-01 01:04:13 +01:00
def parse(menu):
2020-01-24 15:47:29 +01:00
parsed = tatsu_parse(GRAMMAR, menu)
return parsed
return dict((
*((att["key"], att["value"]) for att in parsed["attributes"]),
("id", parsed["id"]),
("name", parsed["name"]),
("choices", filter(kind_comparer("choice_declaration"), parsed["items_"])),
("bases", filter(kind_comparer("base"), parsed["items_"])),
))
def parse_file(filename):
with open(filename, "r") as fh:
return parse(fh.read())
def load_all():
# TODO Use proper way to get resources, see https://stackoverflow.com/a/10935674
data_dir = path.join(path.dirname(__file__), "..", "..", "data")
files = glob(path.join(data_dir, "**.hlds"))
menus = map(parse_file, files)
return list(itertools.chain.from_iterable(menus))
2019-12-01 01:04:13 +01:00
def main(filename):
2020-01-24 15:47:29 +01:00
import json
from tatsu.util import asjson
2019-12-01 01:04:13 +01:00
2020-01-24 15:47:29 +01:00
ast = parse_file(filename)
print(json.dumps(asjson(ast), indent="\t"))
2019-12-01 01:04:13 +01:00
if __name__ == "__main__":
2020-01-24 15:47:29 +01:00
import sys
main(*sys.argv[1:])