filtration 2.3.2__tar.gz → 3.0.0__tar.gz
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-2.3.2 → filtration-3.0.0}/PKG-INFO +37 -28
- {filtration-2.3.2 → filtration-3.0.0}/README.rst +21 -14
- filtration-3.0.0/filtration/__init__.py +322 -0
- {filtration-2.3.2 → filtration-3.0.0}/filtration.egg-info/PKG-INFO +37 -28
- {filtration-2.3.2 → filtration-3.0.0}/filtration.egg-info/SOURCES.txt +1 -1
- filtration-3.0.0/filtration.egg-info/requires.txt +3 -0
- filtration-3.0.0/pyproject.toml +69 -0
- filtration-3.0.0/tests/test_parser.py +205 -0
- filtration-3.0.0/tests/test_tokens.py +352 -0
- filtration-2.3.2/filtration/__init__.py +0 -218
- filtration-2.3.2/filtration.egg-info/requires.txt +0 -2
- filtration-2.3.2/setup.py +0 -31
- filtration-2.3.2/tests/test_parser.py +0 -162
- filtration-2.3.2/tests/test_tokens.py +0 -106
- {filtration-2.3.2 → filtration-3.0.0}/filtration.egg-info/dependency_links.txt +0 -0
- {filtration-2.3.2 → filtration-3.0.0}/filtration.egg-info/top_level.txt +0 -0
- {filtration-2.3.2 → filtration-3.0.0}/setup.cfg +0 -0
|
@@ -1,22 +1,24 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: filtration
|
|
3
|
-
Version:
|
|
3
|
+
Version: 3.0.0
|
|
4
4
|
Summary: filtration - A library for parsing arbitrary filters
|
|
5
|
-
Author: Steve McMaster
|
|
6
|
-
|
|
5
|
+
Author-email: Steve McMaster <mcmaster@hurricanelabs.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
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
8
|
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Description-Content-Type: text/x-rst
|
|
19
|
+
Requires-Dist: pyparsing>=3.0.1
|
|
20
|
+
Requires-Dist: ipcalc>=1.99.0
|
|
21
|
+
Requires-Dist: six>=1.16.0
|
|
20
22
|
|
|
21
23
|
##########
|
|
22
24
|
Filtration
|
|
@@ -34,25 +36,25 @@ Get Filtration
|
|
|
34
36
|
|
|
35
37
|
.. code-block:: shell
|
|
36
38
|
|
|
37
|
-
pip install
|
|
39
|
+
pip install filtration
|
|
38
40
|
|
|
39
41
|
Run the tests
|
|
40
42
|
=============
|
|
41
|
-
|
|
43
|
+
With `uv <https://docs.astral.sh/uv/>`_ installed, run:
|
|
42
44
|
|
|
43
45
|
.. code-block:: shell
|
|
44
46
|
|
|
45
47
|
git clone https://github.com/HurricaneLabs/filtration.git
|
|
46
48
|
cd filtration
|
|
47
|
-
|
|
49
|
+
uv run pytest
|
|
48
50
|
|
|
49
51
|
########
|
|
50
52
|
Usage
|
|
51
53
|
########
|
|
52
54
|
Filtration is used to parse "filter expressions" made up of one or more "statements". Each
|
|
53
55
|
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,
|
|
55
|
-
"Expression Evaluation" for more details.
|
|
56
|
+
side" (RHS). When no operator and RHS are specified, the statement checks whether the LHS is
|
|
57
|
+
truthy. See "Expression Evaluation" for more details.
|
|
56
58
|
|
|
57
59
|
Statements are joined together using "AND" or "OR" to form an expression. Parentheses may be used
|
|
58
60
|
when joining statements together to enforce precedence. For example:
|
|
@@ -60,13 +62,16 @@ when joining statements together to enforce precedence. For example:
|
|
|
60
62
|
.. code-block:: python
|
|
61
63
|
|
|
62
64
|
>>> from filtration import Expression
|
|
63
|
-
>>>
|
|
64
|
-
((a and b) or c
|
|
65
|
-
|
|
66
|
-
(a and (b or c))
|
|
65
|
+
>>> c = {"a": False, "b": False, "c": True}
|
|
66
|
+
>>> Expression.parseString("a and b or c")(c) # (a and b) or c
|
|
67
|
+
True
|
|
68
|
+
>>> Expression.parseString("a and (b or c)")(c)
|
|
69
|
+
False
|
|
67
70
|
>>>
|
|
68
71
|
|
|
69
|
-
|
|
72
|
+
The whole filter must parse. Leftover text, such as the ``b`` in ``a == 1 b``, raises a
|
|
73
|
+
``pyparsing.ParseException`` instead of being ignored. Pass ``parse_all=False`` to get the
|
|
74
|
+
older behavior, which parses as much of the start of the filter as it can and ignores the rest.
|
|
70
75
|
|
|
71
76
|
Expression Format
|
|
72
77
|
=================
|
|
@@ -74,7 +79,7 @@ Expression Format
|
|
|
74
79
|
Operators
|
|
75
80
|
~~~~~~~~~
|
|
76
81
|
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
|
|
82
|
+
the RHS is also omitted), the statement returns True if the LHS has a truthy value.
|
|
78
83
|
|
|
79
84
|
* Equal ("==")
|
|
80
85
|
* Not equal ("!=")
|
|
@@ -160,15 +165,19 @@ whereas this expression would return False:
|
|
|
160
165
|
False
|
|
161
166
|
>>>
|
|
162
167
|
|
|
163
|
-
When no operator/RHS is provided, the statement
|
|
164
|
-
|
|
168
|
+
When no operator/RHS is provided, the statement is True if the LHS key is in the context and
|
|
169
|
+
its value is truthy. A missing key, ``0``, ``""``, ``False``, ``None`` or an empty list gives
|
|
170
|
+
False. For example:
|
|
165
171
|
|
|
166
172
|
.. code-block:: python
|
|
167
173
|
|
|
168
|
-
>>> c = {"a": 1, "b":
|
|
174
|
+
>>> c = {"a": 1, "b": 0, "c": 3}
|
|
169
175
|
>>> expr = Expression.parseString("a")
|
|
170
176
|
>>> expr(c)
|
|
171
177
|
True
|
|
178
|
+
>>> expr = Expression.parseString("b")
|
|
179
|
+
>>> expr(c)
|
|
180
|
+
False
|
|
172
181
|
>>> expr = Expression.parseString("d")
|
|
173
182
|
>>> expr(c)
|
|
174
183
|
False
|
|
@@ -14,25 +14,25 @@ Get Filtration
|
|
|
14
14
|
|
|
15
15
|
.. code-block:: shell
|
|
16
16
|
|
|
17
|
-
pip install
|
|
17
|
+
pip install filtration
|
|
18
18
|
|
|
19
19
|
Run the tests
|
|
20
20
|
=============
|
|
21
|
-
|
|
21
|
+
With `uv <https://docs.astral.sh/uv/>`_ installed, run:
|
|
22
22
|
|
|
23
23
|
.. code-block:: shell
|
|
24
24
|
|
|
25
25
|
git clone https://github.com/HurricaneLabs/filtration.git
|
|
26
26
|
cd filtration
|
|
27
|
-
|
|
27
|
+
uv run pytest
|
|
28
28
|
|
|
29
29
|
########
|
|
30
30
|
Usage
|
|
31
31
|
########
|
|
32
32
|
Filtration is used to parse "filter expressions" made up of one or more "statements". Each
|
|
33
33
|
statement is comprised of a "left hand side" (LHS), and optionally an operator and a "right hand
|
|
34
|
-
side" (RHS). When no operator and RHS are specified,
|
|
35
|
-
"Expression Evaluation" for more details.
|
|
34
|
+
side" (RHS). When no operator and RHS are specified, the statement checks whether the LHS is
|
|
35
|
+
truthy. See "Expression Evaluation" for more details.
|
|
36
36
|
|
|
37
37
|
Statements are joined together using "AND" or "OR" to form an expression. Parentheses may be used
|
|
38
38
|
when joining statements together to enforce precedence. For example:
|
|
@@ -40,13 +40,16 @@ when joining statements together to enforce precedence. For example:
|
|
|
40
40
|
.. code-block:: python
|
|
41
41
|
|
|
42
42
|
>>> from filtration import Expression
|
|
43
|
-
>>>
|
|
44
|
-
((a and b) or c
|
|
45
|
-
|
|
46
|
-
(a and (b or c))
|
|
43
|
+
>>> c = {"a": False, "b": False, "c": True}
|
|
44
|
+
>>> Expression.parseString("a and b or c")(c) # (a and b) or c
|
|
45
|
+
True
|
|
46
|
+
>>> Expression.parseString("a and (b or c)")(c)
|
|
47
|
+
False
|
|
47
48
|
>>>
|
|
48
49
|
|
|
49
|
-
|
|
50
|
+
The whole filter must parse. Leftover text, such as the ``b`` in ``a == 1 b``, raises a
|
|
51
|
+
``pyparsing.ParseException`` instead of being ignored. Pass ``parse_all=False`` to get the
|
|
52
|
+
older behavior, which parses as much of the start of the filter as it can and ignores the rest.
|
|
50
53
|
|
|
51
54
|
Expression Format
|
|
52
55
|
=================
|
|
@@ -54,7 +57,7 @@ Expression Format
|
|
|
54
57
|
Operators
|
|
55
58
|
~~~~~~~~~
|
|
56
59
|
These operators control comparison of the LHS to the RHS. If the operator is omitted (and thus
|
|
57
|
-
the RHS is also omitted), the statement returns True
|
|
60
|
+
the RHS is also omitted), the statement returns True if the LHS has a truthy value.
|
|
58
61
|
|
|
59
62
|
* Equal ("==")
|
|
60
63
|
* Not equal ("!=")
|
|
@@ -140,15 +143,19 @@ whereas this expression would return False:
|
|
|
140
143
|
False
|
|
141
144
|
>>>
|
|
142
145
|
|
|
143
|
-
When no operator/RHS is provided, the statement
|
|
144
|
-
|
|
146
|
+
When no operator/RHS is provided, the statement is True if the LHS key is in the context and
|
|
147
|
+
its value is truthy. A missing key, ``0``, ``""``, ``False``, ``None`` or an empty list gives
|
|
148
|
+
False. For example:
|
|
145
149
|
|
|
146
150
|
.. code-block:: python
|
|
147
151
|
|
|
148
|
-
>>> c = {"a": 1, "b":
|
|
152
|
+
>>> c = {"a": 1, "b": 0, "c": 3}
|
|
149
153
|
>>> expr = Expression.parseString("a")
|
|
150
154
|
>>> expr(c)
|
|
151
155
|
True
|
|
156
|
+
>>> expr = Expression.parseString("b")
|
|
157
|
+
>>> expr(c)
|
|
158
|
+
False
|
|
152
159
|
>>> expr = Expression.parseString("d")
|
|
153
160
|
>>> expr(c)
|
|
154
161
|
False
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
import ipaddress
|
|
3
|
+
import operator
|
|
4
|
+
import re
|
|
5
|
+
from functools import reduce
|
|
6
|
+
from typing import Union
|
|
7
|
+
|
|
8
|
+
import ipcalc
|
|
9
|
+
from pyparsing import (
|
|
10
|
+
CaselessKeyword,
|
|
11
|
+
Combine,
|
|
12
|
+
Group,
|
|
13
|
+
Keyword,
|
|
14
|
+
Literal,
|
|
15
|
+
MatchFirst,
|
|
16
|
+
OneOrMore,
|
|
17
|
+
OpAssoc,
|
|
18
|
+
Optional,
|
|
19
|
+
ParseException,
|
|
20
|
+
ParseFatalException,
|
|
21
|
+
QuotedString,
|
|
22
|
+
Suppress,
|
|
23
|
+
Word,
|
|
24
|
+
ZeroOrMore,
|
|
25
|
+
alphas,
|
|
26
|
+
infix_notation,
|
|
27
|
+
nums,
|
|
28
|
+
quoted_string,
|
|
29
|
+
remove_quotes,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Token:
|
|
34
|
+
def __init__(self, toks):
|
|
35
|
+
compiler = getattr(self, "compiler", None)
|
|
36
|
+
if callable(compiler):
|
|
37
|
+
self.value = compiler(*toks)
|
|
38
|
+
else:
|
|
39
|
+
try:
|
|
40
|
+
self.value = toks[0]
|
|
41
|
+
except TypeError: # pragma: no cover
|
|
42
|
+
self.value = toks
|
|
43
|
+
|
|
44
|
+
def __call__(self, ctx):
|
|
45
|
+
if isinstance(self.value, datetime.time):
|
|
46
|
+
# a bare time means that time on the day the filter runs
|
|
47
|
+
return datetime.datetime.combine(datetime.date.today(), self.value)
|
|
48
|
+
return self.value
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
Year = Word(nums, max=4).set_parse_action(lambda toks: int(toks[0]))
|
|
52
|
+
Month = Word(nums, max=2).set_parse_action(lambda toks: int(toks[0]))
|
|
53
|
+
Day = Word(nums, max=2).set_parse_action(lambda toks: int(toks[0]))
|
|
54
|
+
|
|
55
|
+
Hour = Word(nums, max=2).set_parse_action(lambda toks: int(toks[0]))
|
|
56
|
+
Minute = Word(nums, max=2).set_parse_action(lambda toks: int(toks[0]))
|
|
57
|
+
Second = Word(nums, max=2).set_parse_action(lambda toks: int(toks[0]))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _fatal_on_value_error(build):
|
|
61
|
+
# datetime and ipaddress raise ValueError for things like month 13 or a 010 octet;
|
|
62
|
+
# make that a parse error. Fatal, so the Value alternatives can't fall back to
|
|
63
|
+
# reading 2015-13-01 as 2015 or 010.0.0.0/8 as 10
|
|
64
|
+
def action(s, loc, toks):
|
|
65
|
+
try:
|
|
66
|
+
return build(toks)
|
|
67
|
+
except ValueError as exc:
|
|
68
|
+
raise ParseFatalException(s, loc, str(exc)) from exc
|
|
69
|
+
|
|
70
|
+
return action
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
Date = (Year + Suppress("-") + Month + Suppress("-") + Day).set_parse_action(
|
|
74
|
+
_fatal_on_value_error(
|
|
75
|
+
lambda toks: datetime.datetime.combine(datetime.date(*toks), datetime.time.min)
|
|
76
|
+
)
|
|
77
|
+
)
|
|
78
|
+
# a plain time, not a datetime: the day is filled in when the filter runs (Token.__call__)
|
|
79
|
+
Time = (Hour + Suppress(":") + Minute + Suppress(":") + Second).set_parse_action(
|
|
80
|
+
_fatal_on_value_error(lambda toks: datetime.time(*toks))
|
|
81
|
+
)
|
|
82
|
+
DateTime = (Date + Suppress(Optional("T")) + Time).set_parse_action(
|
|
83
|
+
lambda toks: datetime.datetime.combine(toks[0].date(), toks[1])
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class _Regex(Token):
|
|
88
|
+
def compiler(self, pattern, flags):
|
|
89
|
+
try:
|
|
90
|
+
return re.compile(pattern, flags)
|
|
91
|
+
except re.error as exc:
|
|
92
|
+
raise ParseException(str(exc)) from exc
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
RegexFlag = Word("ims", exact=1).set_parse_action(lambda toks: getattr(re, toks[0].upper()))
|
|
96
|
+
# flags must touch the closing slash, so `/x/ in b` reads in as the operator
|
|
97
|
+
RegexFlags = (
|
|
98
|
+
ZeroOrMore(RegexFlag)
|
|
99
|
+
.leave_whitespace()
|
|
100
|
+
.set_parse_action(lambda toks: reduce(lambda a, b: a | b, toks, 0))
|
|
101
|
+
)
|
|
102
|
+
Regex = (QuotedString("/") + RegexFlags).set_parse_action(_Regex)
|
|
103
|
+
|
|
104
|
+
Octet = Word(nums, max=3).add_condition(lambda toks: int(toks[0]) <= 255)
|
|
105
|
+
IpAddr = Combine(Octet + "." + Octet + "." + Octet + "." + Octet)
|
|
106
|
+
Cidr = Word(nums, max=2).add_condition(lambda toks: int(toks[0]) <= 32)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class _Subnet(Token):
|
|
110
|
+
def compiler(self, subnet):
|
|
111
|
+
# strict=False so 10.0.0.1/8 means 10.0.0.0/8 rather than an error
|
|
112
|
+
network = ipaddress.ip_network(subnet, strict=False)
|
|
113
|
+
# stored as ipcalc, the type filtration 2.x pickled into runbook bundles, so a bundle
|
|
114
|
+
# built with this version still loads and matches in readers on 2.x; in_op checks
|
|
115
|
+
# with ipaddress either way
|
|
116
|
+
return ipcalc.Network(str(network))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# Octet lets 010 through, but ipaddress rejects leading zeros
|
|
120
|
+
Subnet = Combine(IpAddr + "/" + Cidr).set_parse_action(_fatal_on_value_error(_Subnet))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class _Symbol(Token):
|
|
124
|
+
def __call__(self, ctx):
|
|
125
|
+
# If symbol is a literal 'a.b' and exists in ctx, return it
|
|
126
|
+
# Imperfect bugfix to allow for fields with literal dots in the root of ctx
|
|
127
|
+
if self.value in ctx:
|
|
128
|
+
return ctx[self.value]
|
|
129
|
+
|
|
130
|
+
parts = self.value.split(".")
|
|
131
|
+
value = ctx
|
|
132
|
+
try:
|
|
133
|
+
for part in parts:
|
|
134
|
+
if part in value:
|
|
135
|
+
value = value[part]
|
|
136
|
+
else:
|
|
137
|
+
return None
|
|
138
|
+
except TypeError:
|
|
139
|
+
# a value partway down isn't a dict (a string, number, list or None)
|
|
140
|
+
return None
|
|
141
|
+
return value
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
Symbol = Word((alphas + "_"), body_chars=(alphas + nums + "." + "_")).set_parse_action(_Symbol)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
Value = MatchFirst(
|
|
148
|
+
[
|
|
149
|
+
DateTime,
|
|
150
|
+
Date,
|
|
151
|
+
Time,
|
|
152
|
+
quoted_string.copy().set_parse_action(remove_quotes),
|
|
153
|
+
Word(nums).set_parse_action(lambda toks: int(toks[0])),
|
|
154
|
+
]
|
|
155
|
+
).set_parse_action(Token)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class _List(Token):
|
|
159
|
+
def __call__(self, ctx):
|
|
160
|
+
return [item(ctx) for item in self.value]
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
List = Group(Value + OneOrMore(Suppress(Literal(",")) + Value)).set_parse_action(_List)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _in_subnet(item: object, subnet: Union[ipaddress.IPv4Network, ipaddress.IPv6Network]) -> bool:
|
|
167
|
+
"""Return True if item is an IP or subnet that falls inside subnet."""
|
|
168
|
+
if isinstance(item, tuple):
|
|
169
|
+
# ip_network reads a tuple as (address, prefix) and raises all sorts on bad ones
|
|
170
|
+
return False
|
|
171
|
+
try:
|
|
172
|
+
# an IP becomes a single-address network, so IPs and subnets share one check
|
|
173
|
+
return ipaddress.ip_network(item, strict=False).subnet_of(subnet)
|
|
174
|
+
except (TypeError, ValueError):
|
|
175
|
+
# not an IP, or IPv6 against an IPv4 subnet
|
|
176
|
+
return False
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _from_ipcalc(
|
|
180
|
+
network: ipcalc.Network,
|
|
181
|
+
) -> Union[ipaddress.IPv4Network, ipaddress.IPv6Network]:
|
|
182
|
+
"""Return network as an ipaddress network, normalized to its network address."""
|
|
183
|
+
# built from the stored numbers, not the text: a 2.x bundle can hold text like
|
|
184
|
+
# 010.0.0.0/8 that ipcalc accepted and ipaddress won't parse
|
|
185
|
+
cls = ipaddress.IPv4Network if network.v == 4 else ipaddress.IPv6Network
|
|
186
|
+
return cls((network.ip, network.mask), strict=False)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _network_eq(network: ipcalc.Network, other: object) -> bool:
|
|
190
|
+
"""Return True if other is the same network as network, an ipcalc.Network."""
|
|
191
|
+
if other is None or isinstance(other, tuple):
|
|
192
|
+
return False
|
|
193
|
+
try:
|
|
194
|
+
return ipaddress.ip_network(other, strict=False) == _from_ipcalc(network)
|
|
195
|
+
except (TypeError, ValueError):
|
|
196
|
+
return False
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def in_op(lhs, rhs):
|
|
200
|
+
# only a missing field skips the check; 0 and '' are real values
|
|
201
|
+
if lhs is None or rhs is None:
|
|
202
|
+
return False
|
|
203
|
+
|
|
204
|
+
if isinstance(rhs, ipcalc.Network):
|
|
205
|
+
# a Subnet literal, or one unpickled from a bundle built by filtration 2.x
|
|
206
|
+
rhs = _from_ipcalc(rhs)
|
|
207
|
+
|
|
208
|
+
if isinstance(rhs, (ipaddress.IPv4Network, ipaddress.IPv6Network)):
|
|
209
|
+
# a list matches a subnet when any item is inside it; one bad item can't sink the rest
|
|
210
|
+
items = lhs if isinstance(lhs, list) else [lhs]
|
|
211
|
+
return any(_in_subnet(item, rhs) for item in items)
|
|
212
|
+
|
|
213
|
+
return operator.contains(rhs, lhs)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def re_op(lhs, rhs):
|
|
217
|
+
if lhs is None or rhs is None:
|
|
218
|
+
return False
|
|
219
|
+
|
|
220
|
+
if isinstance(lhs, list):
|
|
221
|
+
return any(rhs.search(item) for item in lhs)
|
|
222
|
+
|
|
223
|
+
return bool(rhs.search(lhs))
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# Operators
|
|
227
|
+
ComparisonOp = MatchFirst(
|
|
228
|
+
[
|
|
229
|
+
Literal("==").set_parse_action(lambda toks: operator.eq),
|
|
230
|
+
Literal("!=").set_parse_action(lambda toks: operator.ne),
|
|
231
|
+
Literal("<=").set_parse_action(lambda toks: operator.le),
|
|
232
|
+
Literal("<").set_parse_action(lambda toks: operator.lt),
|
|
233
|
+
Literal(">=").set_parse_action(lambda toks: operator.ge),
|
|
234
|
+
Literal(">").set_parse_action(lambda toks: operator.gt),
|
|
235
|
+
Keyword("in").set_parse_action(lambda toks: in_op),
|
|
236
|
+
Literal("=~").set_parse_action(lambda toks: re_op),
|
|
237
|
+
]
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class _Not(Token):
|
|
242
|
+
def compiler(self, *toks):
|
|
243
|
+
return toks[0][1]
|
|
244
|
+
|
|
245
|
+
def __call__(self, ctx):
|
|
246
|
+
return not self.value(ctx)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
class _And(Token):
|
|
250
|
+
def compiler(self, *toks):
|
|
251
|
+
return toks[0][0::2]
|
|
252
|
+
|
|
253
|
+
def __call__(self, ctx):
|
|
254
|
+
return all(item(ctx) for item in self.value)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class _Or(Token):
|
|
258
|
+
def compiler(self, *toks):
|
|
259
|
+
return toks[0][0::2]
|
|
260
|
+
|
|
261
|
+
def __call__(self, ctx):
|
|
262
|
+
return any(item(ctx) for item in self.value)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
BooleanOps = [
|
|
266
|
+
(CaselessKeyword("not"), 1, OpAssoc.RIGHT, _Not),
|
|
267
|
+
(CaselessKeyword("and"), 2, OpAssoc.LEFT, _And),
|
|
268
|
+
(CaselessKeyword("or"), 2, OpAssoc.LEFT, _Or),
|
|
269
|
+
]
|
|
270
|
+
|
|
271
|
+
LHS = Symbol | Value | Regex
|
|
272
|
+
RHS = Symbol | Subnet | List | Value | Regex
|
|
273
|
+
|
|
274
|
+
ORDERING_OPS = (operator.lt, operator.le, operator.gt, operator.ge)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
class _Statement:
|
|
278
|
+
def __init__(self, lhs, op=None, rhs=None):
|
|
279
|
+
self.lhs = lhs
|
|
280
|
+
self.op = op
|
|
281
|
+
self.rhs = rhs
|
|
282
|
+
|
|
283
|
+
def __call__(self, ctx):
|
|
284
|
+
if self.op is None:
|
|
285
|
+
# a bare field is a truthiness check, so 0, '' and [] are False like a missing one
|
|
286
|
+
return bool(self.lhs(ctx))
|
|
287
|
+
|
|
288
|
+
lhs, rhs = self.lhs(ctx), self.rhs(ctx)
|
|
289
|
+
# a missing field can't be ordered; checked here, not in a wrapper function,
|
|
290
|
+
# so op stays a stdlib operator that older filtration can still unpickle
|
|
291
|
+
if self.op in ORDERING_OPS and (lhs is None or rhs is None):
|
|
292
|
+
return False
|
|
293
|
+
# ipcalc's own == parses the other side and raises on a missing or non-IP field
|
|
294
|
+
if self.op in (operator.eq, operator.ne) and isinstance(rhs, ipcalc.Network):
|
|
295
|
+
equal = _network_eq(rhs, lhs)
|
|
296
|
+
return equal if self.op is operator.eq else not equal
|
|
297
|
+
|
|
298
|
+
return self.op(lhs, rhs)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
Statement = (LHS + Optional(ComparisonOp + RHS)).set_parse_action(lambda toks: _Statement(*toks))
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
class Expression:
|
|
305
|
+
@classmethod
|
|
306
|
+
def parse_string(cls, instring, parse_all=True, **kwargs):
|
|
307
|
+
# whole-input match by default, so a typo can't silently drop the rest of a filter;
|
|
308
|
+
# parseAll is the old spelling and has to be mapped here or it can't turn this off
|
|
309
|
+
if "parseAll" in kwargs:
|
|
310
|
+
parse_all = kwargs.pop("parseAll")
|
|
311
|
+
|
|
312
|
+
expr = infix_notation(Statement, BooleanOps).set_parse_action(
|
|
313
|
+
lambda toks: _Statement(*toks)
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
try:
|
|
317
|
+
return expr.parse_string(instring, parse_all=parse_all, **kwargs)[0]
|
|
318
|
+
except ParseFatalException as exc:
|
|
319
|
+
# callers catch ParseException, which the fatal one isn't a subclass of
|
|
320
|
+
raise ParseException(exc.pstr, exc.loc, exc.msg) from exc
|
|
321
|
+
|
|
322
|
+
parseString = parse_string
|
|
@@ -1,22 +1,24 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: filtration
|
|
3
|
-
Version:
|
|
3
|
+
Version: 3.0.0
|
|
4
4
|
Summary: filtration - A library for parsing arbitrary filters
|
|
5
|
-
Author: Steve McMaster
|
|
6
|
-
|
|
5
|
+
Author-email: Steve McMaster <mcmaster@hurricanelabs.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
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
8
|
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Description-Content-Type: text/x-rst
|
|
19
|
+
Requires-Dist: pyparsing>=3.0.1
|
|
20
|
+
Requires-Dist: ipcalc>=1.99.0
|
|
21
|
+
Requires-Dist: six>=1.16.0
|
|
20
22
|
|
|
21
23
|
##########
|
|
22
24
|
Filtration
|
|
@@ -34,25 +36,25 @@ Get Filtration
|
|
|
34
36
|
|
|
35
37
|
.. code-block:: shell
|
|
36
38
|
|
|
37
|
-
pip install
|
|
39
|
+
pip install filtration
|
|
38
40
|
|
|
39
41
|
Run the tests
|
|
40
42
|
=============
|
|
41
|
-
|
|
43
|
+
With `uv <https://docs.astral.sh/uv/>`_ installed, run:
|
|
42
44
|
|
|
43
45
|
.. code-block:: shell
|
|
44
46
|
|
|
45
47
|
git clone https://github.com/HurricaneLabs/filtration.git
|
|
46
48
|
cd filtration
|
|
47
|
-
|
|
49
|
+
uv run pytest
|
|
48
50
|
|
|
49
51
|
########
|
|
50
52
|
Usage
|
|
51
53
|
########
|
|
52
54
|
Filtration is used to parse "filter expressions" made up of one or more "statements". Each
|
|
53
55
|
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,
|
|
55
|
-
"Expression Evaluation" for more details.
|
|
56
|
+
side" (RHS). When no operator and RHS are specified, the statement checks whether the LHS is
|
|
57
|
+
truthy. See "Expression Evaluation" for more details.
|
|
56
58
|
|
|
57
59
|
Statements are joined together using "AND" or "OR" to form an expression. Parentheses may be used
|
|
58
60
|
when joining statements together to enforce precedence. For example:
|
|
@@ -60,13 +62,16 @@ when joining statements together to enforce precedence. For example:
|
|
|
60
62
|
.. code-block:: python
|
|
61
63
|
|
|
62
64
|
>>> from filtration import Expression
|
|
63
|
-
>>>
|
|
64
|
-
((a and b) or c
|
|
65
|
-
|
|
66
|
-
(a and (b or c))
|
|
65
|
+
>>> c = {"a": False, "b": False, "c": True}
|
|
66
|
+
>>> Expression.parseString("a and b or c")(c) # (a and b) or c
|
|
67
|
+
True
|
|
68
|
+
>>> Expression.parseString("a and (b or c)")(c)
|
|
69
|
+
False
|
|
67
70
|
>>>
|
|
68
71
|
|
|
69
|
-
|
|
72
|
+
The whole filter must parse. Leftover text, such as the ``b`` in ``a == 1 b``, raises a
|
|
73
|
+
``pyparsing.ParseException`` instead of being ignored. Pass ``parse_all=False`` to get the
|
|
74
|
+
older behavior, which parses as much of the start of the filter as it can and ignores the rest.
|
|
70
75
|
|
|
71
76
|
Expression Format
|
|
72
77
|
=================
|
|
@@ -74,7 +79,7 @@ Expression Format
|
|
|
74
79
|
Operators
|
|
75
80
|
~~~~~~~~~
|
|
76
81
|
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
|
|
82
|
+
the RHS is also omitted), the statement returns True if the LHS has a truthy value.
|
|
78
83
|
|
|
79
84
|
* Equal ("==")
|
|
80
85
|
* Not equal ("!=")
|
|
@@ -160,15 +165,19 @@ whereas this expression would return False:
|
|
|
160
165
|
False
|
|
161
166
|
>>>
|
|
162
167
|
|
|
163
|
-
When no operator/RHS is provided, the statement
|
|
164
|
-
|
|
168
|
+
When no operator/RHS is provided, the statement is True if the LHS key is in the context and
|
|
169
|
+
its value is truthy. A missing key, ``0``, ``""``, ``False``, ``None`` or an empty list gives
|
|
170
|
+
False. For example:
|
|
165
171
|
|
|
166
172
|
.. code-block:: python
|
|
167
173
|
|
|
168
|
-
>>> c = {"a": 1, "b":
|
|
174
|
+
>>> c = {"a": 1, "b": 0, "c": 3}
|
|
169
175
|
>>> expr = Expression.parseString("a")
|
|
170
176
|
>>> expr(c)
|
|
171
177
|
True
|
|
178
|
+
>>> expr = Expression.parseString("b")
|
|
179
|
+
>>> expr(c)
|
|
180
|
+
False
|
|
172
181
|
>>> expr = Expression.parseString("d")
|
|
173
182
|
>>> expr(c)
|
|
174
183
|
False
|