When jw.include merges content at a target path, the local content in
the main document should take precedence over the included content
(siblings win, and the main file is the ultimate source of truth).
Fix _merge_at_path so that root's existing content at the target path
wins over the value being merged in.
Also update the test_include_override_existing test to reflect the
correct semantics: local content overrides included content.
Signed-off-by: Jan Lindemann <jan@janware.com>
Add two functions, add_hide_log_patterns() and
clear_hide_log_patterns(). Their intended purpose is to keep secrets
from leaking into logging. add_hide_log_patterns() takes compiled
regular expressions, strings or arrays thereof that are added to the
global pattern list. It defaults to ["secret", "password", "token"],
case-insensitive. clear_hide_log_patterns() clears the list, so the
caller must start from scratch building one.
This keeps sensitive keys visible for debugging while suppressing
their child values from log output.
In addition to these two functions, debug logging was removed in some
places where the effort of keeping would have outweighed the gain.
Signed-off-by: Jan Lindemann <jan@janware.com>
frame_parameters() returns a dictionary of name -> value pairs with
the parameters of the current call frames.
They can be limited by specifying exclude_names and exclude_values
which do the obvious thing.
Signed-off-by: Jan Lindemann <jan@janware.com>
Make Auth.Kind inherit from Flag rather than Enum, and introduce
Kind.Both, allowing an entity to be both Group and User.
Signed-off-by: Jan Lindemann <jan@janware.com>
Add type annotations to 30 files across jw.util, resolving all
191 'no-untyped-def' mypy errors in strict mode.
The changes cover Signals, CppState, Bunch, RedirectStdIO, StopWatch,
Process, Options, ArgsContainer, Object, multi_key_dict, ldap, Session,
rows, ShuntingYard, TableIoHandler, DataBase, Queries, Query, QueryResult,
and all db/schema files (Column, Table, ColumnSet, DataType, Schema,
SingleForeignKey, CompositeForeignKey), plus asyncio variants and
ev/base/Object and auth/dummy/Auth.
Additionally, unreachable code and type annotation conflicts were
resolved in StopWatch.py, Options.py, rows.py, and Table.py.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v0.82.0
Signed-off-by: Jan Lindemann <jan@janware.com>
Add proper type annotations to fix mypy warn_return_any errors.
The following files were modified to add cast() calls or return
type annotations where functions returned Any values:
- algo/ShuntingYard.py: Add cast for operator() return value
- auth/Auth.py: Add cast for load() return value, fix imports
- cast.py: Fix cast_str_to_int return type, fix _strip type
- db/TableIoHandler.py: Remove redundant cast, fix store() return
- db/query/Queries.py: Add cast for _run() and __getitem__ returns
- db/query/Query.py: Add cast for db property return
- db/query/QueryResult.py: Add cast for db and query property returns
- db/schema/Schema.py: Add return type to __tables property, cast columns
- db/schema/Table.py: Add cast for model_module_search_paths return
- ev/app/EventRouter.py: Add cast for peer_conf.get() return
- ev/base/Object.py: Add cast for get_conf_section and str_or_none returns
- ev/base/SimpleObject.py: Add cast for create() return, fix imports
- load_yaml.py: Add cast for _expand_links_recursive return
- misc.py: Fix object_builtin_name return type, add param annotations
- stree/StringTree.py: Fix get() return type with default_value variable
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v0.82.0
Signed-off-by: Jan Lindemann <jan@janware.com>
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>
Fix fallout of mypy --warn-unreachable --error-code=exchaustive-match.
The warn_unreachable and exhaustive-match mypy directives exposed several
classes of issues: unreachable statements after exhaustive matches,
unreachable isinstance checks on already-narrowed types, dead code after
raise statements, and missing None in type unions where the code
checked for it at runtime.
Fix the following files:
- Config.py: Broaden glob_paths parameter type to accept str, matching
the isinstance check in the function body.
- ldap.py: Remove dead code (unreachable if-block with False condition
and unreachable continue after raise).
- DataType.py: Use case _ fallback in py_type() match for exhaustive-
match compliance, remove redundant isinstance check and assertion
that were unreachable given type annotations.
- Event.py: Add | None to Dest type alias where the code checks for
None at runtime.
- EventHub.py: Add | None to peer_confs variable type annotation where
the code checks for None at runtime.
- StringTree.py: Fix is_quoted() to accept only str (not StringTree),
fix __set() path parameter type to str | None, remove dead code after
exhaustive isinstance checks, remove unnecessary assert.
- auth/ldap/Auth.py: Remove unreachable continue statement after raise.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v0.82.0
Signed-off-by: Jan Lindemann <jan@janware.com>
Fix fallout of mypy --enable-error-code=ignore-without-code check.
The multi_key_dict class had several type issues: the keys() and values()
methods could implicitly return None when a key type was specified but not
found, pyright flagged the conditional items() redefinition, and six test
call sites carried bare "# type: ignore" comments.
Add from __future__ import annotations, a _keys_from_dict() helper, and
proper parameter/return type annotations to keys(), values(), and items().
Consolidate the conditional Python 2/3 items() into a single function with
runtime dispatch. Remove all six bare type-ignores from multi_key_dict.py
and annotate the remaining pre-existing ones in other files with specific
error codes required by ignore-without-code.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v0.82.0
Signed-off-by: Jan Lindemann <jan@janware.com>
Rename the AuthEntity class to Entity, because the Auth prefix is
redundant if used in / imported from the auth module.
Next, put all relevant properties into that class, and make User and
Group a TypeAlias of that type. Introduce an Enum, "Kind", to allow a
distinction. See the previous commits for a rationale.
Signed-off-by: Jan Lindemann <jan@janware.com>
Auth objects can currently be loaded dynamically with a Config type
argument. For greater flexibility, allow to pass dict and StringTree
mappings to load(), too.
Signed-off-by: Jan Lindemann <jan@janware.com>
Expecting possible confusion regarding further base class gymnastics,
e.g. multiple inheritance, make it impossible to pass constructor
arguments to User and Group as blank positional arguments, force
passing the argument names instead by adding "*" as first argument.
Signed-off-by: Jan Lindemann <jan@janware.com>
User and Group share now enough properties to tie them closer
together. The number of these properties will likely grow:
email-address, nested groups and others. This commit introduces
AuthEntity as a common base class to make that happen.
Signed-off-by: Jan Lindemann <jan@janware.com>
jw.include now supports specifying a target path where the included
content should be merged, using syntax similar to named links:
jw.include: "path.to.target|/path/to/file.yaml"
The file's contents are deep-merged into the target path in the
resulting document tree. If the target path doesn't exist,
intermediate dicts are created automatically.
Original behavior (plain string) still works:
jw.include: "/path/to/file.yaml"
This merges the file at the root of the document.
Mixed usage is supported:
jw.include:
- "/path/to/plain.yaml"
- section|/path/to/target.yaml
Added 8 unit tests covering: plain includes, nested paths, deep paths,
merge with existing, override existing, multiple paths, optional
includes, and mixed plain/path includes.
Signed-off-by: Jan Lindemann <jan@janware.com>
jw.inplace-link behaves like jw.link but can have sibling keys that
are deep-merged into the resolved target dict (siblings override target
on conflict).
Usage:
entry:
jw.inplace-link: path.to.target
sibling_key: value
Expands to:
entry:
<merged result of path.to.target + sibling_key: value>
This solves the common use case of pulling in a dict from elsewhere
while overriding specific keys inline.
Added 12 unit tests covering: no siblings, dict siblings, scalar
siblings, non-dict targets, relative paths, cycle detection, chains,
list siblings, list items, deep nesting, sibling override, and
integration with jw.include.
Signed-off-by: Jan Lindemann <jan@janware.com>
The include directive was previously triggered by a bare "include"
key in YAML files. This could collide with user-defined keys.
Rename it to "jw.include" so that:
jw.include: file.yaml
jw.include:
- file1.yaml
- file2.yaml
is used instead of just "include:". This follows the convention
established by "jw.link" for link expansion markers.
Signed-off-by: Jan Lindemann <jan@janware.com>
Implement link expansion in _expand_links() to resolve jw.link markers
in YAML documents after the include/merge phase. Two link forms are
supported:
- Inplace links jw.link: "path.to.target" replace the marker entirely
with the resolved value at the target path.
- Named links jw.link: "name|path.to.target" replace the marker with
{name: resolved_value}, using the first path segment as the key.
Paths use dot-separated segments. Relative paths start with ".."
(like Python imports): "." stays at the current level, ".." goes up
one level, "..." two, and so on. A single pipe character in the link
value separates the link name from the target path for named links.
The implementation includes:
- _parse_link(): splits a link value into (is_named, name, path)
- _resolve_path(): resolves an absolute or relative path to a value
- _expand_links_recursive(): walks the structure, expands links,
detects cycles via a resolving set, and memoises via a resolved dict.
Cyclic links and missing targets both raise ValueError/KeyError.
jw.link markers with sibling keys are left unexpanded.
Add 86 unit tests covering the entire load_yaml module:
- Basic YAML loading, optional loading, root type checking
- Include directive (single, multiple, deep merge, circular detect)
- Inplace links, named links, relative paths (up, descend, same level)
- Transitive links, cycle detection, missing targets
- Regression tests, combined include+links, edge cases, type preservation
Signed-off-by: Jan Lindemann <jan@janware.com>
Add load_yaml.load_yaml(), adding little over yaml.safe_load(), aside
from supporting a toplevel entry "include", which can contain a list
of included paths.
Signed-off-by: Jan Lindemann <jan@janware.com>
Add some introspection properties to Object, to make it suitable as a
lightweight base class for named objects.
Signed-off-by: Jan Lindemann <jan@janware.com>
Add the func_tools module for giving the private_method decorator a
home.
The decorator enforces that a method can only be called by methods
belonging to the same class. It inspects the call stack at runtime
and raises AttributeError if the caller is not a method of the owning
class.
When decorating a class, the decorator scans all other class members
for functions (including static, class, and other private methods) and
records their code objects as allowed callers. The __get__() method
returns a wrapper that checks the current frame's code object against
this set before dispatching to the actual method.
Signed-off-by: Jan Lindemann <jan@janware.com>
Add the module enum_helper, providing the following functions:
def kebab_to_pascal(value: str) -> str
def pascal_to_kebab(value: str) -> str
def enum_from_kebab(enum_cls: type[EnumType], value: str) -> EnumType
def enum_to_kebab(member: Enum) -> str
The intended use of these functions is to convert from configuration
strings to application enums and back.
Signed-off-by: Jan Lindemann <jan@janware.com>
load_path() takes a string as module path. To broaded its
versatility, allow also multiple strings to be searched in order.
Signed-off-by: Jan Lindemann <jan@janware.com>
Add a function that allows to test one expression if a value can be
iterated over without being a string or bytes.
Signed-off-by: Jan Lindemann <jan@janware.com>
Add some type hints to the misc module, and remove the unused
silentremove functionality. Also, make the jwutils facade follow the
move.
Signed-off-by: Jan Lindemann <jan@janware.com>
Depending on whether or not a name or type filter is used, the
exception message of load_class() can be a bit confusing. Fix that.
Signed-off-by: Jan Lindemann <jan@janware.com>
Make load_class() use jw.pkg.lib.LoadTypes, because it provides the
possibility to nicely log which modules and classes it picks.
TODO: Don't use importlib at all in module misc.
Signed-off-by: Jan Lindemann <jan@janware.com>
Derive Config from collections.abc.Mapping to formally declare it as
a read-only mapping interface. Implement the three abstract methods:
- __getitem__(): delegates to get(), raises KeyError if missing
- __iter__(): iterates over config keys (delegated to __conf)
- __len__(): returns number of top-level keys
Add @override to __getitem__(), __iter__(), and __len__(). The get()
method does not get @override — Mapping.get() uses generic overloads
with Any-typed parameters that are incompatible with Config.get()’s
specific str-typed signature. While Config.get() is Liskov-safe
(contravariant args, covariant return), mypy flags the mismatch on
the def line. A targeted "# type: ignore[override]" suppresses only
this one false positive without disabling override checking for the
rest of the module.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v
Signed-off-by: Jan Lindemann <jan@janware.com>
Replace Optional[X] with X | None and typing.Dict with builtin dict
throughout the module. Add "from __future__ import annotations" to
enable deferred evaluation, removing all quoted forward references.
Add missing return type annotations to __setitem__(), parent, root,
set(), get(), value(), and name. Remove Optional and Dict from the
typing import since cast() is the only runtime typing helper needed.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v
Signed-off-by: Jan Lindemann <jan@janware.com>
The __load() method has no type annotations for any of its three
parameters, making it inconsistent with __init__ and harder for type
checkers to verify correctness. Add type annotations to all __load()
parameters and the paths_buf local variable.
The paths_buf variable needs an explicit list[str] annotation because
mypy cannot infer the type of an empty list literal when passed as
a mutable buffer argument to serdes.read().
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v
Signed-off-by: Jan Lindemann <jan@janware.com>
The bare assert (len(paths_buf)) relies on truthiness which, while
correct, is misleading — readers might expect "assert len(paths_buf)
> 0" instead. Replace with an explicit comparison and add a diagnostic
message showing the actual length for easier debugging.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v
Signed-off-by: Jan Lindemann <jan@janware.com>
The branch() method returns either None or a Config but has no
return type annotation — just a "# type: ignore" comment with a
FIXME. Add the proper Optional[Config] annotation (written as
Config | None in modern syntax) and remove the workaround.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v
Signed-off-by: Jan Lindemann <jan@janware.com>
Extract the magic 0o0027 default for refuse_mode_mask into a module-
level constant with a docstring. This makes the default parameter
self-documenting and prevents duplication if the value ever changes.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v
Signed-off-by: Jan Lindemann <jan@janware.com>
The __is_abs() helper duplicates os.path.isabs() logic. Replace it
with the standard library function, guarding for None/empty strings
to match the original helper safety behavior.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v
Signed-off-by: Jan Lindemann <jan@janware.com>
When search_dirs comes from an environment variable, the __load()
method iterates over each character of the colon-separated string
instead of treating it as a list of directory paths. This produces
nonsensical glob paths like "h/", "o/", "m/", etc.
Fix by splitting the env var value into a list before assigning it
to the search_dirs variable.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v
Signed-off-by: Jan Lindemann <jan@janware.com>
Reorder the StringTree class members to follow the project coding
style:
1. Nested public/helper types (Error, Match) at the top.
2. Instance attribute annotations so mypy can track them before
__adopt_children runs in __init__.
3. Private methods (__adopt_children, __set, __dump, __find) grouped
together, with _dict_to_tree moved from module scope into the
class as a @staticmethod.
4. Dunder methods (__repr__ through __len__) between private and public.
5. Public API preceded by # -- Public API comment, with __init__
moved from the top into this section.
6. _dict_to_tree recursive call updated to StringTree._dict_to_tree()
to avoid the bare-name lookup that mypy rejects on a @staticmethod.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v0.80.2
Signed-off-by: Jan Lindemann <jan@janware.com>
StringTree declares itself as a Mapping but implements __setitem__
which returns StringTree — neither correct for Mapping nor for
MutableMapping. This commit changes the base class to MutableMapping
and fixes the signatures to match the ABC contract: __setitem__ now
returns None, and __delitem__ is implemented by delegating to the
underlying OrderedDict.
The __setitem__ return value change is an API break for callers that
rely on its StringTree return. Those callers should use add() instead.
This is acceptable because the previous type signature was silently
incorrect — it violated the Mapping abstract base class contract.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v0.80.2
Signed-off-by: Jan Lindemann <jan@janware.com>
The StringTree class and its companion serdes module have minimal
type annotations — only method signatures and a few instance
attributes were typed. This commit adds proper type annotations to
every parameter, return type, and local variable across both files.
cleanup_string() gains overloaded signatures so callers passing str
get str back, avoiding the need to widen the return type everywhere.
The matcher return type in __find is narrowed from Any to
Callable[[str, str], bool]. Casts are used sparingly where the
runtime guarantees a narrower type than the checker can infer (e.g.
self.value() always returns str when called without path, despite the
return annotation being str | None).
Variable annotations in StringTree.__set, get, __find, child_list, and
dump cover local bindings. serdes gains full parameter and return type
coverage plus annotations for all local variables in _cleanup_line,
parse, _read_lines_from_one_path, and _read_lines.
The get() default parameter remains Any because overriding
Mapping.get with a concrete type breaks the Liskov substitution
principle — Mapping.get is generic over the default type.
Assisted-by: unsloth/Qwen3.6-35B-A3B-GGUF:IQ4_NL with pi.dev v0.80.2
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit refactors the order of functions a little from used to
using.
It also fixes a bug: .find() could omit matching entries, fixes
intricate case distinction, and doesn't ignore re.PatternError
anylonger.
Signed-off-by: Jan Lindemann <jan@janware.com>
Raise a specialized StringTree.Error rather than a bare Exception to
allow callers to distinguish where it came from.
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit derives StringTree from Mapping, allowing it to be used
as a drop-in-replacement for dictionaries returned from load_yaml().
Note that this is a breaking change, because it changes the return
value of __getitem__() from str to StringTree. Either this or get()
have to give, because the base class uses __getitem__() to implement
get(), and returning different types from these, as it's currently
the case would break caller expectations.
To mitigate the pain of the breakage, __str__() now returns .content
or "", and can be used to easily convert []'s return value to a
string.
Signed-off-by: Jan Lindemann <jan@janware.com>
Add StringTree.read() which is a frontend for serdes.read(), saving
one import from the caller's perspective.
Signed-off-by: Jan Lindemann <jan@janware.com>
Some methods take a "path_" argument, which is not nice for callers.
Rename it to "path" and fix the fallout in the method bodies.
Signed-off-by: Jan Lindemann <jan@janware.com>
Remove jw-python's implementation of the log module entirely, making
it a facade of jw-pkg's implementation. This removes reduncancy and
duplicate state.
Signed-off-by: Jan Lindemann <jan@janware.com>