1 import sys, marshal
2
3 from Ft.Xml.Domlette import NonvalidatingReader, Element
4 from Ft.Lib import Uri
8
9
10 ___STORAGE = 'data/db.rules'
11
12
13
14
15
16 @staticmethod
18 """Parse the rules defined in the xml to the python
19 data structure and marshal it to ___STORAGE
20
21 The data structure is a list of rules. Rules are hashes
22 that have the keys name, type, priority and message. As
23 well as keys for subrules and params which are lists with
24 the subsequent entries.
25 """
26 file_uri = Uri.OsPathToUri(aFilename)
27 doc = NonvalidatingReader.parseUri(file_uri)
28
29
30
31 rules = doc.xpath('//rule')
32 rs = []
33 for rule in rules:
34 r = {}
35 subrules = []
36 r['name'] = rule.attributes[(None, 'name')].value
37 r['type'] = rule.attributes[(None, 'type')].value
38 r['priority'] = rule.attributes[(None, 'priority')].value
39 for child in rule.childNodes:
40
41
42 if not isinstance(child, Element):
43 continue
44 if child.localName == 'message':
45 r['message'] = child.firstChild.nodeValue
46 elif child.localName == 'subrule':
47
48 subrule = {}
49 constraints = []
50 subrule['name'] = child.attributes[(None, 'name')].value
51 for sc in child.childNodes:
52 constraint = {}
53 if not isinstance(sc, Element):
54 continue
55 if sc.localName == 'head':
56 subrule['head'] = sc.attributes[(None, 'element')].value
57 elif sc.localName == 'target':
58 subrule['target'] = sc.attributes[(None, 'element')].value
59 elif sc.localName == 'constraint':
60 entries = []
61 constraint['name'] = sc.attributes[(None, 'name')].value
62 constraint['type'] = sc.attributes[(None, 'type')].value
63 for cons in sc.childNodes:
64 entry = {}
65 if not isinstance(cons, Element):
66 continue
67 if cons.localName == 'reference':
68 entry['type'] = 'reference'
69 entry['name'] = cons.attributes[(None, 'name')].value
70 if cons.localName == 'parameter':
71 entry['type'] = 'parameter'
72 entry['name'] = cons.attributes[(None, 'name')].value
73 entries.append(entry)
74 constraint['entries'] = entries
75 constraints.append(constraint)
76 subrule['constraints'] = constraints
77 subrules.append(subrule)
78 elif child.localName == 'param':
79 if not 'params' in r:
80 r['params'] = []
81
82 r['params'].append(child.attributes[(None, 'name')].value)
83
84 else:
85 print >> sys.stderr, "Unknown element: %s" % child.localName
86
87 r['subrules'] = subrules
88
89 rs.append(r)
90
91 ouf = open(RuleParser.___STORAGE, 'wb')
92 marshal.dump(rs, ouf)
93 ouf.close()
94
95
96
97 @staticmethod
100
101 @staticmethod
103 """Read the rules from the store"""
104 inf = open(RuleParser.___STORAGE)
105 r = marshal.load(inf)
106 inf.close()
107 return r
108