pyrtan / sourcev0.19.0 · main

pyrtan / src / pyrtan / conditions.py

4,740 bytes · last changed 2026-10-25 in Initial public release

1"""Conditions for ``decide`` branches.
2
3A condition is a small table with one or more tests; all tests must hold.
4Every test is a plain comparison a reader can check by eye, which is the
5point: the branch taken is always explainable from the observed value and
6the condition text.
7
8 { eq = 200 }
9 { gte = 500 }
10 { matches = "^https://" }
11 { contains = "error" }
12 { in = ["open", "pending"] }
13 { exists = true }
14 { empty = false }
15 { between = [200, 299] }
16 { type = "list" }
17"""
18
19from __future__ import annotations
20
21import re
22from typing import Any
23
24from .template import MISSING
25
26KNOWN = {"eq", "ne", "lt", "lte", "gt", "gte", "matches", "contains", "in", "exists", "empty", "between", "type", "startswith", "endswith"}
27
28TYPE_NAMES = {
29 "str": str,
30 "string": str,
31 "int": int,
32 "float": float,
33 "number": (int, float),
34 "bool": bool,
35 "list": list,
36 "dict": dict,
37 "map": dict,
38 "null": type(None),
39 "none": type(None),
40}
41
42
43class ConditionError(ValueError):
44 pass
45
46
47def validate(cond: Any) -> None:
48 if not isinstance(cond, dict) or not cond:
49 raise ConditionError("a condition is a non-empty table")
50 unknown = set(cond) - KNOWN
51 if unknown:
52 raise ConditionError(f"unknown condition keys: {sorted(unknown)}")
53 if "matches" in cond:
54 try:
55 re.compile(cond["matches"])
56 except re.error as e:
57 raise ConditionError(f"bad regex in matches: {e}") from e
58 if "between" in cond and (not isinstance(cond["between"], list) or len(cond["between"]) != 2):
59 raise ConditionError("between takes a two-item list")
60 if "type" in cond and cond["type"] not in TYPE_NAMES:
61 raise ConditionError(f"unknown type {cond['type']!r}; one of {sorted(TYPE_NAMES)}")
62 if "in" in cond and not isinstance(cond["in"], list):
63 raise ConditionError("in takes a list")
64
65
66def holds(cond: dict[str, Any], value: Any) -> bool:
67 """True when every test in ``cond`` holds for ``value``."""
68 for key, expected in cond.items():
69 if not _test(key, expected, value):
70 return False
71 return True
72
73
74def _is_empty(value: Any) -> bool:
75 if value is MISSING or value is None:
76 return True
77 if isinstance(value, (str, list, dict, tuple)):
78 return len(value) == 0
79 return False
80
81
82def _num(value: Any) -> float | None:
83 if isinstance(value, bool):
84 return None
85 if isinstance(value, (int, float)):
86 return float(value)
87 if isinstance(value, str):
88 try:
89 return float(value.strip())
90 except ValueError:
91 return None
92 return None
93
94
95def _test(key: str, expected: Any, value: Any) -> bool:
96 if key == "exists":
97 return (value is not MISSING and value is not None) == bool(expected)
98 if key == "empty":
99 return _is_empty(value) == bool(expected)
100 if value is MISSING:
101 return False
102 if key == "eq":
103 return _loose_eq(value, expected)
104 if key == "ne":
105 return not _loose_eq(value, expected)
106 if key in ("lt", "lte", "gt", "gte"):
107 a, b = _num(value), _num(expected)
108 if a is None or b is None:
109 return False
110 return {"lt": a < b, "lte": a <= b, "gt": a > b, "gte": a >= b}[key]
111 if key == "between":
112 a, lo, hi = _num(value), _num(expected[0]), _num(expected[1])
113 if a is None or lo is None or hi is None:
114 return False
115 return lo <= a <= hi
116 if key == "matches":
117 return value is not None and re.search(expected, str(value)) is not None
118 if key == "contains":
119 if isinstance(value, (list, tuple)):
120 return any(_loose_eq(item, expected) for item in value)
121 if isinstance(value, dict):
122 return expected in value
123 return str(expected) in str(value)
124 if key == "startswith":
125 return str(value).startswith(str(expected))
126 if key == "endswith":
127 return str(value).endswith(str(expected))
128 if key == "in":
129 return any(_loose_eq(value, option) for option in expected)
130 if key == "type":
131 return isinstance(value, TYPE_NAMES[expected]) and not (expected in ("int", "number", "float") and isinstance(value, bool))
132 raise ConditionError(f"unknown condition key {key!r}")
133
134
135def _loose_eq(a: Any, b: Any) -> bool:
136 """Equality that lets ``"200"`` match ``200`` but keeps bools strict."""
137 if isinstance(a, bool) or isinstance(b, bool):
138 return a is b or (isinstance(a, bool) and isinstance(b, bool) and a == b)
139 if a == b:
140 return True
141 na, nb = _num(a), _num(b)
142 if na is not None and nb is not None and (isinstance(a, str) or isinstance(b, str)):
143 return na == nb
144 return False