config.py 1.39 KB
# -*- coding: utf-8 -*-
import re
import os

SECTION = re.compile("^\[(.*)\]$")
SUBSECTION = re.compile("^\{(.*)\}$")
ENTRY = re.compile("^([^=\s]+)\s*=\s*([^=]+)\s*$")

def cut_comment(s):
    return s.split("#")[0]

class Config:

    def __init__(self, path):
        section = None
        subsection = None
        self.d = {}
        with open(path) as f:
            for line in f:
                line = cut_comment(line).strip()

                m = SECTION.search(line)
                if m is not None:
                    section = m.group(1)
                    subsection = None
                    continue

                m = SUBSECTION.search(line)
                if m is not None:
                    subsection = m.group(1)
                    continue

                m = ENTRY.search(line)
                if m is not None:
                    key = m.group(1)
                    val = m.group(2)
                    if subsection == "paths":
                        # print path, val, os.path.join(path, val)
                        val = self.relative_path(val, path)
                    if section is not None:
                        self.d[section + "." + key] = val
                    else:
                        self.d[key] = val

    def relative_path(self, path, ref):
        return os.path.join(os.path.dirname(ref), path)

    def __getitem__(self, key):
        return self.d[key]