jw-python/src/python/jw/util/stree/StringTree.py
Jan Lindemann f171443d49
mypy: Fix any_generics, redundant_casts, unused_ignores
Add mypy directives disallow_any_generics, warn_redundant_casts, and
warn_unused_ignores. Fix all resulting type annotation errors:

- load_yaml.py: Add type arguments to dict, tuple, set annotations; fix
  resolving dict/set types for link keys; handle str|int path types.
- misc.py: Add Mapping[str, Any] and Iterable[Any] type arguments; fix
  multiline export comment to avoid bad pattern flag.
- multi_key_dict.py: Add type argument to dict[tuple, Any].
- StringTree.py: Move Any import out of TYPE_CHECKING; fix MutableMapping
  type args.
- serdes.py: Add type argument to re.Match.
- Config.py: Change Config from Mapping to Mapping[str, str]; remove
  unused cast.
- ev/base/Object.py, SimpleObject.py, EventLogger.py, PollerOneShot.py:
  Add Mapping[str, Any] type args.
- ev/app/EventRouter.py: Add dict[str, Any] type args in inner functions.
- auth/*: Remove now-unnecessary # type: ignore[return-value] comments.

Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v0.82.0
Signed-off-by: Jan Lindemann <jan@janware.com>
2026-08-12 23:10:13 +00:00

448 lines
15 KiB
Python

from __future__ import annotations
import fnmatch
import re
from collections import OrderedDict
from collections.abc import MutableMapping
from enum import Enum, auto
from typing import TYPE_CHECKING, Any, override
from typing import overload
from typing import cast
if TYPE_CHECKING:
from collections.abc import Callable
from typing import Iterator
from ..log import DEBUG, INFO, get_caller_pos, slog
def is_quoted(s: str) -> bool:
s = s.strip()
if len(s) < 2:
return False
d = s[0]
if d == s[-1] and d in ['"', "'"]:
return True
return False
def quote(s: str) -> str:
if is_quoted(s):
return s
s = s.strip()
if len(s) > 0:
if s[0] == '"':
return "'" + s + "'"
return '"' + s + '"'
@overload
def cleanup_string(s: str) -> str:
...
@overload
def cleanup_string(s: StringTree) -> StringTree:
...
def cleanup_string(s: str | StringTree) -> str | StringTree:
if isinstance(s, StringTree):
return s
assert isinstance(s, str), f'Expected str or StringTree, got {type(s).__name__}'
s = s.strip()
if is_quoted(s):
return s[1:-1].replace('\\' + s[0], s[0])
return s
class StringTree(MutableMapping[str, Any]): # export
class Error(Exception):
pass
class Match(Enum):
Equal = auto()
RegExArg = auto()
RegExConf = auto()
GlobArg = auto()
GlobConf = auto()
__parent: StringTree | None
children: OrderedDict[str, StringTree]
content: str | None
def __adopt_children(self, parent: StringTree) -> None:
assert isinstance(parent, StringTree)
slog(DEBUG, f'At {self.content}: Adopting children of {parent}')
#parent.dump(INFO, "These children are added")
self.content = parent.content
for name, c in parent.children.items():
if name not in self.children.keys():
slog(DEBUG, f'At {self.content}: Adding new child {c}')
self.children[name] = c
else:
self.children[name].__adopt_children(c)
def __set(
self,
path: str | None,
content: str | StringTree | None,
split: bool = True
) -> StringTree:
slog(
DEBUG,
('At "{}": '.format(str(self.content)) if hasattr(self, "content") else "")
+ f'Setting "{path}" -> "{content}"'
)
# Not sure what the idea behind this was. It often goes off, and all
# works fine without.
#assert self.content != str(content)
if content is not None and not isinstance(content, (str, StringTree)):
raise self.Error(
"Tried to add content of unsupported type {}".format(
type(content).__name__
)
)
if path is None:
if isinstance(content, str):
self.content = cleanup_string(content)
elif isinstance(content, StringTree):
self.__adopt_children(content)
slog(
DEBUG,
" -- content = >" + str(content) + "<, self.content = >" +
str(self.content) + "<"
)
return self
_path: str = cleanup_string(path)
if not _path:
#assert self.content is None or (
# isinstance(content, StringTree) and content.content == self.content
#)
if isinstance(content, StringTree):
#assert isinstance(content, StringTree), (
# f'Type: {type(content).__name__ }'
#)
self.__adopt_children(content)
else:
if self.content != content:
#self.content = cleanup_string(content)
slog(DEBUG, f'Changing content: "{self.content}" ->"{content}"')
assert (content != '"[a-zA-Z0-9+_*/-]"')
self.content = content
#assert(content != "'antlr_doesnt_understand_vertical_tab'")
#self.children[content] = StringTree(None, content)
return self
components: list[str] = _path.split('.') if split else [_path]
length: int = len(components)
#assert self.content is not None, f'Tried to set empty content to "{path}"'
nibble: str = components[0]
rest: str = '.'.join(components[1:])
if nibble not in self.children:
self.children[nibble] = StringTree('', content = nibble, parent = self)
if length > 1:
if len(rest) <= 0:
raise self.Error(f'{nibble} has missing child name')
return self.children[nibble].__set(rest, content = content)
# last component, a.k.a. leaf
if content is not None:
gc: StringTree = content if isinstance(content, StringTree) else StringTree(
'', content = content, parent = self.children[nibble]
)
if gc.content is None:
raise self.Error(f'Grandchild {nibble} has no content')
# Make sure no existing grand child is updated. It would reside too
# far up in the grand child OrderedDict, we need it last
if gc.content in self.children[nibble].children:
del self.children[nibble].children[gc.content]
self.children[nibble].children[gc.content] = gc
return self.children[nibble]
def __dump(self, prio: int, indent: int = 0, **kwargs: Any) -> None:
caller = kwargs['caller'] if 'caller' in kwargs.keys() else get_caller_pos(1)
slog(prio, '|' + (' ' * indent) + str(self.content), caller = caller)
indent += 2
for name, child in self.children.items():
child.__dump(prio, indent = indent, caller = caller)
def __find(
self,
key: str | None,
val: str | None,
m: Match,
depth_first: bool,
) -> list[StringTree]:
def __children() -> None:
for name, child in self.children.items():
ret.extend(child.__find(key, val, m, depth_first))
def __self() -> None:
_val: str = cast('str', self.value())
_content: str | None = self.content
try:
if ((key == _content and matcher(cast('str', val), _val))
or (key is None and matcher(cast('str', val), _val))
or (key == _content and val is None)):
ret.append(self)
except Exception as e:
raise self.Error(str(e)).with_traceback(e.__traceback__) from e
def __select_matcher(m: StringTree.Match) -> Callable[[str, str], bool]:
match m:
case self.Match.Equal:
return lambda x, y: x == y
case self.Match.RegExArg:
return lambda x, y: re.search(x, y) is not None
case self.Match.RegExConf:
return lambda x, y: re.search(y, x) is not None
case self.Match.GlobArg:
return lambda x, y: fnmatch.fnmatch(y, x)
case self.Match.GlobConf:
return lambda x, y: fnmatch.fnmatch(x, y)
case _:
raise NotImplementedError(f'Matcher {m} is not yet implemented')
def __debug_matcher(
matcher: Callable[[str, str], bool],
log_level: int = DEBUG
) -> Callable[[str, str], bool]:
def __matcher(x: str, y: str) -> bool:
slog(log_level, f'Comparing "{x}" ~ "{y}"')
return matcher(x, y)
return __matcher
if not self.children:
return []
matcher = __select_matcher(m)
ret: list[StringTree] = []
if depth_first:
__children()
__self()
else:
__self()
__children()
return ret
@staticmethod
def _dict_to_tree(
parent: StringTree,
data: dict[str, str | Any],
) -> None:
"""Recursively populate *parent* with entries from a nested dict."""
for key, value in data.items():
if isinstance(value, dict):
StringTree._dict_to_tree(parent.add(key), value)
else:
parent.add(key, str(value))
@override
def __repr__(self) -> str:
return 'st:"{}"'.format(self.content)
@override
def __str__(self) -> str:
return self.content or ''
@override
def __getitem__(self, path: str) -> StringTree:
ret = self.get(path)
if ret is None:
raise self.Error(path)
return ret
@override
def __setitem__(self, key: str, value: str) -> None:
self.__set(key, value)
@override
def __iter__(self) -> Iterator[str]:
return iter(self.children)
@override
def __delitem__(self, key: str) -> None:
if key in self.children:
del self.children[key]
@override
def __len__(self) -> int:
return len(self.children)
# -- Public API
def __init__(
self, path: str, content: str, parent: StringTree | None = None
) -> None:
slog(DEBUG, f'Constructing StringTree(path="{path}", content="{content}")')
self.__parent: StringTree | None = parent
self.children: OrderedDict[str, StringTree] = OrderedDict()
self.content: str | None = None
self.__set(path, content)
#assert self.content is not None
# root (content = [ symbols ])
# symbols (content = [ regex ])
# regex ( content ='[ \n\t\r]+' )
# root (content = root, children = [ symbols ])
# symbols (content = symbols, children = [ regex ])
# regex ( content = regex, children = [ '[ \n\t\r]+' ] )
# '[ \n\t\r]+)' ( content = '\n\t\r]+)', children = [] )
@property
def path(self) -> str:
if self.__parent is None:
return ''
prefix = self.__parent.path
if len(prefix):
prefix += '.'
return prefix + cast('str', self.content)
@property
def parent(self) -> StringTree | None:
return self.__parent
@property
def root(self) -> StringTree:
if self.__parent is None:
return self
return self.__parent.root
def set_content(self, content: str) -> None:
if content is None:
raise self.Error("Tried to set none content")
content = cleanup_string(content)
if len(content) == 0:
raise self.Error("Tried to set empty content")
self.content = content
def add(
self,
path: str,
content: str | StringTree | None = None,
split: bool = True
) -> StringTree:
slog(DEBUG, f'-- At "{self.content}": Adding "{path}" -> "{content}"')
return self.__set(path, content, split)
@override
def get(self, path: str, default: Any = None) -> StringTree | None:
slog(DEBUG, 'looking for "{}" in "{}"'.format(path, self.content))
_path: str = cleanup_string(path)
if len(_path) == 0:
slog(DEBUG, "returning myself")
return self
if is_quoted(path):
if _path not in self.children.keys():
return default
return self.children[_path]
components: list[str] = _path.split('.')
if len(components) == 0:
return self
name: str = cleanup_string(components[0])
if not hasattr(self, "children"):
return default
if name not in self.children.keys():
slog(DEBUG, "Name \"" + name + "\" is not in children of", self.content)
for child in self.children:
slog(DEBUG, "child = ", child)
return default
rel_path: str = '.'.join(components[1:])
return self.children[name].get(rel_path)
def value(self, path: str | None = None, default: str | None = None) -> str | None:
if path:
child = self.get(path)
if child is None:
if default:
return default
return None
return child.value()
if len(self.children) == 0:
raise self.Error('tried to get value from leaf "{}"'.format(self.content))
slog(DEBUG, f'Returning value from children {self.children}')
return self.children[next(reversed(self.children))].content
def child_list(self, depth_first: bool = True) -> list[StringTree]:
if not depth_first:
raise self.Error(
'Tried to retrieve child list with breadth-first '
'search, not yet implemented'
)
r: list[StringTree] = []
for name, c in self.children.items():
r.append(c)
r.extend(c.child_list())
return r
def dump(self, prio: int, *args: str, **kwargs: Any) -> None:
caller = kwargs['caller'] if 'caller' in kwargs.keys() else get_caller_pos(1)
msg: str = ''
if args is not None:
msg = ' ' + ' '.join(args) + ' '
slog(prio, ",------------" + msg + "----------- >", caller = caller)
self.__dump(prio, indent = 0, caller = caller)
slog(prio, "`------------" + msg + "----------- <", caller = caller)
def find(
self,
key: str | None = None,
val: str | None = None,
match: Match = Match.Equal,
depth_first: bool = False
) -> list[str]:
ret: list[str] = []
for node in self.__find(key, val, m = match, depth_first = depth_first):
if node.parent is None:
continue
ret.append(node.parent.path)
return ret
@classmethod
def read(
cls,
path: str,
root_content: str = 'root',
log_prio: int = INFO,
paths_buf: list[str] | None = None
) -> StringTree:
from .serdes import read
return read(
path,
root_content = root_content,
log_prio = log_prio,
paths_buf = paths_buf
)
@classmethod
def from_dict(
cls,
data: dict[str, str | Any],
root_content: str = 'root',
) -> StringTree:
"""Build a StringTree from a nested dict.
Dict values that are dicts represent sub-trees. All other values
are converted to strings via ``str()``. Keys are path components;
dotted keys are expanded just as with :meth:`add`.
Example::
>>> tree = StringTree.from_dict({'section': {'key': 'value'}})
>>> tree.value('section.key')
'value'
"""
tree: StringTree = cls('', content = root_content)
cls._dict_to_tree(tree, data)
return tree