Debian Codegraph @

ansible_collections/kubernetes/core/plugins/module_utils/selector.py

raw symbols SCIP
1 # Copyright [2021] [Red Hat, Inc.]
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import re
16
17
18 class Selector(object):
19 equality_based_operators = ("==", "!=", "=")
20
21 def __init__(self, data):
22 self._operator = None
23 self._data = None
24 if not self.parse_set_based_requirement(data):
25 no_whitespace_data = data.replace(" ", "")
26 for op in self.equality_based_operators:
27 idx = no_whitespace_data.find(op)
28 if idx != -1:
29 self._operator = "in" if op == "==" or op == "=" else "notin"
30 self._key = no_whitespace_data[0:idx]
31 # fmt: off
32 self._data = [no_whitespace_data[idx + len(op):]]
33 # fmt: on
34 break
35
36 def parse_set_based_requirement(self, data):
37 m = re.match(
38 r"( *)([a-z0-9A-Z][a-z0-9A-Z\._-]*[a-z0-9A-Z])( +)(notin|in)( +)\((.*)\)( *)",
39 data,
40 )
41 if m:
42 self._set_based_requirement = True
43 self._key = m.group(2)
44 self._operator = m.group(4)
45 self._data = [x.replace(" ", "") for x in m.group(6).split(",") if x != ""]
46 return True
47 elif all(x not in data for x in self.equality_based_operators):
48 self._key = data.rstrip(" ").lstrip(" ")
49 if self._key.startswith("!"):
50 self._key = self._key[1:].lstrip(" ")
51 self._operator = "!"
52 return True
53 return False
54
55 def isMatch(self, labels):
56 if self._operator == "in":
57 return self._key in labels and labels.get(self._key) in self._data
58 elif self._operator == "notin":
59 return self._key not in labels or labels.get(self._key) not in self._data
60 else:
61 return (
62 self._key not in labels
63 if self._operator == "!"
64 else self._key in labels
65 )
66
67
68 class LabelSelectorFilter(object):
69 def __init__(self, label_selectors):
70 self.selectors = [Selector(data) for data in label_selectors]
71
72 def isMatching(self, definition):
73 if "metadata" not in definition or "labels" not in definition["metadata"]:
74 return False
75 labels = definition["metadata"]["labels"]
76 if not isinstance(labels, dict):
77 return None
78 return all(sel.isMatch(labels) for sel in self.selectors)