Add writing operation to parser

This commit is contained in:
Tim Van Baak 2021-02-12 17:06:44 -08:00
parent 396f8d405a
commit c263d8b469
1 changed files with 39 additions and 10 deletions

View File

@ -23,6 +23,9 @@ class TabOptions:
def __init__(self, **kwargs) -> None:
self.options: dict = OrderedDict(**kwargs)
def to_json(self):
return self.options
@property
def priority(self) -> int:
"""Priority determines tab order."""
@ -68,6 +71,9 @@ class TagOptions:
# Hide the tag from unauthenticated viewers
self.private: bool = kwargs.get('private', False)
def to_json(self):
return self.options
@property
def hyperlink(self) -> bool:
return self.options.get(self._HYPERLINK_KEY, False)
@ -108,6 +114,13 @@ class DocumentSubtag:
self.value: str = value
self.options: TagOptions = options if options is not None else TagOptions()
def to_json(self):
return OrderedDict(
name=self.name,
value=self.value,
options=self.options.to_json(),
)
class DocumentTag:
"""
@ -125,6 +138,14 @@ class DocumentTag:
self.options: TagOptions = options if options is not None else TagOptions()
self.subtags: list = subtags if subtags is not None else []
def to_json(self):
return OrderedDict(
name=self.name,
value=self.value,
options=self.options.to_json(),
subtags=[subtag.to_json() for subtag in self.subtags],
)
class DocumentTab:
"""
@ -140,6 +161,13 @@ class DocumentTab:
self.tags: List[DocumentTag] = tags
self.options: TabOptions = options if options is not None else TabOptions()
def to_json(self):
return OrderedDict(
name=self.name,
tags=[tag.to_json() for tag in self.tags],
options=self.options.to_json(),
)
def get_tag(self, name: str):
for tag in self.tags:
if tag.name == name:
@ -154,6 +182,9 @@ class Document:
def __init__(self, tabs: List[DocumentTab]) -> None:
self.tabs: List[DocumentTab] = tabs
def to_json(self):
return [tab.to_json() for tab in self.tabs]
def __iter__(self):
return self.tabs.__iter__()
@ -186,16 +217,6 @@ def load(fd: IO) -> Document:
return parse_document_from_json(parsed_json)
def loads(string: str) -> Document:
"""
Load a document from a string.
"""
parsed_json = json.loads(string, object_pairs_hook=OrderedDict)
if not isinstance(parsed_json, list):
raise ValueError('Parsing as document, expected list')
return parse_document_from_json(parsed_json)
def parse_document_from_json(parsed_json: list) -> Document:
"""
Parses JSON into a Document object.
@ -292,6 +313,14 @@ def parse_subtag_from_json(subtag_json: dict) -> DocumentSubtag:
return DocumentSubtag(name, value, options)
def dump(doc: Document, fd: IO):
"""
Write a document to a file descriptor.
"""
dumped_json = doc.to_json()
json.dump(dumped_json, fd)
#
# CLI functions
#