1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 from libxyz.parser import BaseParser
18 from libxyz.parser import SourceData
19 from libxyz.exceptions import XYZValueError
20 from libxyz.exceptions import ParseError
21
23 """
24 RegexpParser is used to parse statements based on regular expressions
25 It is only useful for parsing linear, non-structured files.
26 """
27
29 """
30 @param cbpool: Dictionary with compiled regexp as keys and
31 callback functions as values.
32 Upon matching regexp, callback will be called with
33 MatchObject as an argument. Callback function should
34 raise XYZValueError in case of any error and return
35 whatever otherwise.
36 """
37
38 super(RegexpParser, self).__init__()
39
40 self.cbpool = cbpool
41
42
43
45 """
46 Parse config
47 """
48
49 _lineno = 0
50 _source = SourceData(source, bytes=False)
51
52 for _line in _source:
53 _lineno += 1
54 _line = _line.strip()
55
56
57 if not _line:
58 continue
59
60 _matched = False
61
62 for _regexp in self.cbpool:
63 _res = _regexp.search(_line)
64
65 if _res is not None:
66 _matched = True
67 try:
68 self.cbpool[_regexp](_res)
69 except XYZValueError, e:
70 raise ParseError(_(u"%s: parse error on line %d: %s"\
71 % (_source.desc(), _lineno, e)))
72 else:
73 break
74
75 if not _matched:
76 raise ParseError(_(u"Unmatched line %d: %s" % (_lineno, _line)))
77