Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
226ae4901c
Release 1.0.0-64
All checks were successful
CI / Packaging - Kali Linux (push) Successful in 5m28s
CI / Packaging - OpenSUSE Tumbleweed (push) Successful in 6m1s
CI / Packaging test (push) Successful in 0s
2026-11-21 01:17:18 +01:00
62d308ef88
[PR jw/#6] load_yaml: Redirect and parameterize includes for tests
All checks were successful
CI / Packaging - Kali Linux (push) Successful in 5m6s
CI / Packaging - OpenSUSE Tumbleweed (push) Successful in 5m31s
CI / Packaging test (push) Successful in 0s
Merge pull request "load_yaml: Redirect and parameterize includes for tests"

Upstream-repo: ssh://git@code.janware.com/janware/jw-python
Source-branch: jan/feature/20261120-load-yaml-redirect-and-parameterize-includes-for-tests
Target-branch: master
Reviewed-on: #6
2026-11-20 23:01:08 +01:00
2e85f3ccf8
load_yaml: Support jw.include-map-no-absolute
All checks were successful
CI / Packaging - Kali Linux (pull_request) Successful in 5m5s
CI / Packaging - OpenSUSE Tumbleweed (pull_request) Successful in 5m30s
CI / Packaging test (pull_request) Successful in 0s
A test that redirects production includes with jw.include-map can silently
read a real production path when the map misses a spec, making the test
depend on the host's /etc without any warning.

Add a jw.include-map-no-absolute key next to the map. When true, an
absolute include spec that matched no map entry raises ValueError, naming
the spec and the including file; an identity entry whitelists an absolute
path that may be read. The key defaults to false and applies to the whole
include tree: _load_yaml() pops it in the top-level document, rejects it
in included documents, and threads it to _parse_include_spec(), where the
check runs before the normal disk lookup.

Signed-off-by: Jan Lindemann <jan@janware.com>
Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.6.0
2026-11-20 22:39:55 +01:00
5d94a1fcee
load_yaml: Add jw.include-map
This commit adds support for interpreting a new syntax:

  jw.include-map:
    - /etc/some/file.conf: ../../../file.conf
    - /opt/blah/another/config.yaml: ../../../config.yaml

Production configs include absolute paths outside the repository tree, so a
test that runs a production-style document against repository-local copies
must redirect those includes, ideally without modifying the
files meant to be installed as is.

Add a jw.include-map key to the top-level document: an ordered list
of single-key mappings from LHS pattern to RHS pattern or list of RHS
patterns. Before resolution, the file part of each include spec is
qualified against the including file's directory and matched against the
LHS patterns in table order; the first match rewrites the spec to every RHS
pattern of that entry. Relative LHS and RHS values are interpreted against
the directory of the document that declares the map, so matching runs on
canonical paths and same-named includes from different directories stay
distinguishable. The optional marker and the target path are decomposed
before the rewrite: every rewritten source inherits the spec's optionality,
and the target path applies to the merged result.

- _parse_include_map(): parse and validate the table; only '*' is supported
  in an LHS, a RHS may not have more '*' than its LHS, and RHS values
  expand $(VAR) and ${VAR} from the environment
- _canonicalize_path(): join a relative path with a base directory and
  normalize, without disk access
- _compile_lhs_pattern(): compile a canonical LHS into an anchored regex
  whose '*' groups match runs that are not '/'
- _apply_include_map(): match the first entry and fill the LHS captures
  into every RHS pattern; log the rewrite at DEBUG
- _load_yaml(): parse the map once in the top-level document, reject it in
  included documents, thread it through the include tree

Signed-off-by: Jan Lindemann <jan@janware.com>
Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.6.0
2026-11-20 22:39:55 +01:00
911c78ff99
load_yaml: Expand variables in top-level include specs
Test wrappers that mimic production invocations redirect the includes of
production documents to tree-local copies; the target location depends on
where the tree is checked out, so it would be nice if the wrapper could
take TOPDIR from the environment instead of hardcoding it.

Allow the file part of a top-level include spec to reference environment
variables as $(VAR) or ${VAR}. _load_yaml() receives a depth counter,
zero at the top level and one per include level, and threads it to
_normalize_include_specs() and _parse_include_spec(); the file part passes
through _expand_include_vars() only at depth zero, after the optional
marker and the target path have been split off. Specs in included documents
keep their literal behaviour. An undefined variable raises ValueError,
naming the reference and the file it came from.

Signed-off-by: Jan Lindemann <jan@janware.com>
Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.6.0
2026-11-20 22:39:55 +01:00
3d4e49f047
Release 1.0.0-63
All checks were successful
CI / Packaging - OpenSUSE Tumbleweed (push) Successful in 6m2s
CI / Packaging - Kali Linux (push) Successful in 4m57s
CI / Packaging test (push) Successful in 0s
2026-11-19 01:16:50 +01:00
c983a77ef0
[PR jw/#5] enum_helper.py: Import the name conversion helpers from jw-pkg
All checks were successful
CI / Packaging - Kali Linux (push) Successful in 5m3s
CI / Packaging - OpenSUSE Tumbleweed (push) Successful in 5m28s
CI / Packaging test (push) Successful in 0s
Merge pull request "enum_helper.py: Import the name conversion helpers from jw-pkg"

Upstream-repo: ssh://git@code.janware.com/janware/jw-python
Source-branch: jan/fix/20261118-enum-helper-py-import-the-name-conversion-helpers-from-jw-pkg
Target-branch: master
Reviewed-on: #5
2026-11-18 19:47:04 +01:00
d5c64af683
enum_helper.py: Import the name conversion helpers from jw-pkg
All checks were successful
CI / Packaging - Kali Linux (pull_request) Successful in 4m53s
CI / Packaging - OpenSUSE Tumbleweed (pull_request) Successful in 5m33s
CI / Packaging test (pull_request) Successful in 0s
kebab_to_pascal() and pascal_to_kebab() are needed in jw-pkg, for the
resolution of filter names and, later, the dynamic loading of file
contexts. jw-python depends on jw-pkg, so jw-pkg's util.py is their
canonical home.

This commit imports them from jw.pkg.lib.util and re-exports them, so the
existing importers keep working.

Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.2
Signed-off-by: Jan Lindemann <jan@janware.com>
2026-11-18 19:25:41 +01:00
f965705479
Release 1.0.0-62
All checks were successful
CI / Packaging - Kali Linux (push) Successful in 5m17s
CI / Packaging - OpenSUSE Tumbleweed (push) Successful in 5m32s
CI / Packaging test (push) Successful in 0s
2026-11-14 00:12:52 +00:00
629a47861a
[PR jw/#4] Sync the tree with current mypy and isort
All checks were successful
CI / Packaging - Kali Linux (push) Successful in 5m25s
CI / Packaging - OpenSUSE Tumbleweed (push) Successful in 5m10s
CI / Packaging test (push) Successful in 0s
Merge pull request "Sync the tree with current mypy and isort"

Upstream-repo: ssh://git@code.janware.com/janware/jw-python
Source-branch: jan/fix/20261113-sync-the-tree-with-current-mypy-and-isort
Target-branch: master
Reviewed-on: #4
2026-11-13 15:20:33 +01:00
71037e631a
style: Sync import formatting with current isort
All checks were successful
CI / Packaging - Kali Linux (pull_request) Successful in 5m26s
CI / Packaging - OpenSUSE Tumbleweed (pull_request) Successful in 5m27s
CI / Packaging test (pull_request) Successful in 0s
The current isort formats parenthesized import lists with a trailing comma
and wraps long imports differently than when the files were last formatted,
so make format rewrites them on every run even though nothing is wrong with
the code.

Apply make format to the two drifted import statements so the tree matches
the formatter's output and make format becomes a no-op:

- src/python/jw/util/log.py: trailing comma in the jw.pkg.lib.log import
  list
- src/python/jwutils/db/schema/CompositeForeignKey.py: wrap the
  CompositeForeignKey import in parentheses

Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.2
Signed-off-by: Jan Lindemann <jan@janware.com>
2026-11-13 15:09:33 +01:00
c679505053
Options.__init__(): Annotate __allowed_keys as Any
mypy 2.4.0 infers the attribute from the None assignment in __init__() and
then flags the right operand of the and check in __parse__() as unreachable
code, failing make check.

The attribute is only ever assigned None, so annotate it as Any and keep
the runtime behaviour unchanged.

Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.2
Signed-off-by: Jan Lindemann <jan@janware.com>
2026-11-13 15:09:33 +01:00
9 changed files with 700 additions and 34 deletions

2
HASH
View file

@ -2,4 +2,4 @@ suse-tumbleweed/i586: 355d0bb2086dcacbb4afdf822260ad40
suse-tumbleweed/x86_64: 82d9dcbdb1012909116116128366a0cc suse-tumbleweed/x86_64: 82d9dcbdb1012909116116128366a0cc
centos-7/x86_64: e8ea9ef53b556c831438870b4d08d174 centos-7/x86_64: e8ea9ef53b556c831438870b4d08d174
ubuntu-18.04/amd64: a7b0581e118c41a056b0dda0c61bf293 ubuntu-18.04/amd64: a7b0581e118c41a056b0dda0c61bf293
kali-rolling/amd64: 82d9dcbdb1012909116116128366a0cc kali-rolling/amd64: e8897a7e93fd57f38862f315f9a37d08

View file

@ -1,5 +0,0 @@
suse-tumbleweed/i586: 1.0.0-1
suse-tumbleweed/x86_64: 1.0.0-61
centos-7/x86_64: 1.0.0-4
ubuntu-18.04/amd64: 1.0.0-8
kali-rolling/amd64: 1.0.0-61

View file

@ -1 +1 @@
1.0.0-61-dev 1.0.0-64-dev

View file

@ -126,7 +126,7 @@ class Options: # export
true_val: Any = True true_val: Any = True
) -> None: ) -> None:
self.__true_val = true_val self.__true_val = true_val
self.__allowed_keys = None self.__allowed_keys: Any = None
self.__delimiter = delimiter self.__delimiter = delimiter
self.__data = ( self.__data = (
self.__class__.OrderedData() self.__class__.OrderedData()

View file

@ -1,22 +1,20 @@
from __future__ import annotations from __future__ import annotations
import re
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from jw.pkg.lib.util import kebab_to_pascal, pascal_to_kebab
if TYPE_CHECKING: if TYPE_CHECKING:
from enum import Enum from enum import Enum
from typing import TypeVar from typing import TypeVar
EnumType = TypeVar("EnumType", bound = Enum) EnumType = TypeVar("EnumType", bound = Enum)
def kebab_to_pascal(value: str) -> str: __all__ = [
return "".join(part.capitalize() for part in value.split("-")) "kebab_to_pascal",
"pascal_to_kebab",
def pascal_to_kebab(value: str) -> str: "enum_from_kebab",
# Handles normal CamelCase / PascalCase, including many acronym cases "enum_to_kebab",
s1 = re.sub(r"(.)([A-Z][a-z]+)", r"\1-\2", value) ]
s2 = re.sub(r"([a-z0-9])([A-Z])", r"\1-\2", s1)
return s2.lower()
def enum_from_kebab(enum_cls: type[EnumType], value: str) -> EnumType: def enum_from_kebab(enum_cls: type[EnumType], value: str) -> EnumType:
return enum_cls[kebab_to_pascal(value)] return enum_cls[kebab_to_pascal(value)]

View file

@ -12,7 +12,32 @@ supports three extensions:
``[...]``); all matches are included in lexical order, and a ``[...]``); all matches are included in lexical order, and a
non-optional glob that matches no files raises ValueError. A spec non-optional glob that matches no files raises ValueError. A spec
that starts with a glob character such as ``*`` or ``[`` must be that starts with a glob character such as ``*`` or ``[`` must be
quoted in YAML. quoted in YAML. In the top-level document, the file part of an
include spec may reference environment variables as ``$(VAR)`` or
``${VAR}``; an undefined variable raises ValueError. Specs in
included documents are never expanded.
- ``jw.include-map`` — a table that rewrites include specs to other
paths, for testing against tree-local copies of production
configs. The value is a list of single-key mappings; the key is
the LHS pattern, the value a RHS pattern or a list of RHS
patterns. Before resolution, the file part of each include spec
is qualified against the including file's directory and matched
against the LHS patterns in table order; the first match rewrites
the spec to every RHS pattern of that entry. ``*`` matches any
run of characters that is not ``/``; the i-th ``*`` of the LHS
captures into the i-th ``*`` of the RHS, so a glob spec rewrites
to a glob RHS. A relative LHS or RHS is interpreted relative to
the directory of the document that declares the map, and RHS
values may reference environment variables as ``$(VAR)`` or
``${VAR}``. Only the top-level document may declare
``jw.include-map``.
- ``jw.include-map-no-absolute`` — when true, an absolute include
spec that matched no map entry raises ValueError, naming the
spec and the file, guarding a test against silently reading a
real production path. An identity entry (LHS and RHS the
same) whitelists a path that may be read. The key defaults to
false and applies to the whole include tree; only the
top-level document may set it.
- ``jw.link`` — replaces a node with the value found at a dot-separated - ``jw.link`` — replaces a node with the value found at a dot-separated
target path. A prefix before the first ``|`` names the resulting target path. A prefix before the first ``|`` names the resulting
key instead of replacing the node in place. key instead of replacing the node in place.
@ -30,6 +55,7 @@ themselves.
from __future__ import annotations from __future__ import annotations
import os
import re import re
from copy import deepcopy from copy import deepcopy
@ -38,10 +64,14 @@ from typing import Any, TypeAlias, cast
import yaml # type: ignore[import-untyped] import yaml # type: ignore[import-untyped]
from jw.util.log import DEBUG, log_m
# -- Constants ------------------------------------------------------------------ # -- Constants ------------------------------------------------------------------
IncludeSpec: TypeAlias = tuple[bool, Path, tuple[str, ...]] IncludeSpec: TypeAlias = tuple[bool, Path, tuple[str, ...]]
Includes: TypeAlias = list[IncludeSpec] Includes: TypeAlias = list[IncludeSpec]
IncludeMapEntry: TypeAlias = tuple[re.Pattern[str], tuple[str, ...]]
IncludeMap: TypeAlias = tuple[list[IncludeMapEntry], Path]
_LINK_NAME_RE = re.compile(r'^([a-zA-Z0-9_-]+)\|') _LINK_NAME_RE = re.compile(r'^([a-zA-Z0-9_-]+)\|')
_INCLUDE_PATH_RE = re.compile(r'^([a-zA-Z0-9_.-]+)\|') _INCLUDE_PATH_RE = re.compile(r'^([a-zA-Z0-9_.-]+)\|')
@ -137,6 +167,44 @@ def _resolve_path(
# -- Include helpers ------------------------------------------------------------ # -- Include helpers ------------------------------------------------------------
_VAR_RE = re.compile(r'\$\(([A-Za-z_][A-Za-z0-9_]*)\)|\$\{([A-Za-z_][A-Za-z0-9_]*)\}')
def _expand_include_vars(value: str, where: str) -> str:
"""Expand $(VAR) and ${VAR} references in *value* from the environment.
Raises ValueError naming the reference and *where* when a
variable is not set.
"""
def __sub(m: re.Match[str]) -> str:
name = m.group(1) if m.group(1) is not None else m.group(2)
if name not in os.environ:
raise ValueError(f'Undefined variable {m.group(0)} in {where}')
return os.environ[name]
return _VAR_RE.sub(__sub, value)
def _canonicalize_path(path_str: str, base: Path) -> str:
"""Return *path_str* as a normalized absolute path string.
Relative paths are joined with *base* first. Pure path
arithmetic: no disk access, glob characters pass through
untouched.
"""
if path_str.startswith('/'):
return os.path.normpath(path_str)
return os.path.normpath(str(base / path_str))
def _compile_lhs_pattern(lhs: str) -> re.Pattern[str]:
"""Compile a canonical LHS pattern into an anchored regex.
Literal pieces are escaped; each '*' becomes a capture group
that matches any run of characters that is not '/'.
"""
pieces = lhs.split('*')
body = '([^/]*)'.join(re.escape(piece) for piece in pieces)
return re.compile('^' + body + '$')
def _glob_include(file_spec: str, parent: Path) -> list[Path]: def _glob_include(file_spec: str, parent: Path) -> list[Path]:
"""Resolve *file_spec* against *parent* and expand glob characters. """Resolve *file_spec* against *parent* and expand glob characters.
@ -156,12 +224,126 @@ def _glob_include(file_spec: str, parent: Path) -> list[Path]:
path = Path(file_spec) path = Path(file_spec)
return [path if path.is_absolute() else parent / path] return [path if path.is_absolute() else parent / path]
def _parse_include_spec(spec: str, parent: Path) -> list[IncludeSpec]: def _parse_include_map(value: Any, base: Path, where: str) -> IncludeMap:
"""Parse and validate a jw.include-map value.
The value is a list of single-key mappings: the key is the LHS
pattern, the value a RHS pattern or a list of RHS patterns.
Only '*' is supported as a glob character in an LHS, and a RHS
may not contain more '*' than its LHS. Relative LHS and RHS
paths are interpreted relative to *base*, the directory of the
document that declares the map; $(VAR) and ${VAR} references in
RHS values are expanded from the environment. Returns the
compiled entries together with *base*.
"""
if value is None:
return ([], base)
if not isinstance(value, list):
raise TypeError(f'jw.include-map must be a list, got {type(value).__name__}')
entries: list[IncludeMapEntry] = []
for i, item in enumerate(value):
if not isinstance(item, dict) or len(item) != 1:
raise ValueError(
f'jw.include-map entry {i}: expected a single-key '
f'mapping, got {item!r}'
)
lhs, rhs = next(iter(item.items()))
if not isinstance(lhs, str):
raise ValueError(
f'jw.include-map entry {i}: LHS must be a string, '
f'got {type(lhs).__name__}'
)
if not lhs:
raise ValueError(f'jw.include-map entry {i}: empty LHS')
if lhs.startswith('-') or '|' in lhs:
raise ValueError(
f'jw.include-map entry {i}: LHS must be a plain path '
f'pattern without optional marker or target path: '
f'{lhs!r}'
)
if set(lhs) & (_GLOB_CHARS - frozenset('*')):
raise ValueError(
f'jw.include-map entry {i}: only "*" is supported as '
f'a glob character in the LHS: {lhs!r}'
)
if isinstance(rhs, str):
if not rhs:
raise ValueError(f'jw.include-map entry {i}: empty RHS')
rhs_list: list[str] = [rhs]
elif isinstance(rhs, list):
rhs_list = []
for entry in rhs:
if not isinstance(entry, str) or not entry:
raise ValueError(
f'jw.include-map entry {i}: RHS list items must '
f'be non-empty strings, got {entry!r}'
)
rhs_list.append(entry)
if not rhs_list:
raise ValueError(f'jw.include-map entry {i}: empty RHS list')
else:
raise ValueError(
f'jw.include-map entry {i}: RHS must be a string or a '
f'list of strings, got {type(rhs).__name__}'
)
for entry in rhs_list:
if entry.count('*') > lhs.count('*'):
raise ValueError(
f'jw.include-map entry {i}: RHS has more "*" than '
f'the LHS: {lhs!r} -> {entry!r}'
)
expanded = tuple(
_expand_include_vars(entry, f'{where} (jw.include-map entry {i})')
for entry in rhs_list
)
pattern = _compile_lhs_pattern(_canonicalize_path(lhs, base))
entries.append((pattern, expanded))
return (entries, base)
def _apply_include_map(spec: str, include_map: IncludeMap) -> list[str] | None:
"""Rewrite the canonical *spec* via the first matching map entry.
The captures of the LHS match fill the '*' slots of every RHS
pattern; a relative result is resolved against the map's base
directory. Returns the rewritten canonical specs, or None when
no entry matches.
"""
entries, base = include_map
for pattern, rhs_list in entries:
m = pattern.fullmatch(spec)
if m is None:
continue
captures = m.groups()
rewrites: list[str] = []
for rhs in rhs_list:
pieces = rhs.split('*')
ret = pieces[0]
for piece, capture in zip(pieces[1:], captures):
ret += capture + piece
rewrites.append(_canonicalize_path(ret, base))
log_m(DEBUG, f'include-map: {spec} -> {rewrites}')
return rewrites
return None
def _parse_include_spec(
spec: str,
path: Path,
include_map: IncludeMap,
expand_vars: bool,
no_absolute: bool,
) -> list[IncludeSpec]:
"""Parse a jw.include spec into one or more IncludeSpec entries. """Parse a jw.include spec into one or more IncludeSpec entries.
The file part may use glob characters; every match becomes a The file part may use glob characters; every match becomes a
separate entry. A non-optional glob that matches no files raises separate entry. A non-optional glob that matches no files raises
ValueError. ValueError. The file part is qualified against the including
file's directory and rewritten by the first matching entry of
*include_map* before resolution; the rewritten specs are resolved
and glob-expanded by the normal pipeline. When *expand_vars* is
true (the top-level document only), $(VAR) and ${VAR} references
in the file part are expanded from the environment first. When
*no_absolute* is true, an absolute spec that matched no entry
raises ValueError instead of being read from disk.
""" """
if not spec: if not spec:
raise ValueError('Empty include spec') raise ValueError('Empty include spec')
@ -177,12 +359,31 @@ def _parse_include_spec(spec: str, parent: Path) -> list[IncludeSpec]:
if m: if m:
target_path = tuple(m.group(1).split('.')) target_path = tuple(m.group(1).split('.'))
spec = spec[len(m.group(1)) + 1:] spec = spec[len(m.group(1)) + 1:]
paths = _glob_include(spec, parent) if expand_vars:
spec = _expand_include_vars(spec, str(path))
qualified = _canonicalize_path(spec, path.parent)
rewrites = _apply_include_map(qualified, include_map)
if rewrites is None:
if no_absolute and spec.startswith('/'):
raise ValueError(
f'jw.include-map-no-absolute: absolute include '
f'{spec!r} in {path} is not covered by the include map'
)
rewrites = [qualified]
paths: list[Path] = []
for rewrite in rewrites:
paths.extend(_glob_include(rewrite, path.parent))
if not paths and not optional: if not paths and not optional:
raise ValueError(f'Include glob {spec!r} matches no files') raise ValueError(f'Include glob {spec!r} matches no files in {path}')
return [(optional, path, target_path) for path in paths] return [(optional, inc, target_path) for inc in paths]
def _normalize_include_specs(specs: Any, parent: Path) -> Includes: def _normalize_include_specs(
specs: Any,
path: Path,
include_map: IncludeMap,
expand_vars: bool,
no_absolute: bool,
) -> Includes:
if specs is None: if specs is None:
return [] return []
if isinstance(specs, str): if isinstance(specs, str):
@ -193,7 +394,9 @@ def _normalize_include_specs(specs: Any, parent: Path) -> Includes:
for spec in specs: for spec in specs:
if not isinstance(spec, str): if not isinstance(spec, str):
raise TypeError(f'Unsupported include entry: {spec!r}') raise TypeError(f'Unsupported include entry: {spec!r}')
ret.extend(_parse_include_spec(spec, parent)) ret.extend(
_parse_include_spec(spec, path, include_map, expand_vars, no_absolute)
)
return ret return ret
# -- Include target-path merging ----------------------------------------------- # -- Include target-path merging -----------------------------------------------
@ -403,7 +606,14 @@ def _expand_links(root: dict[str, Any]) -> dict[str, Any]:
# -- Top-level entry points ----------------------------------------------------- # -- Top-level entry points -----------------------------------------------------
def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, Any]: def _load_yaml(
path: str | Path,
optional: bool,
seen: set[Path],
depth: int,
include_map: IncludeMap | None,
no_absolute: bool,
) -> dict[str, Any]:
path = Path(path).resolve() path = Path(path).resolve()
if path in seen: if path in seen:
raise ValueError(f'Cyclic YAML include detected: {path}') raise ValueError(f'Cyclic YAML include detected: {path}')
@ -426,12 +636,36 @@ def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, A
if optional: if optional:
return {} return {}
raise raise
includes = _normalize_include_specs(ret.get('jw.include', []), path.parent) if include_map is None:
no_absolute = bool(ret.pop('jw.include-map-no-absolute', False))
include_map = _parse_include_map(
ret.pop('jw.include-map', None), path.parent, str(path)
)
elif 'jw.include-map' in ret \
or 'jw.include-map-no-absolute' in ret:
raise ValueError(
f'jw.include-map and jw.include-map-no-absolute are '
f'only allowed in the top-level document: {path}'
)
includes = _normalize_include_specs(
ret.get('jw.include', []),
path,
include_map = include_map,
expand_vars = depth == 0,
no_absolute = no_absolute
)
ret.pop('jw.include', None) ret.pop('jw.include', None)
included_all: dict[str, Any] = {} included_all: dict[str, Any] = {}
for include in includes: for include in includes:
opt, inc_path, target = include opt, inc_path, target = include
included_next = _load_yaml(inc_path, optional = opt, seen = seen) included_next = _load_yaml(
inc_path,
optional = opt,
seen = seen,
depth = depth + 1,
include_map = include_map,
no_absolute = no_absolute
)
if not included_next: if not included_next:
# An empty document contributes nothing; in particular # An empty document contributes nothing; in particular
# it must not create the target key of a path-addressed # it must not create the target key of a path-addressed
@ -448,7 +682,11 @@ def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, A
def load_yaml(path: str | Path, optional: bool = False) -> dict[str, Any]: # export def load_yaml(path: str | Path, optional: bool = False) -> dict[str, Any]: # export
seen: set[Path] = set() seen: set[Path] = set()
return _expand_links(_load_yaml(path, optional, seen)) return _expand_links(
_load_yaml(
path, optional, seen, depth = 0, include_map = None, no_absolute = False
)
)
if __name__ == '__main__': if __name__ == '__main__':
import json import json

View file

@ -25,7 +25,7 @@ from jw.pkg.lib.log import (
set_flags, set_flags,
set_level, set_level,
set_module_name_length, set_module_name_length,
throw throw,
) )
slog = log slog = log

View file

@ -1,6 +1,7 @@
# ruff: noqa: E501 # ruff: noqa: E501
from jw.util.db.schema.CompositeForeignKey import \ from jw.util.db.schema.CompositeForeignKey import (
CompositeForeignKey as CompositeForeignKey CompositeForeignKey as CompositeForeignKey,
)
__all__ = [ __all__ = [
"CompositeForeignKey", "CompositeForeignKey",

View file

@ -1153,6 +1153,440 @@ class TestIncludeGlobbing:
with pytest.raises(ValueError, match = 'Cyclic YAML include'): with pytest.raises(ValueError, match = 'Cyclic YAML include'):
load_yaml(pathlib.Path(base) / 'main.yaml') load_yaml(pathlib.Path(base) / 'main.yaml')
class TestIncludeVarExpansion:
"""Tests for $(VAR) and ${VAR} expansion in include specs."""
def test_expand_braced_var(
self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch
) -> None:
"""${VAR} in a top-level include spec is expanded."""
base = temp_dir([('conf/a.yaml', 'from_a: 1\n')])
monkeypatch.setenv('LOAD_YAML_TEST_TOP', base)
main = pathlib.Path(base) / 'main.yaml'
main.write_text('jw.include: ${LOAD_YAML_TEST_TOP}/conf/a.yaml\n')
data = load_yaml(main)
assert data['from_a'] == 1
def test_expand_paren_var(
self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch
) -> None:
"""$(VAR) in a top-level include spec is expanded."""
base = temp_dir([('conf/a.yaml', 'from_a: 1\n')])
monkeypatch.setenv('LOAD_YAML_TEST_TOP', base)
main = pathlib.Path(base) / 'main.yaml'
main.write_text('jw.include: $(LOAD_YAML_TEST_TOP)/conf/a.yaml\n')
data = load_yaml(main)
assert data['from_a'] == 1
def test_expand_var_with_glob(
self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Expansion and glob expansion compose."""
base = temp_dir(
[
('conf/a.yaml', 'from_a: 1\n'),
('conf/b.yaml', 'from_b: 2\n'),
]
)
monkeypatch.setenv('LOAD_YAML_TEST_TOP', base)
main = pathlib.Path(base) / 'main.yaml'
main.write_text('jw.include: ${LOAD_YAML_TEST_TOP}/conf/*.yaml\n')
data = load_yaml(main)
assert data['from_a'] == 1
assert data['from_b'] == 2
def test_undefined_var_raises(self, temp_dir: _TempDir) -> None:
"""An undefined variable in a top-level spec raises."""
base = temp_dir([('main.yaml', 'jw.include: ${LOAD_YAML_TEST_NOPE}/x.yaml\n')])
with pytest.raises(ValueError, match = 'Undefined variable'):
load_yaml(pathlib.Path(base) / 'main.yaml')
def test_nested_spec_not_expanded(self, temp_dir: _TempDir) -> None:
"""Specs in included documents are never expanded."""
base = temp_dir(
[
('main.yaml', 'jw.include: nested/real.yaml\n'),
('nested/real.yaml', 'jw.include: ${HOME}/x.yaml\n'),
('nested/${HOME}/x.yaml', 'literal: yes\n'),
]
)
data = load_yaml(pathlib.Path(base) / 'main.yaml')
assert data['literal'] is True
class TestIncludeMap:
"""Tests for the jw.include-map include spec rewrite table."""
def test_exact_rewrite(self, temp_dir: _TempDir) -> None:
"""An exact LHS rewrites the spec to the RHS."""
base = temp_dir(
[
(
'wrapper.yaml',
'jw.include-map:\n'
' - /prod/etc/app.yaml: test/app.yaml\n'
'jw.include: /prod/etc/app.yaml\n'
),
('test/app.yaml', 'from_test: 1\n'),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['from_test'] == 1
def test_glob_rewrite(self, temp_dir: _TempDir) -> None:
"""A glob LHS captures into a glob RHS."""
base = temp_dir(
[
('prod.d/one.yaml', 'one: prod\n'),
('prod.d/two.yaml', 'two: prod\n'),
('test.d/one.yaml', 'one: test\n'),
('test.d/two.yaml', 'two: test\n'),
(
'wrapper.yaml',
'jw.include-map:\n'
' - prod.d/*.yaml: test.d/*.yaml\n'
'jw.include: prod.d/*.yaml\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['one'] == 'test'
assert data['two'] == 'test'
def test_rhs_list(self, temp_dir: _TempDir) -> None:
"""A list RHS expands to multiple sources in list order."""
base = temp_dir(
[
('t1/a.yaml', 'one: 1\nshared: t1a\n'),
('t1/b.yaml', 'shared: t1b\ntwo: 2\n'),
('t2/a.yaml', 'shared: t2a\nthree: 3\n'),
(
'wrapper.yaml',
'jw.include-map:\n'
' - prod.d/*.yaml: [t1/*.yaml, t2/*.yaml]\n'
'jw.include: prod.d/*.yaml\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['one'] == 1
assert data['two'] == 2
assert data['three'] == 3
# Sources merge in RHS list order, later files win
assert data['shared'] == 't2a'
def test_rewrite_before_disk_lookup(self, temp_dir: _TempDir) -> None:
"""The LHS pattern need not match anything on disk."""
base = temp_dir(
[
('test.d/one.yaml', 'one: 1\n'),
(
'wrapper.yaml',
'jw.include-map:\n'
' - prod.d/*.yaml: test.d/*.yaml\n'
'jw.include: prod.d/one.yaml\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['one'] == 1
def test_first_match_wins(self, temp_dir: _TempDir) -> None:
"""The first matching entry wins; later entries are ignored."""
base = temp_dir(
[
('first.yaml', 'source: first\n'),
('second.yaml', 'source: second\n'),
(
'wrapper.yaml',
'jw.include-map:\n'
' - /prod/etc/app.yaml: first.yaml\n'
' - /prod/etc/app.yaml: second.yaml\n'
'jw.include: /prod/etc/app.yaml\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['source'] == 'first'
def test_relative_lhs_collision(self, temp_dir: _TempDir) -> None:
"""Same-named relative includes are disambiguated by directory."""
base = temp_dir(
[
('prod/a/doc.yaml', 'jw.include: x.yaml\n'),
('prod/b/doc.yaml', 'jw.include: x.yaml\n'),
('ax.yaml', 'from_ax: 1\n'),
('bx.yaml', 'from_bx: 2\n'),
(
'wrapper.yaml',
'jw.include-map:\n'
' - prod/a/x.yaml: ax.yaml\n'
' - prod/b/x.yaml: bx.yaml\n'
'jw.include:\n'
' - prod/a/doc.yaml\n'
' - prod/b/doc.yaml\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['from_ax'] == 1
assert data['from_bx'] == 2
def test_relative_rhs_against_wrapper(self, temp_dir: _TempDir) -> None:
"""A relative RHS resolves against the wrapper's directory."""
base = temp_dir(
[
('prod/app.yaml', 'jw.include: deep.yaml\n'),
('copies/deep.yaml', 'deep: ok\n'),
(
'wrapper.yaml',
'jw.include-map:\n'
' - prod/deep.yaml: copies/deep.yaml\n'
'jw.include: prod/app.yaml\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['deep'] == 'ok'
def test_absolute_lhs(self, temp_dir: _TempDir) -> None:
"""Absolute LHS patterns match production-style includes."""
base = temp_dir(
[
('prod.yaml', 'jw.include: /etc/jw/app/*.yaml\n'),
('test/app.yaml', 'from_test: 1\n'),
(
'wrapper.yaml',
'jw.include-map:\n'
' - /etc/jw/app/*.yaml: test/app.yaml\n'
'jw.include: prod.yaml\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['from_test'] == 1
def test_optional_flag_inherited(self, temp_dir: _TempDir) -> None:
"""Rewritten sources inherit the original spec's optionality."""
base = temp_dir(
[
(
'wrapper.yaml',
'jw.include-map:\n'
' - prod/*.yaml: nowhere/*.yaml\n'
'jw.include: -prod/missing.yaml\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data == {}
def test_non_optional_rewrite_missing_raises(self, temp_dir: _TempDir) -> None:
"""A rewritten plain path that does not exist raises."""
base = temp_dir(
[
(
'wrapper.yaml',
'jw.include-map:\n'
' - prod/*.yaml: nowhere/*.yaml\n'
'jw.include: prod/missing.yaml\n'
),
]
)
with pytest.raises(FileNotFoundError):
load_yaml(pathlib.Path(base) / 'wrapper.yaml')
def test_target_path_preserved(self, temp_dir: _TempDir) -> None:
"""The target path prefix survives the rewrite."""
base = temp_dir(
[
('t/one.yaml', 'a: 1\n'),
('t/two.yaml', 'b: 2\n'),
(
'wrapper.yaml',
'jw.include-map:\n'
' - prod/*.yaml: t/*.yaml\n'
'jw.include: section|prod/*.yaml\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['section'] == {'a': 1, 'b': 2}
def test_nested_map_raises(self, temp_dir: _TempDir) -> None:
"""jw.include-map in a non-top-level document raises."""
base = temp_dir(
[
('inner.yaml', 'jw.include-map:\n - a.yaml: b.yaml\n'),
('wrapper.yaml', 'jw.include: inner.yaml\n'),
]
)
with pytest.raises(ValueError, match = 'top-level'):
load_yaml(pathlib.Path(base) / 'wrapper.yaml')
def test_empty_map_is_noop(self, temp_dir: _TempDir) -> None:
"""An empty map leaves all includes untouched."""
base = temp_dir(
[
('app.yaml', 'ok: 1\n'),
('wrapper.yaml', 'jw.include-map: []\n'
'jw.include: app.yaml\n'),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['ok'] == 1
def test_map_not_a_list_raises(self, temp_dir: _TempDir) -> None:
"""A non-list jw.include-map value raises."""
base = temp_dir([('wrapper.yaml', 'jw.include-map: {}\n')])
with pytest.raises(TypeError, match = 'must be a list'):
load_yaml(pathlib.Path(base) / 'wrapper.yaml')
def test_multi_key_entry_raises(self, temp_dir: _TempDir) -> None:
"""A map entry with two keys raises."""
base = temp_dir(
[
(
'wrapper.yaml',
'jw.include-map:\n'
' - a.yaml: b.yaml\n'
' c.yaml: d.yaml\n'
),
]
)
with pytest.raises(ValueError, match = 'single-key'):
load_yaml(pathlib.Path(base) / 'wrapper.yaml')
def test_rhs_star_overflow_raises(self, temp_dir: _TempDir) -> None:
"""A RHS with more stars than the LHS raises."""
base = temp_dir(
[
('wrapper.yaml', 'jw.include-map:\n - a/*.yaml: b/*/*.yaml\n'),
]
)
with pytest.raises(ValueError, match = r'more "\*"'):
load_yaml(pathlib.Path(base) / 'wrapper.yaml')
def test_lhs_question_mark_raises(self, temp_dir: _TempDir) -> None:
"""A '?' in the LHS raises; only '*' is supported."""
base = temp_dir([('wrapper.yaml', 'jw.include-map:\n - a/?.yaml: b.yaml\n')])
with pytest.raises(ValueError, match = r'only "\*"'):
load_yaml(pathlib.Path(base) / 'wrapper.yaml')
def test_var_in_rhs(
self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch
) -> None:
"""RHS values expand environment variables."""
base = temp_dir([('app.yaml', 'ok: 1\n')])
monkeypatch.setenv('LOAD_YAML_TEST_TOP', base)
main = pathlib.Path(base) / 'wrapper.yaml'
main.write_text(
'jw.include-map:\n'
' - /etc/app.yaml: ${LOAD_YAML_TEST_TOP}/app.yaml\n'
'jw.include: /etc/app.yaml\n'
)
data = load_yaml(main)
assert data['ok'] == 1
class TestIncludeMapNoAbsolute:
"""Tests for the jw.include-map-no-absolute guard."""
def test_absolute_uncovered_raises(self, temp_dir: _TempDir) -> None:
"""An absolute spec with no matching entry raises."""
base = temp_dir(
[
(
'wrapper.yaml',
'jw.include-map: []\n'
'jw.include-map-no-absolute: true\n'
'jw.include: /etc/app.yaml\n'
),
]
)
with pytest.raises(ValueError, match = 'not covered by the include map'):
load_yaml(pathlib.Path(base) / 'wrapper.yaml')
def test_absolute_covered_ok(self, temp_dir: _TempDir) -> None:
"""An absolute spec covered by the map loads."""
base = temp_dir(
[
('app.yaml', 'ok: 1\n'),
(
'wrapper.yaml',
'jw.include-map:\n'
' - /etc/app.yaml: app.yaml\n'
'jw.include-map-no-absolute: true\n'
'jw.include: /etc/app.yaml\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['ok'] == 1
def test_nested_absolute_uncovered_raises(self, temp_dir: _TempDir) -> None:
"""The guard covers nested includes, not just the wrapper's own."""
base = temp_dir(
[
('prod.yaml', 'jw.include: /etc/app.yaml\n'),
(
'wrapper.yaml',
'jw.include-map: []\n'
'jw.include-map-no-absolute: true\n'
'jw.include: prod.yaml\n'
),
]
)
with pytest.raises(ValueError, match = 'not covered by the include map'):
load_yaml(pathlib.Path(base) / 'wrapper.yaml')
def test_relative_specs_pass(self, temp_dir: _TempDir) -> None:
"""Relative specs are unaffected by the guard."""
base = temp_dir(
[
('app.yaml', 'ok: 1\n'),
(
'wrapper.yaml',
'jw.include-map: []\n'
'jw.include-map-no-absolute: true\n'
'jw.include: app.yaml\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'wrapper.yaml')
assert data['ok'] == 1
def test_identity_entry_whitelists(self, temp_dir: _TempDir) -> None:
"""An identity entry whitelists an absolute path."""
base = temp_dir([('real.yaml', 'ok: 1\n')])
main = pathlib.Path(base) / 'wrapper.yaml'
main.write_text(
'jw.include-map:\n'
f' - {base}/real.yaml: {base}/real.yaml\n'
'jw.include-map-no-absolute: true\n'
f'jw.include: {base}/real.yaml\n'
)
data = load_yaml(main)
assert data['ok'] == 1
def test_default_is_false(self, temp_dir: _TempDir) -> None:
"""Without the flag, an uncovered absolute spec is read from disk."""
base = temp_dir(
[('wrapper.yaml', 'jw.include-map: []\n'
'jw.include: /etc/app.yaml\n')]
)
with pytest.raises(FileNotFoundError):
load_yaml(pathlib.Path(base) / 'wrapper.yaml')
def test_nested_flag_raises(self, temp_dir: _TempDir) -> None:
"""The flag in a non-top-level document raises."""
base = temp_dir(
[
('inner.yaml', 'jw.include-map-no-absolute: true\n'),
('wrapper.yaml', 'jw.include: inner.yaml\n'),
]
)
with pytest.raises(ValueError, match = 'top-level'):
load_yaml(pathlib.Path(base) / 'wrapper.yaml')
# -- jw.include with target path ------------------------------------------------ # -- jw.include with target path ------------------------------------------------
class TestPathResolution: class TestPathResolution: