|
1 # |
|
2 # Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). |
|
3 # All rights reserved. |
|
4 # This component and the accompanying materials are made available |
|
5 # under the terms of "Eclipse Public License v1.0" |
|
6 # which accompanies this distribution, and is available |
|
7 # at the URL "http://www.eclipse.org/legal/epl-v10.html". |
|
8 # |
|
9 # Initial Contributors: |
|
10 # Nokia Corporation - initial contribution. |
|
11 # |
|
12 # Contributors: |
|
13 # |
|
14 # Description: |
|
15 # |
|
16 |
|
17 class ProblemTypeFilter(object): |
|
18 """ |
|
19 Class for filtering problem types. |
|
20 |
|
21 An instance of this class can be constructed with includes |
|
22 and excludes, and then it can be asked if a certain problem |
|
23 type matches and should be included. |
|
24 """ |
|
25 def __init__(self, includes, excludes): |
|
26 self._includes = [Pattern(expr) for expr in includes] |
|
27 self._excludes = [Pattern(expr) for expr in excludes] |
|
28 |
|
29 def match(self, problem_type): |
|
30 """ |
|
31 Check whether the given problem type matches the filter or not. |
|
32 @return: True if matches (should be included), False if not. |
|
33 """ |
|
34 # No filters: always match |
|
35 if not self._includes and not self._excludes: |
|
36 return True |
|
37 |
|
38 # Filter out entries that don't match includes |
|
39 if self._includes and not self._match(self._includes, problem_type): |
|
40 return False |
|
41 |
|
42 # Filter out entries that match excludes |
|
43 if self._excludes and self._match(self._excludes, problem_type): |
|
44 return False |
|
45 |
|
46 return True |
|
47 |
|
48 def filter(self, lst, key=lambda item: item.type): |
|
49 result = [] |
|
50 for item in lst: |
|
51 if self.match(key(item)): |
|
52 result.append(item) |
|
53 return result |
|
54 |
|
55 def _match(self, patterns, problem_type): |
|
56 for p in patterns: |
|
57 if p.match(problem_type): |
|
58 return True |
|
59 return False |
|
60 |
|
61 class Pattern(object): |
|
62 def __init__(self, pattern): |
|
63 self.elements = pattern.split('.') |
|
64 |
|
65 def match(self, problem_type): |
|
66 type_elements = problem_type.split('.') |
|
67 for i in xrange(max(len(type_elements), len(self.elements))): |
|
68 if i < len(type_elements): |
|
69 type_elem = type_elements[i] |
|
70 else: |
|
71 # The pattern is longer than the type, so it cannot |
|
72 # possibly match. |
|
73 # E.g. type = 'foo', pattern = 'foo.bar.baz' |
|
74 return False |
|
75 |
|
76 if i < len(self.elements): |
|
77 pattern_elem = self.elements[i] |
|
78 else: |
|
79 # The pattern ends and we have matched so far, so the |
|
80 # type is a sub-type of an included one. |
|
81 # E.g. type = 'foo.bar.baz', pattern = 'foo.bar' |
|
82 return True |
|
83 |
|
84 if pattern_elem != '*' and type_elem != pattern_elem: |
|
85 return False |
|
86 |
|
87 return True |
|
88 |