-
Notifications
You must be signed in to change notification settings - Fork 10
/
icon_resolver.py
61 lines (39 loc) · 1.14 KB
/
icon_resolver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import collections
import re
import pickle
class Rule:
prop = ''
expression = ''
value = ''
def __init__(self, prop: str, expression: str, value: str):
self.prop = prop
self.expression = expression
self.value = value
def match(self, data: dict) -> bool:
return re.match(self.expression, data[self.prop]) != None
class IconResolver:
_rules = []
_cache = {}
def __init__(self, rules):
self._rules = [self._parse_rule(rule) for rule in rules]
def resolve(self, app):
id = pickle.dumps(app)
if id in self._cache:
return self._cache[id]
for rule in self._rules:
if rule.match(app):
out = rule.value
break
self._cache[id] = out
return out
def _parse_rule(self, rule) -> Rule:
parts = rule[0].split('=', 1)
prop = 'class'
match = ''
if len(parts) > 1:
prop = parts[0]
match = parts[1]
else:
match = parts[0]
exp = re.escape(match).replace('\\*', '.+')
return Rule(prop, exp, rule[1])