filtration 2.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
filtration/__init__.py ADDED
@@ -0,0 +1,218 @@
1
+ import datetime
2
+ import operator
3
+ import re
4
+ from functools import reduce
5
+
6
+ import ipcalc
7
+ from pyparsing import alphas, nums
8
+ from pyparsing import CaselessLiteral, Combine, Group, Keyword, Literal, MatchFirst, OneOrMore
9
+ from pyparsing import infix_notation, OpAssoc, Optional, ParseException, quoted_string
10
+ from pyparsing import QuotedString, remove_quotes, Suppress, Word, ZeroOrMore
11
+
12
+
13
+ class Token:
14
+ def __init__(self, toks):
15
+ compiler = getattr(self, "compiler", None)
16
+ if callable(compiler):
17
+ self.value = compiler(*toks) # pylint: disable=not-callable
18
+ else:
19
+ try:
20
+ self.value = toks[0]
21
+ except TypeError: # pragma: no cover
22
+ self.value = toks
23
+
24
+ def __call__(self, ctx):
25
+ # pylint: disable=unused-argument
26
+ return self.value
27
+
28
+
29
+ Year = Word(nums, max=4).set_parse_action(lambda toks: int(toks[0]))
30
+ Month = Word(nums, max=2).set_parse_action(lambda toks: int(toks[0]))
31
+ Day = Word(nums, max=2).set_parse_action(lambda toks: int(toks[0]))
32
+
33
+ Hour = Word(nums, max=2).set_parse_action(lambda toks: int(toks[0]))
34
+ Minute = Word(nums, max=2).set_parse_action(lambda toks: int(toks[0]))
35
+ Second = Word(nums, max=2).set_parse_action(lambda toks: int(toks[0]))
36
+
37
+ Date = (Year + Suppress("-") + Month + Suppress("-") + Day).set_parse_action(
38
+ lambda toks: datetime.datetime.combine(datetime.date(*toks), datetime.time.min)
39
+ )
40
+ Time = (Hour + Suppress(":") + Minute + Suppress(":") + Second).set_parse_action(
41
+ lambda toks: datetime.datetime.combine(datetime.date.today(), datetime.time(*toks))
42
+ )
43
+ DateTime = (Date + Suppress(Optional("T")) + Time).set_parse_action(
44
+ lambda toks: datetime.datetime.combine(toks[0].date(), toks[1].time())
45
+ )
46
+
47
+
48
+ class _Regex(Token):
49
+ def compiler(self, pattern, flags):
50
+ # pylint: disable=no-self-use
51
+ try:
52
+ return re.compile(pattern, flags)
53
+ except re.error as exc:
54
+ raise ParseException(str(exc)) from exc
55
+
56
+
57
+ RegexFlag = Word("ims", exact=1).set_parse_action(
58
+ lambda toks: getattr(re, toks[0].upper())
59
+ )
60
+ RegexFlags = ZeroOrMore(RegexFlag).set_parse_action(
61
+ lambda toks: reduce(lambda a, b: a | b, toks, 0)
62
+ )
63
+ Regex = (QuotedString("/") + RegexFlags).set_parse_action(_Regex)
64
+
65
+ Octet = Word(nums, max=3).addCondition(lambda toks: int(toks[0]) <= 255)
66
+ IpAddr = Combine(Octet + "." + Octet + "." + Octet + "." + Octet)
67
+ Cidr = Word(nums, max=2).addCondition(lambda toks: int(toks[0]) <= 32)
68
+
69
+
70
+ class _Subnet(Token):
71
+ def compiler(self, subnet):
72
+ # pylint: disable=no-self-use
73
+ return ipcalc.Network(subnet)
74
+
75
+
76
+ Subnet = Combine(IpAddr + "/" + Cidr).set_parse_action(_Subnet)
77
+
78
+
79
+ class _Symbol(Token):
80
+ def __call__(self, ctx):
81
+ # If symbol is a literal 'a.b' and exists in ctx, return it
82
+ # Imperfect bugfix to allow for fields with literal dots in the root of ctx
83
+ if self.value in ctx:
84
+ return ctx[self.value]
85
+
86
+ parts = self.value.split(".")
87
+ value = ctx
88
+ for part in parts:
89
+ if part in value:
90
+ value = value[part]
91
+ else:
92
+ value = None
93
+ break
94
+ return value
95
+
96
+
97
+ Symbol = Word((alphas + "_"), bodyChars=(alphas + nums + "." + "_")).set_parse_action(_Symbol)
98
+
99
+
100
+ Value = MatchFirst([
101
+ DateTime,
102
+ Date,
103
+ Time,
104
+ quoted_string.set_parse_action(remove_quotes),
105
+ Word(nums).set_parse_action(lambda toks: int(toks[0])),
106
+ ]).set_parse_action(Token)
107
+
108
+
109
+ class _List(Token):
110
+ def __call__(self, ctx):
111
+ return [item(ctx) for item in self.value]
112
+
113
+
114
+ List = Group(Value + OneOrMore(Suppress(Literal(",")) + Value)).set_parse_action(_List)
115
+
116
+
117
+ def in_op(lhs, rhs):
118
+ if not (lhs and rhs):
119
+ return False
120
+
121
+ try:
122
+ # If lhs is a list, we need to call ipcalc's contains() function for each item
123
+ if isinstance(lhs, list) and isinstance(rhs, ipcalc.Network):
124
+ return any([operator.contains(rhs, list_item) for list_item in lhs])
125
+
126
+ return operator.contains(rhs, lhs)
127
+ except ValueError:
128
+ return False
129
+
130
+
131
+ def re_op(lhs, rhs):
132
+ if not (lhs and rhs):
133
+ return False
134
+
135
+ if isinstance(lhs, list):
136
+ return any(rhs.search(item) for item in lhs)
137
+
138
+ return bool(rhs.search(lhs))
139
+
140
+
141
+ # Operators
142
+ ComparisonOp = MatchFirst([
143
+ Literal("==").set_parse_action(lambda toks: operator.eq),
144
+ Literal("!=").set_parse_action(lambda toks: operator.ne),
145
+ Literal("<=").set_parse_action(lambda toks: operator.le),
146
+ Literal("<").set_parse_action(lambda toks: operator.lt),
147
+ Literal(">=").set_parse_action(lambda toks: operator.ge),
148
+ Literal(">").set_parse_action(lambda toks: operator.gt),
149
+ Keyword("in").set_parse_action(lambda toks: in_op),
150
+ Literal("=~").set_parse_action(lambda toks: re_op),
151
+ ])
152
+
153
+
154
+ class _Not(Token):
155
+ def compiler(self, *toks):
156
+ # pylint: disable=no-self-use
157
+ return toks[0][1]
158
+
159
+ def __call__(self, ctx):
160
+ return not self.value(ctx)
161
+
162
+
163
+ class _And(Token):
164
+ def compiler(self, *toks):
165
+ # pylint: disable=no-self-use
166
+ return toks[0][0::2]
167
+
168
+ def __call__(self, ctx):
169
+ return all(item(ctx) for item in self.value)
170
+
171
+
172
+ class _Or(Token):
173
+ def compiler(self, *toks):
174
+ # pylint: disable=no-self-use
175
+ return toks[0][0::2]
176
+
177
+ def __call__(self, ctx):
178
+ return any(item(ctx) for item in self.value)
179
+
180
+
181
+ BooleanOps = [
182
+ (CaselessLiteral("not"), 1, OpAssoc.RIGHT, _Not),
183
+ (CaselessLiteral("and"), 2, OpAssoc.LEFT, _And),
184
+ (CaselessLiteral("or"), 2, OpAssoc.LEFT, _Or),
185
+ ]
186
+
187
+ LHS = Symbol | Value | Regex
188
+ RHS = Symbol | Subnet | List | Value | Regex
189
+
190
+
191
+ class _Statement:
192
+ def __init__(self, lhs, op=None, rhs=None):
193
+ self.lhs = lhs
194
+ self.op = op # pylint: disable=invalid-name
195
+ self.rhs = rhs
196
+
197
+ def __call__(self, ctx):
198
+ if self.op is None:
199
+ return self.lhs(ctx)
200
+
201
+ return self.op(self.lhs(ctx), self.rhs(ctx))
202
+
203
+
204
+ Statement = (LHS + Optional(ComparisonOp + RHS)).set_parse_action(
205
+ lambda toks: _Statement(*toks)
206
+ )
207
+
208
+
209
+ class Expression:
210
+ @classmethod
211
+ def parse_string(cls, *args, **kwargs):
212
+ expr = infix_notation(Statement, BooleanOps).set_parse_action(
213
+ lambda toks: _Statement(*toks)
214
+ )
215
+
216
+ return expr.parse_string(*args, **kwargs)[0]
217
+
218
+ parseString = parse_string
@@ -0,0 +1,193 @@
1
+ Metadata-Version: 2.4
2
+ Name: filtration
3
+ Version: 2.3.2
4
+ Summary: filtration - A library for parsing arbitrary filters
5
+ Author: Steve McMaster
6
+ Author-email: mcmaster@hurricanelabs.com
7
+ Project-URL: Bug Tracker, https://github.com/HurricaneLabs/filtration/issues
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Requires-Dist: pyparsing>=3.0.0
12
+ Requires-Dist: ipcalc
13
+ Dynamic: author
14
+ Dynamic: author-email
15
+ Dynamic: classifier
16
+ Dynamic: description
17
+ Dynamic: project-url
18
+ Dynamic: requires-dist
19
+ Dynamic: summary
20
+
21
+ ##########
22
+ Filtration
23
+ ##########
24
+
25
+ **A library for parsing arbitrary filters provided by a UI or as a Query String**
26
+
27
+ Features
28
+ ========
29
+ - Compatible with Python 3
30
+ - Parses human readable filters
31
+
32
+ Get Filtration
33
+ ==============
34
+
35
+ .. code-block:: shell
36
+
37
+ pip install git+https://github.com/HurricaneLabs/filtration.git
38
+
39
+ Run the tests
40
+ =============
41
+ You must install nose2, then run:
42
+
43
+ .. code-block:: shell
44
+
45
+ git clone https://github.com/HurricaneLabs/filtration.git
46
+ cd filtration
47
+ nose2
48
+
49
+ ########
50
+ Usage
51
+ ########
52
+ Filtration is used to parse "filter expressions" made up of one or more "statements". Each
53
+ statement is comprised of a "left hand side" (LHS), and optionally an operator and a "right hand
54
+ side" (RHS). When no operator and RHS are specified, a special "LHS exists" syntax is assumed. See
55
+ "Expression Evaluation" for more details.
56
+
57
+ Statements are joined together using "AND" or "OR" to form an expression. Parentheses may be used
58
+ when joining statements together to enforce precedence. For example:
59
+
60
+ .. code-block:: python
61
+
62
+ >>> from filtration import Expression
63
+ >>> Expression.parseString("a and b or c")
64
+ ((a and b) or c)
65
+ >>> Expression.parseString("a and (b or c)")
66
+ (a and (b or c))
67
+ >>>
68
+
69
+ Filtration can also be used to parse query string syntax. See below for more information.
70
+
71
+ Expression Format
72
+ =================
73
+
74
+ Operators
75
+ ~~~~~~~~~
76
+ These operators control comparison of the LHS to the RHS. If the operator is omitted (and thus
77
+ the RHS is also omitted), the statement returns True IF the symbol in the LHS exists at all.
78
+
79
+ * Equal ("==")
80
+ * Not equal ("!=")
81
+ * Less than ("<")
82
+ * Less than or equal ("<=")
83
+ * Greater than (">")
84
+ * Greater than or equal (">=")
85
+ * Contains ("in")
86
+ * RHS must be a list or a Subnet
87
+ * Regular expression ("=~")
88
+ * RHS must be a regex token
89
+
90
+ Tokens
91
+ ~~~~~~~~~~~~~~~
92
+ These tokens are used in the LHS or RHS of a statement.
93
+
94
+ Regex
95
+ -----
96
+ A regular expression must be wrapped in "/" and may contain the characters "i", "m" or "s" after
97
+ the closing "/" to represent the corresponding regex flags. Examples::
98
+
99
+ /abc/
100
+ /^abc/i
101
+ /^abc$/ms
102
+
103
+ Subnet
104
+ ------
105
+ A subnet is an IPv4 subnet in CIDR notation::
106
+
107
+ 127.0.0.0/8
108
+ 192.168.0.0/24
109
+
110
+ Symbol
111
+ ------
112
+ A symbol is represented as a bare, unquoted string. It begins with a letter or underscore, and
113
+ can be followed by any number of letters, numbers, dots (".") or underscores. Dots have special
114
+ meaning and are used to indicate dictionary traversal (see Expression Evaluation below).
115
+
116
+ Value
117
+ -----
118
+ A value can be a date, time, date/time, quoted string, or an integer. A date is represented in
119
+ YYYY-MM-DD format (not quoted), and is interpreted to mean midnight on that date. A time is
120
+ represented in HH:MM:SS format (also not quoted), and is interpreted to mean that time on whatever
121
+ day the filter is evaluated. A date/time is represented in YYYY-MM-DDTHH:MM:SS format, where the
122
+ "T" is optional and could instead be represented by a space. This format is roughly ISO 8601, but
123
+ is lacking microseconds.
124
+
125
+ List
126
+ ----
127
+ A list is two-or-more Value tokens separated by commas.
128
+
129
+ Expression Evaluation
130
+ =====================
131
+
132
+ Expression objects are callable, with a single "context" argument. When used in this way, either
133
+ true or false is returned, based on whether the "context" matches the filter. For example, given
134
+ this context:
135
+
136
+ .. code-block:: python
137
+
138
+ >>> c = {"a": 1, "b": 2, "c": 3}
139
+
140
+ and this expression:
141
+
142
+ .. code-block:: python
143
+
144
+ >>> expr = Expression.parseString("a == 1 and b == 2")
145
+
146
+ calling the expression would return True:
147
+
148
+ .. code-block:: python
149
+
150
+ >>> expr(c)
151
+ True
152
+ >>>
153
+
154
+ whereas this expression would return False:
155
+
156
+ .. code-block:: python
157
+
158
+ >>> expr = Expression.parseString("a == 2 and b == 2")
159
+ >>> expr(c)
160
+ False
161
+ >>>
162
+
163
+ When no operator/RHS is provided, the statement resolves to true if the LHS key exists in the
164
+ context. For example:
165
+
166
+ .. code-block:: python
167
+
168
+ >>> c = {"a": 1, "b": 2, "c": 3}
169
+ >>> expr = Expression.parseString("a")
170
+ >>> expr(c)
171
+ True
172
+ >>> expr = Expression.parseString("d")
173
+ >>> expr(c)
174
+ False
175
+ >>>
176
+
177
+ Dictionary Traversal
178
+ ~~~~~~~~~~~~~~~~~~~~
179
+
180
+ Symbols are able to traverse nested dictionaries in the context. Given this context:
181
+
182
+ .. code-block:: python
183
+
184
+ >>> c = {"a": {"b": {"c": 1}}}
185
+
186
+ This expression will return true:
187
+
188
+ .. code-block:: python
189
+
190
+ >>> expr = Expression.parseString("a.b.c == 1")
191
+ >>> expr(c)
192
+ True
193
+ >>>
@@ -0,0 +1,5 @@
1
+ filtration/__init__.py,sha256=ONXwuSgqRDGyLfZF02ZhyHkrvxUAFp8WjY7_mX06ArE,6324
2
+ filtration-2.3.2.dist-info/METADATA,sha256=PHh8Bs3orOJNY9o5UY193TuoqKZcazi8RosQwZXPcOc,5041
3
+ filtration-2.3.2.dist-info/WHEEL,sha256=0CuiUZ_p9E4cD6NyLD6UG80LBXYyiSYZOKDm5lp32xk,91
4
+ filtration-2.3.2.dist-info/top_level.txt,sha256=lA8sgGRm2iRHb-IJERUtZLunh2Mb-8JgHO2M5S4hOqM,11
5
+ filtration-2.3.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.3.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ filtration