import re

def complete(value):
    if value.startswith('[') and not value.endswith(']'):
        return False
    return True

def interpret(value):
    return eval(value) # good enough for now

class Metadata:
    def __init__(self, fn):
        self.text = open(fn, 'r').read()
        lines = filter(lambda l: not l.startswith("#") and not l.strip()=='', self.text.splitlines())
        d = {}
        parent = []
        node = d
        mode = 0
        for l in lines:
            if mode == 0:
                if l.strip() == '}':
                    node = parent[-1]
                    del parent[-1]
                elif l.strip().endswith('{'):
                    name = l.strip()[:-1].strip()
                    parent.append(node)
                    child = {}
                    node[name] = child
                    node = child
                else:
                    key, value = re.search(r'\t*(\S*) = (.*?)(\s*# .*)?$', l).groups()[0:2]
                    if not complete(value):
                        mode = 1
                    else:
                        node[key] = interpret(value)
            elif mode == 1:
                value += re.search(r'\t*(.*?)( *# .*)?$', l).group(0).strip()
                if complete(value):
                    node[key] = interpret(value)
                    mode = 0
        self.d = d

import pprint
pprint.pprint(Metadata('xenvg-backup').d)
