root | d8ab63c | 2017-07-25 07:19:31 +0000 | [diff] [blame] | 1 | import jsonpath_rw as jsonpath |
| 2 | import operator |
| 3 | |
| 4 | |
| 5 | class SimpleCondition(object): |
| 6 | op = None |
| 7 | |
| 8 | def check(self, value, expected): |
| 9 | return self.op(value, expected) |
| 10 | |
| 11 | |
| 12 | class EqCondition(SimpleCondition): |
| 13 | op = operator.eq |
| 14 | |
| 15 | OPERATORS = { |
| 16 | 'eq': EqCondition, |
| 17 | } |
| 18 | |
| 19 | class BaseRule(object): |
| 20 | |
| 21 | def __init__(self, field, op, val, multiple='first'): |
| 22 | self.field = field |
| 23 | self.op = op |
| 24 | self.value = val |
| 25 | self.multiple = multiple |
| 26 | |
| 27 | def check(self, pillar): |
| 28 | """Check if condition match in the passed pillar. |
| 29 | |
| 30 | :param pillar: pillar data to check for condition in. |
| 31 | :return: True if condition match, False otherwise. |
| 32 | """ |
| 33 | |
| 34 | res = False |
| 35 | count = 0 |
| 36 | for match in jsonpath.parse(self.field).find(pillar): |
| 37 | cond_ext = OPERATORS[self.op]() |
| 38 | res = cond_ext.check(match.value, self.value) |
| 39 | if (self.multiple == 'first' or |
| 40 | (self.multiple == 'all' and not res) or |
| 41 | (self.multiple == 'any' and res)): |
| 42 | break |
| 43 | elif self.multiple == 'multiple' and res: |
| 44 | count += 1 |
| 45 | if count > 1: |
| 46 | return True |
| 47 | |
| 48 | if not res or self.multiple == 'multiple': |
| 49 | return False |
| 50 | |
| 51 | return True |