jw-python/src/python/jw/util/Config.py

213 lines
7.1 KiB
Python
Raw Normal View History

from __future__ import annotations
import glob
import os
import re
import sys
from collections.abc import Iterator, Mapping
from pathlib import Path
mypy: Fix disallow_incomplete_defs fallout Add parameter and return type annotations to untyped functions all over the package: - ldap.py: Add return types to Config properties (ldap_uri, bind_dn, bind_pw, base_dn), Connection.__init__, add, delete, walk, find, __oc_recurse_to_top, object_class_path, and inner callbacks - cast.py: Add Any import, add return type annotations to cast_str_to_bool, guess_type, from_str, from_env, cast_str, and parameter type annotations where missing - Table.py: - __init__ (schema: Schema) - __eq__ (rhs: Any) - _column_data_type (name: str) - _column_default (name: str) - column_default (name: str) - foreign_keys_to_parent_table (parent_table: Any) - misc.py: - get_derived_classes (mod: Any, flt: Any) - load_classes (flt: Any) - load_class_names (remove_flt: bool) - load_object (*args: Any, **kwargs: Any) - multi_regex_edit (spec: Any) - dump_dict (*args: Any, **kwargs: Any) - get_derived_classes (mod: Any, flt: Any) - load_classes (flt: Any) - load_class_names (remove_flt: bool) - load_object (*args: Any, **kwargs: Any) - dump (*args: Any, **kwargs: Any) - MapAttr2Shape.py, ShuntingYard.py, Queries.py: - Add parameter and return type annotations to fix disallow_incomplete_defs: - MapAttr2Shape.py: __keys, __attribs, __massage_node, __massage_nodes, __add - ShuntingYard.py: Op.__init__, tokenize, infix_to_postfix, eval_postfix, eval - Queries.py: _run, _register, name property, __getitem__, keys, load, add, _add - Add parameter and return type annotations: - ArgsContainer.py: __setattr__, args, kwargs, dump, specified_args, add_argument - rows.py: rows_duplicates, rows_check_not_null, rows_dumps, rows_dump - auth/Auth.py: load, conf, _entity, projects - auth/ldap/Auth.py: __init__, _create_entity - Fix parameter type annotations: - rows_check_not_null: keys: str | list[str], stat_key: str | None, caller: Any - rows_dumps: lead: str | list[str] | None, tablefmt: str | None - rows_dump: heading: str | None, lead: str | list[str] | None, tablefmt: str | None - Table.py: column_default, add_row_location, add_child_row_location - CompositeForeignKey.py: __table, parent_column, child_column - TableIoHandler.py: _load, _store, load - Query.py: _register, register, parent property - Ldap.py: Entity.__init__, Ldap.__init__, _create_entity - MapAttr2Shape.py, auth/ldap/Auth.py, Query.py: - MapAttr2Shape.py: Add None check for id, add None check for graph - auth/ldap/Auth.py: Add Any import, fix __init__ and _create_entity - Query.py: Fix _add, run, parent signatures - ArgsContainer.py: __setattr__, args, kwargs, dump, specified_args, add_argument - Config.py: dump - ShuntingYard.py: Op.__init__, tokenize, infix_to_postfix, eval_postfix, eval - ShellCmd.py: __init__ - auth/Auth.py: load, __init__ - auth/dummy/Auth.py: Entity.__init__, Auth.__init__ - auth/ldap/Auth.py: Entity.__init__, Auth.__init__, _create_entity - cast.py: guess_type - DataBase.py: _create_session, _delete_session - TableIoHandler.py: load - Query.py: _run, _register, register, _add, run, parent/db properties - QueryResult.py: pages, _cast - rows.py: rows_duplicates, rows_check_not_null, rows_dumps, rows_dump - Column.py: __eq__, foreign_key - Schema.py: _access_defining_columns, access_defining_columns, table_by_model_name - Table.py: __init__, __eq__, _column_data_type, _column_default, column_default, __relationship_by_foreign_table, add_row_location, add_child_row_location - utils.py: check_schema - EventRouter.py: iter_peers - Group.py: __init__ - SimpleEntity.py: __init__ - Ldap.py: Entity.__init__, Ldap.__init__, _create_entity - Event.py: __init__ - Fuse.py: __init__ - Object.py: __init__ - SimpleObject.py: __init__, create - EvRequest.py: __init__ - Msg.py: __init__ - ldap.py: Config.__get__, Config properties, Connection methods, inner callbacks - misc.py: get_derived_classes, load_classes, load_class_names, load_object, multi_regex_edit, dump_dict, dump - multi_key_dict.py: items - MapAttr2Shape.py: __keys, __attribs, __massage_node, __massage_nodes, __add - auth/dummy/Auth.py: Entity.__init__, Auth.__init__ - Query.py: _run, _register, register, _add, run, parent/db properties - QueryResult.py: pages, _cast - Column.py: __eq__, foreign_key - Schema.py: _access_defining_columns, access_defining_columns, table_by_model_name - Table.py: __init__, __eq__, _column_data_type, _column_default, column_default, __relationship_by_foreign_table, add_row_location, add_child_row_location - utils.py: check_schema - EventRouter.py: iter_peers - Group.py: __init__ - SimpleEntity.py: __init__ - Ldap.py: Entity.__init__, Ldap.__init__, _create_entity - Event.py: __init__ - Fuse.py: __init__ - Object.py: __init__ - SimpleObject.py: __init__, create - EvRequest.py: __init__ - Msg.py: __init__ 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-07-24 22:34:10 +02:00
from typing import Any, override
from .stree import serdes
from .log import DEBUG, ERR, slog, get_caller_pos
from .stree.StringTree import StringTree
# Default file mode mask for secret-checking: reject group-write or
# world-accessible files that contain password/secret-like content.
_REFUSE_MODE_MASK: int = 0o0027
class Config(Mapping[str, str]): # export
def __load(
self,
search_dirs: list[str] | None,
glob_paths: list[str] | str | None,
refuse_mode_mask: int | None
) -> StringTree:
ret = StringTree("", "")
exe = Path(os.path.basename(sys.argv[0])).stem
if glob_paths is None:
glob_paths = [f'.{exe}', f'{exe}.conf']
elif isinstance(glob_paths, str):
glob_paths = [glob_paths]
if search_dirs is None:
env_key = re.sub('[-.]', '_', exe)
env_val = os.getenv(env_key)
if env_val is not None:
search_dirs = env_val.split(':')
for path in glob_paths:
dirs = search_dirs
if dirs is None:
if path and os.path.isabs(path):
dirs = ['']
else:
dirs = [str(Path.home()), str(Path.cwd())]
for d in dirs:
g = d + '/' + path if len(d) else path
slog(DEBUG, 'Looking for config "{}"'.format(g))
for f in glob.glob(g):
slog(DEBUG, 'Reading config "{}"'.format(f))
paths_buf: list[str] = []
tree = serdes.read(f, paths_buf = paths_buf)
assert len(paths_buf) > 0, \
f'Expected at least one path in paths_buf, got {len(paths_buf)}'
if refuse_mode_mask is not None:
for p in paths_buf:
st = os.stat(p)
if st.st_mode & refuse_mode_mask:
for item in tree.child_list():
if item.content is None:
continue
if not re.search('password|secret',
item.content,
flags = re.IGNORECASE):
continue
msg = (
'Config files define secret, but at least one '
'has file permissions open for world'
)
slog(ERR, f'{msg}:')
for pp in paths_buf:
mode = (os.stat(pp).st_mode) & 0o7777
slog(ERR, f' {mode:o} {pp}')
raise Exception(msg)
tree.dump(DEBUG, f)
ret.add("", tree)
return ret
def __init__(
self,
search_dirs: list[str] | None = None,
glob_paths: list[str] | None = None,
glob_paths_env_key: str | None = None,
defaults: dict[str, str] | None = None,
tree: StringTree | None = None,
parent: Config | None = None,
root_section: str | None = None,
refuse_mode_mask: int = _REFUSE_MODE_MASK
) -> None:
self.__parent = parent
if tree is not None:
assert (search_dirs is None)
assert (glob_paths is None)
assert (glob_paths_env_key is None)
self.__conf = tree
else:
assert (tree is None)
if glob_paths_env_key is not None:
glob_paths_env = os.getenv(glob_paths_env_key)
if glob_paths_env is not None:
if glob_paths is None:
glob_paths = []
glob_paths.extend(glob_paths_env.split(':'))
self.__conf = self.__load(
search_dirs = search_dirs,
glob_paths = glob_paths,
refuse_mode_mask = refuse_mode_mask
)
if root_section is not None:
tmp = self.__conf.get(root_section)
if tmp is None:
tmp = StringTree("", "")
self.__conf = tmp
if defaults is not None:
for key, val in defaults.items():
if self.__conf.get(key) is None:
self.__conf[key] = val
self.__conf.dump(DEBUG, "superposed configuration")
@override
def __getitem__(self, key: str) -> str:
ret = self.get(key)
if ret is None:
raise KeyError(key)
return ret
@override
def __iter__(self) -> Iterator[str]:
return iter(self.__conf)
@override
def __len__(self) -> int:
return len(self.__conf)
def __setitem__(self, key: str, value: str) -> None:
self.set(key, value)
@property
def parent(self) -> Config | None:
return self.__parent
@property
def root(self) -> Config:
if self.__parent is None:
return self
return self.__parent.root
def set(self, key: str, val: str) -> None:
self.__conf[key] = val
# Narrowing default and return value from Any to str by overriding
# Mapping.get(). That will work for all callers but isn't accepted by mypy,
# so ignore[override].
@override
def get( # type: ignore[override]
self,
key: str,
default: str | None = None
) -> str | None:
item = self.__conf.get(key)
if item:
return item.value()
return default
def entries(self, key: str) -> list[str]:
item = self.__conf.get(key)
if item is None:
return []
return [name for name, child in item.children.items()]
# This is an alias for get()
def value(self, key: str, default: str | None = None) -> str | None:
return self.get(key, default)
def branch(self, path: str, throw: bool = True) -> Config | None:
if self.__conf:
tree = self.__conf.get(path)
if tree is None:
msg = f'Tried to get non-existent branch "{path}" from config'
if not throw:
slog(DEBUG, msg)
return None
self.dump(ERR, msg)
raise Exception(msg)
return Config(tree = tree, parent = self)
return None
mypy: Fix disallow_incomplete_defs fallout Add parameter and return type annotations to untyped functions all over the package: - ldap.py: Add return types to Config properties (ldap_uri, bind_dn, bind_pw, base_dn), Connection.__init__, add, delete, walk, find, __oc_recurse_to_top, object_class_path, and inner callbacks - cast.py: Add Any import, add return type annotations to cast_str_to_bool, guess_type, from_str, from_env, cast_str, and parameter type annotations where missing - Table.py: - __init__ (schema: Schema) - __eq__ (rhs: Any) - _column_data_type (name: str) - _column_default (name: str) - column_default (name: str) - foreign_keys_to_parent_table (parent_table: Any) - misc.py: - get_derived_classes (mod: Any, flt: Any) - load_classes (flt: Any) - load_class_names (remove_flt: bool) - load_object (*args: Any, **kwargs: Any) - multi_regex_edit (spec: Any) - dump_dict (*args: Any, **kwargs: Any) - get_derived_classes (mod: Any, flt: Any) - load_classes (flt: Any) - load_class_names (remove_flt: bool) - load_object (*args: Any, **kwargs: Any) - dump (*args: Any, **kwargs: Any) - MapAttr2Shape.py, ShuntingYard.py, Queries.py: - Add parameter and return type annotations to fix disallow_incomplete_defs: - MapAttr2Shape.py: __keys, __attribs, __massage_node, __massage_nodes, __add - ShuntingYard.py: Op.__init__, tokenize, infix_to_postfix, eval_postfix, eval - Queries.py: _run, _register, name property, __getitem__, keys, load, add, _add - Add parameter and return type annotations: - ArgsContainer.py: __setattr__, args, kwargs, dump, specified_args, add_argument - rows.py: rows_duplicates, rows_check_not_null, rows_dumps, rows_dump - auth/Auth.py: load, conf, _entity, projects - auth/ldap/Auth.py: __init__, _create_entity - Fix parameter type annotations: - rows_check_not_null: keys: str | list[str], stat_key: str | None, caller: Any - rows_dumps: lead: str | list[str] | None, tablefmt: str | None - rows_dump: heading: str | None, lead: str | list[str] | None, tablefmt: str | None - Table.py: column_default, add_row_location, add_child_row_location - CompositeForeignKey.py: __table, parent_column, child_column - TableIoHandler.py: _load, _store, load - Query.py: _register, register, parent property - Ldap.py: Entity.__init__, Ldap.__init__, _create_entity - MapAttr2Shape.py, auth/ldap/Auth.py, Query.py: - MapAttr2Shape.py: Add None check for id, add None check for graph - auth/ldap/Auth.py: Add Any import, fix __init__ and _create_entity - Query.py: Fix _add, run, parent signatures - ArgsContainer.py: __setattr__, args, kwargs, dump, specified_args, add_argument - Config.py: dump - ShuntingYard.py: Op.__init__, tokenize, infix_to_postfix, eval_postfix, eval - ShellCmd.py: __init__ - auth/Auth.py: load, __init__ - auth/dummy/Auth.py: Entity.__init__, Auth.__init__ - auth/ldap/Auth.py: Entity.__init__, Auth.__init__, _create_entity - cast.py: guess_type - DataBase.py: _create_session, _delete_session - TableIoHandler.py: load - Query.py: _run, _register, register, _add, run, parent/db properties - QueryResult.py: pages, _cast - rows.py: rows_duplicates, rows_check_not_null, rows_dumps, rows_dump - Column.py: __eq__, foreign_key - Schema.py: _access_defining_columns, access_defining_columns, table_by_model_name - Table.py: __init__, __eq__, _column_data_type, _column_default, column_default, __relationship_by_foreign_table, add_row_location, add_child_row_location - utils.py: check_schema - EventRouter.py: iter_peers - Group.py: __init__ - SimpleEntity.py: __init__ - Ldap.py: Entity.__init__, Ldap.__init__, _create_entity - Event.py: __init__ - Fuse.py: __init__ - Object.py: __init__ - SimpleObject.py: __init__, create - EvRequest.py: __init__ - Msg.py: __init__ - ldap.py: Config.__get__, Config properties, Connection methods, inner callbacks - misc.py: get_derived_classes, load_classes, load_class_names, load_object, multi_regex_edit, dump_dict, dump - multi_key_dict.py: items - MapAttr2Shape.py: __keys, __attribs, __massage_node, __massage_nodes, __add - auth/dummy/Auth.py: Entity.__init__, Auth.__init__ - Query.py: _run, _register, register, _add, run, parent/db properties - QueryResult.py: pages, _cast - Column.py: __eq__, foreign_key - Schema.py: _access_defining_columns, access_defining_columns, table_by_model_name - Table.py: __init__, __eq__, _column_data_type, _column_default, column_default, __relationship_by_foreign_table, add_row_location, add_child_row_location - utils.py: check_schema - EventRouter.py: iter_peers - Group.py: __init__ - SimpleEntity.py: __init__ - Ldap.py: Entity.__init__, Ldap.__init__, _create_entity - Event.py: __init__ - Fuse.py: __init__ - Object.py: __init__ - SimpleObject.py: __init__, create - EvRequest.py: __init__ - Msg.py: __init__ 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-07-24 22:34:10 +02:00
def dump(self, prio: int, *args: Any, **kwargs: Any) -> None:
caller = get_caller_pos(1, kwargs)
self.__conf.dump(prio, caller = caller, *args, **kwargs)
@property
def name(self) -> str | None:
return self.__conf.content
def find(
self,
key: str | None,
val: str | None,
match: StringTree.Match = StringTree.Match.Equal
) -> list[str]:
return self.__conf.find(key, val, match = match)
#def __getattr__(self, name: str):
# return getattr(self.__conf, name)