|
1
2
3
4
5
6
7
8
|
'''
Created on 18 lut 2014
@author: mlenart
'''
import re
import codecs
|
|
9
|
from . import exceptions
|
|
10
11
|
def getHeaderValue(line, lineNum):
|
|
12
|
m = re.match(r'\s*\[(.*?)\]\s*(\#.*)?', line)
|
|
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:
|
|
29
|
raise exceptions.ConfigFileException(self.filename, lineNum, 'Invalid section: %s' % sectionName)
|
|
30
|
if sectionName in self.section2Lines:
|
|
31
|
raise exceptions.ConfigFileException(self.filename, lineNum, 'Duplicate section: %s' % sectionName)
|
|
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('#'):
|
|
39
|
raise exceptions.ConfigFileException(self.filename, lineNum, 'Text outside of any section')
|
|
40
41
42
|
self.section2Lines[self.currSection].append((lineNum, line))
def _getHeaderValue(self, line, lineNum):
|
|
43
|
m = re.match(r'\s*\[(.*?)\]\s*(\#.*)?', line)
|
|
44
45
46
47
48
|
if m:
return m.group(1)
else:
return None
|
|
49
50
|
def enumerateLinesInSection(self, sectionName, ignoreComments=True):
if sectionName not in self.section2Lines:
|
|
51
|
raise exceptions.ConfigFileException(self.filename, None, 'Missing section: "%s"' % sectionName)
|
|
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('#')]
|
|
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)
|