Created
August 10, 2015 17:32
-
-
Save hitsumabushi/97d20e416215bdc82665 to your computer and use it in GitHub Desktop.
example of parsimonious
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from parsimonious.grammar import Grammar | |
conf = """diag read interface-id 1 | |
enable | |
! | |
interfae vlan 1 | |
! | |
interface ip hoo | |
interface id | |
interface route | |
! | |
""" | |
class VdxConfig(object): | |
def __init__(self): | |
""" | |
blocks = (newline* block (newline block)* newline*) | |
block = (text continuation_line* newline block_close) | |
continuation_line = (newline indent text) | |
text = (token (space token)*) | |
block_close = "!" | |
indent = " " | |
newline = "\\n" | |
space = ~r" +" | |
token = ~r"[a-zA-Z0-9/-]+" | |
number = ~r"[0-9]+" | |
""" | |
def loads(self, node): | |
if isinstance(node, str): | |
node = Grammar(self.__init__.__doc__).parse(node) | |
method = getattr(self, node.expr_name, self.default) | |
return method(node, [self.loads(n) for n in node]) | |
def blocks(self, node, children): | |
# remove newline of beggining & ending | |
return children[1:-1] | |
def default(self, node, children): | |
return children | |
def block_close(self, node, children): | |
return "!" | |
def indent(self, node, children): | |
return " " | |
def newline(self, node, children): | |
return "\n" | |
def space(self, node, children): | |
return " " | |
def token(self, node, children): | |
return node.text | |
def number(self, node, children): | |
return node.text | |
def main(): | |
vdx = VdxConfig() | |
print(vdx.loads(conf)) | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment