|
|
|
|
|
|
|
from panflute import Doc
|
|
|
|
|
|
|
|
class Context:
|
|
|
|
def __init__(self, doc: Doc, path: str, parent: 'Context'=None):
|
|
|
|
self.parent = parent
|
|
|
|
self._commands = {}
|
|
|
|
self.doc = doc
|
|
|
|
self.path = path
|
|
|
|
if self.get_metadata("flags", immediate=True) is None:
|
|
|
|
self.set_metadata("flags", {})
|
|
|
|
|
|
|
|
def get_command(self, command: str):
|
|
|
|
if command in self._commands:
|
|
|
|
return self._commands[command]
|
|
|
|
elif self.parent:
|
|
|
|
return self.parent.get_command(command)
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
def set_command(self, command: str, val):
|
|
|
|
self._commands[command] = val
|
|
|
|
|
|
|
|
def unset_command(self, command: str):
|
|
|
|
del self._commands[command]
|
|
|
|
|
|
|
|
def is_flag_set(self, flag: str):
|
|
|
|
if self.get_metadata("flags."+flag):
|
|
|
|
if self.get_metadata("flags."+flag):
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
elif self.parent:
|
|
|
|
return self.parent.is_flag_set(flag)
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
|
|
|
def set_flag(self, flag: str, val: bool):
|
|
|
|
self.set_metadata("flags."+flag, val)
|
|
|
|
|
|
|
|
def unset_flag(self, flag):
|
|
|
|
self.unset_metadata("flags."+flag)
|
|
|
|
|
|
|
|
def get_metadata(self, key, simple=True, immediate=False):
|
|
|
|
value = self.doc.get_metadata(key, None, simple)
|
|
|
|
if value is not None:
|
|
|
|
return value
|
|
|
|
elif self.parent and not immediate:
|
|
|
|
return self.parent.get_metadata(key)
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
def set_metadata(self, key, value):
|
|
|
|
meta = self.doc.metadata
|
|
|
|
key = key.split(".")
|
|
|
|
for k in key[:-1]:
|
|
|
|
meta = meta[k]
|
|
|
|
meta[key[-1]] = value
|
|
|
|
|
|
|
|
def unset_metadata(self, key):
|
|
|
|
meta = self.doc.metadata
|
|
|
|
key = key.split(".")
|
|
|
|
for k in key[:-1]:
|
|
|
|
meta = meta[k]
|
|
|
|
del meta.content[key[-1]] # A hack because MetaMap doesn't have a __delitem__
|
|
|
|
|