|
| 1 | +import re |
| 2 | + |
| 3 | + |
| 4 | +class Filter(object): |
| 5 | + def __init__(self, *args, **kwargs): |
| 6 | + pass |
| 7 | + |
| 8 | + @classmethod |
| 9 | + def from_config(cls, config): |
| 10 | + """ |
| 11 | + config: { |
| 12 | + 'type': 'include_any', |
| 13 | + 'rules': [], |
| 14 | + } |
| 15 | + """ |
| 16 | + cls_map = { |
| 17 | + sub_cls.name: sub_cls |
| 18 | + for sub_cls in cls.__subclasses__() |
| 19 | + } |
| 20 | + |
| 21 | + sub_cls = config['type'] |
| 22 | + rules = config['rules'] |
| 23 | + return cls_map[sub_cls](rules) |
| 24 | + |
| 25 | + def validate(self, text): |
| 26 | + raise NotImplementedError |
| 27 | + |
| 28 | + |
| 29 | +class IncludeAnyFilter(Filter): |
| 30 | + |
| 31 | + name = 'include_any' |
| 32 | + |
| 33 | + def __init__(self, rules): |
| 34 | + self.rules = [re.compile(regexp) for regexp in rules] |
| 35 | + |
| 36 | + def validate(self, text): |
| 37 | + for regexp in self.rules: |
| 38 | + if regexp.findall(text): |
| 39 | + return True |
| 40 | + |
| 41 | + return False |
| 42 | + |
| 43 | + |
| 44 | +class IncludeAllFilter(Filter): |
| 45 | + |
| 46 | + name = 'include_all' |
| 47 | + |
| 48 | + def __init__(self, rules): |
| 49 | + self.rules = [re.compile(regexp) for regexp in rules] |
| 50 | + |
| 51 | + def validate(self, text): |
| 52 | + for regexp in self.rules: |
| 53 | + if not regexp.findall(text): |
| 54 | + return False |
| 55 | + |
| 56 | + return True |
| 57 | + |
| 58 | + |
| 59 | +class ExcludeFilter(Filter): |
| 60 | + |
| 61 | + name = 'exclude' |
| 62 | + |
| 63 | + def __init__(self, rules): |
| 64 | + self.rules = [re.compile(regexp) for regexp in rules] |
| 65 | + |
| 66 | + def validate(self, text): |
| 67 | + for regexp in self.rules: |
| 68 | + if regexp.findall(text): |
| 69 | + return False |
| 70 | + |
| 71 | + return True |
0 commit comments