diff --git a/TODO b/TODO new file mode 100644 index 0000000..299a121 --- /dev/null +++ b/TODO @@ -0,0 +1,7 @@ +Python: + - More options for accessing a heck tree. + - automated testing + +Guile, C (or D), and Haxe: + - Initial implementation + diff --git a/python/heckformat/parse.py b/python/heckformat/parse.py index 19fa90b..23e6724 100644 --- a/python/heckformat/parse.py +++ b/python/heckformat/parse.py @@ -9,6 +9,8 @@ from .exceptions import HeckParseException HeckValue = TypeVar("HeckElement") | str | int | float +UNPARSED_MARKER = "%%% UNPARSED %%% " + class HeckElement: """ Container for a tree of HECKformat elements. @@ -30,11 +32,14 @@ class HeckElement: self.unparsed = False def flatten(self) -> Mapping: + """ + Convert a hecktree element into a dictionary. + """ output = {} for elm in self.children: elmval = [] if elm.unparsed: - nam = '%%%UNPARSED%%% '+elm.name + nam = UNPARSED_MARKER+elm.name val = '\n'.join(elm.values) if nam in output: output[nam] = '\n'.join([output[nam], val]) @@ -50,6 +55,37 @@ class HeckElement: output[elm.name] = elmval return output + def get_flat_value(self) -> Union[List, HeckValue]: + if not len(self.values): + return None + + if len(self.values) > 1: + return list(self.values) + + return self.values[0] + + def flatten_replace(self) -> Mapping: + """ + Convert a hecktree element into a dictionary (but don't try to merge values, just pretend each key is unique) + """ + output = {} + for elm in self.children: + if elm.unparsed: + nam = UNPARSED_MARKER+elm.name + val = '\n'.join(elm.values) + output[nam] = val + else: + elmval = None + if len(elm.children): + elmval = {} + elmval['children'] = elm.flatten_replace() + elmval['value'] = elm.get_flat_value() + else: + elmval = elm.get_flat_value() + output[elm.name] = elmval + return output + + def __str__(self): k='' if self.unparsed: