Compare commits

..
9 changed files with 34 additions and 700 deletions

2
HASH
View file

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

5
RELEASES Normal file
View file

@ -0,0 +1,5 @@
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-64-dev
1.0.0-61-dev

View file

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

View file

@ -1,20 +1,22 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import re
from jw.pkg.lib.util import kebab_to_pascal, pascal_to_kebab
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from enum import Enum
from typing import TypeVar
EnumType = TypeVar("EnumType", bound = Enum)
__all__ = [
"kebab_to_pascal",
"pascal_to_kebab",
"enum_from_kebab",
"enum_to_kebab",
]
def kebab_to_pascal(value: str) -> str:
return "".join(part.capitalize() for part in value.split("-"))
def pascal_to_kebab(value: str) -> str:
# Handles normal CamelCase / PascalCase, including many acronym cases
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:
return enum_cls[kebab_to_pascal(value)]

View file

@ -12,32 +12,7 @@ supports three extensions:
``[...]``); all matches are included in lexical order, and a
non-optional glob that matches no files raises ValueError. A spec
that starts with a glob character such as ``*`` or ``[`` must be
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.
quoted in YAML.
- ``jw.link`` — replaces a node with the value found at a dot-separated
target path. A prefix before the first ``|`` names the resulting
key instead of replacing the node in place.
@ -55,7 +30,6 @@ themselves.
from __future__ import annotations
import os
import re
from copy import deepcopy
@ -64,14 +38,10 @@ from typing import Any, TypeAlias, cast
import yaml # type: ignore[import-untyped]
from jw.util.log import DEBUG, log_m
# -- Constants ------------------------------------------------------------------
IncludeSpec: TypeAlias = tuple[bool, Path, tuple[str, ...]]
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_-]+)\|')
_INCLUDE_PATH_RE = re.compile(r'^([a-zA-Z0-9_.-]+)\|')
@ -167,44 +137,6 @@ def _resolve_path(
# -- 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]:
"""Resolve *file_spec* against *parent* and expand glob characters.
@ -224,126 +156,12 @@ def _glob_include(file_spec: str, parent: Path) -> list[Path]:
path = Path(file_spec)
return [path if path.is_absolute() else parent / path]
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]:
def _parse_include_spec(spec: str, parent: Path) -> list[IncludeSpec]:
"""Parse a jw.include spec into one or more IncludeSpec entries.
The file part may use glob characters; every match becomes a
separate entry. A non-optional glob that matches no files raises
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.
ValueError.
"""
if not spec:
raise ValueError('Empty include spec')
@ -359,31 +177,12 @@ def _parse_include_spec(
if m:
target_path = tuple(m.group(1).split('.'))
spec = spec[len(m.group(1)) + 1:]
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))
paths = _glob_include(spec, parent)
if not paths and not optional:
raise ValueError(f'Include glob {spec!r} matches no files in {path}')
return [(optional, inc, target_path) for inc in paths]
raise ValueError(f'Include glob {spec!r} matches no files')
return [(optional, path, target_path) for path in paths]
def _normalize_include_specs(
specs: Any,
path: Path,
include_map: IncludeMap,
expand_vars: bool,
no_absolute: bool,
) -> Includes:
def _normalize_include_specs(specs: Any, parent: Path) -> Includes:
if specs is None:
return []
if isinstance(specs, str):
@ -394,9 +193,7 @@ def _normalize_include_specs(
for spec in specs:
if not isinstance(spec, str):
raise TypeError(f'Unsupported include entry: {spec!r}')
ret.extend(
_parse_include_spec(spec, path, include_map, expand_vars, no_absolute)
)
ret.extend(_parse_include_spec(spec, parent))
return ret
# -- Include target-path merging -----------------------------------------------
@ -606,14 +403,7 @@ def _expand_links(root: dict[str, Any]) -> dict[str, Any]:
# -- Top-level entry points -----------------------------------------------------
def _load_yaml(
path: str | Path,
optional: bool,
seen: set[Path],
depth: int,
include_map: IncludeMap | None,
no_absolute: bool,
) -> dict[str, Any]:
def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, Any]:
path = Path(path).resolve()
if path in seen:
raise ValueError(f'Cyclic YAML include detected: {path}')
@ -636,36 +426,12 @@ def _load_yaml(
if optional:
return {}
raise
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
)
includes = _normalize_include_specs(ret.get('jw.include', []), path.parent)
ret.pop('jw.include', None)
included_all: dict[str, Any] = {}
for include in includes:
opt, inc_path, target = include
included_next = _load_yaml(
inc_path,
optional = opt,
seen = seen,
depth = depth + 1,
include_map = include_map,
no_absolute = no_absolute
)
included_next = _load_yaml(inc_path, optional = opt, seen = seen)
if not included_next:
# An empty document contributes nothing; in particular
# it must not create the target key of a path-addressed
@ -682,11 +448,7 @@ def _load_yaml(
def load_yaml(path: str | Path, optional: bool = False) -> dict[str, Any]: # export
seen: set[Path] = set()
return _expand_links(
_load_yaml(
path, optional, seen, depth = 0, include_map = None, no_absolute = False
)
)
return _expand_links(_load_yaml(path, optional, seen))
if __name__ == '__main__':
import json

View file

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

View file

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

View file

@ -1153,440 +1153,6 @@ class TestIncludeGlobbing:
with pytest.raises(ValueError, match = 'Cyclic YAML include'):
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 ------------------------------------------------
class TestPathResolution: