Blame view

fsabuilder/morfeuszbuilder/utils/configFile.py 2.24 KB
Michał Lenart authored
1
2
3
4
5
6
7
8
'''
Created on 18 lut 2014

@author: mlenart
'''

import re
import codecs
Marcin Woliński authored
9
from . import exceptions
Michał Lenart authored
10
11

def getHeaderValue(line, lineNum):
Marcin Woliński authored
12
    m = re.match(r'\s*\[(.*?)\]\s*(\#.*)?', line)
Michał Lenart authored
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    if m:
        return m.group(1)
    else:
        return None

class ConfigFile(object):

    def __init__(self, filename, sectionNames):
        self.filename = filename
        self.sectionNames = sectionNames
        self.section2Lines = {}
        self.currSection = None
        self._parse()

    def _addSectionStart(self, sectionName, lineNum):
        if not sectionName in self.sectionNames:
Michał Lenart authored
29
            raise exceptions.ConfigFileException(self.filename, lineNum, 'Invalid section: %s' % sectionName)
Michał Lenart authored
30
        if sectionName in self.section2Lines:
Michał Lenart authored
31
            raise exceptions.ConfigFileException(self.filename, lineNum, 'Duplicate section: %s' % sectionName)
Michał Lenart authored
32
33
34
35
36
37
38
        self.section2Lines[sectionName] = []
        self.currSection = sectionName

    def _addLine(self, line, lineNum):
        line = line.strip()
        if line:
            if self.currSection is None and not line.startswith('#'):
Michał Lenart authored
39
                raise exceptions.ConfigFileException(self.filename, lineNum, 'Text outside of any section')
Michał Lenart authored
40
41
42
            self.section2Lines[self.currSection].append((lineNum, line))

    def _getHeaderValue(self, line, lineNum):
Marcin Woliński authored
43
        m = re.match(r'\s*\[(.*?)\]\s*(\#.*)?', line)
Michał Lenart authored
44
45
46
47
48
        if m:
            return m.group(1)
        else:
            return None
Michał Lenart authored
49
50
    def enumerateLinesInSection(self, sectionName, ignoreComments=True):
        if sectionName not in self.section2Lines:
Marcin Woliński authored
51
            raise exceptions.ConfigFileException(self.filename, None, 'Missing section: "%s"' % sectionName)
Michał Lenart authored
52
53
54
55
        if not ignoreComments:
            return self.section2Lines[sectionName]
        else:
            return [(linenum, line) for (linenum, line) in self.section2Lines[sectionName] if not line.startswith('#')]
Michał Lenart authored
56
57
58
59
60
61
62
63
64

    def _parse(self):
        with codecs.open(self.filename, 'r', 'utf8') as f:
            for lineNum, line in enumerate(f, start=1):
                header = self._getHeaderValue(line, lineNum)
                if header:
                    self._addSectionStart(header, lineNum)
                else:
                    self._addLine(line, lineNum)