load_yaml: Add globbing to jw.include specs
The jw.include file spec is resolved as a single literal file name, so a set of files under one directory has to be listed one by one. Let the file part of a spec use glob characters (*, ?, [...]). _normalize_include_specs() expands every match into its own IncludeSpec entry, so matches are loaded and deep-merged in lexical order: at the root, later files win; at a target path, the existing content wins as with a single include. A non-optional glob that matches no files raises ValueError; the leading - prefix keeps a glob optional. Document the globbing in the module docstring, including the YAML quoting requirement for specs that start with a glob character, and add tests covering the glob syntax, lexical order, the no-match and optional cases, target-path merging, absolute paths, and self-inclusion. Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v0.84.2 Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
20c08f0957
commit
d5da1599ad
2 changed files with 155 additions and 20 deletions
|
|
@ -6,7 +6,11 @@ supports three extensions:
|
|||
- ``jw.include`` — deep-merges other YAML files into the document,
|
||||
either at the root or at a dot-separated target path. A leading
|
||||
``-`` marks the include as optional (a missing file contributes an
|
||||
empty document).
|
||||
empty document). File names may use glob characters (``*``, ``?``,
|
||||
``[...]``); 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.
|
||||
- ``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.
|
||||
|
|
@ -39,6 +43,7 @@ Includes: TypeAlias = list[IncludeSpec]
|
|||
|
||||
_LINK_NAME_RE = re.compile(r'^([a-zA-Z0-9_-]+)\|')
|
||||
_INCLUDE_PATH_RE = re.compile(r'^([a-zA-Z0-9_.-]+)\|')
|
||||
_GLOB_CHARS = frozenset('*?[')
|
||||
|
||||
# -- Low-level helpers (call graph leaves) --------------------------------------
|
||||
|
||||
|
|
@ -130,7 +135,32 @@ def _resolve_path(
|
|||
|
||||
# -- Include helpers ------------------------------------------------------------
|
||||
|
||||
def _parse_include_spec(spec: str, parent: Path) -> IncludeSpec:
|
||||
def _glob_include(file_spec: str, parent: Path) -> list[Path]:
|
||||
"""Resolve *file_spec* against *parent* and expand glob characters.
|
||||
|
||||
A spec without glob characters resolves to a single path, which
|
||||
need not exist yet. A spec with glob characters is expanded to
|
||||
the matching paths in lexical order (possibly an empty list).
|
||||
"""
|
||||
parts = file_spec.split('/')
|
||||
for i, part in enumerate(parts):
|
||||
if _GLOB_CHARS & set(part):
|
||||
prefix = '/'.join(parts[:i])
|
||||
if file_spec.startswith('/'):
|
||||
base = Path(prefix)
|
||||
else:
|
||||
base = parent / prefix
|
||||
return sorted(base.glob('/'.join(parts[i:])))
|
||||
path = Path(file_spec)
|
||||
return [path if path.is_absolute() else parent / path]
|
||||
|
||||
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.
|
||||
"""
|
||||
if not spec:
|
||||
raise ValueError('Empty include spec')
|
||||
optional = spec.startswith('-')
|
||||
|
|
@ -144,29 +174,25 @@ def _parse_include_spec(spec: str, parent: Path) -> IncludeSpec:
|
|||
m = _INCLUDE_PATH_RE.match(spec)
|
||||
if m:
|
||||
target_path = tuple(m.group(1).split('.'))
|
||||
file_spec = spec[len(m.group(1)) + 1:]
|
||||
else:
|
||||
file_spec = spec
|
||||
else:
|
||||
file_spec = spec
|
||||
path = Path(file_spec)
|
||||
if not path.is_absolute():
|
||||
path = parent / path
|
||||
return (optional, path, target_path)
|
||||
spec = spec[len(m.group(1)) + 1:]
|
||||
paths = _glob_include(spec, parent)
|
||||
if not paths and not optional:
|
||||
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, parent: Path) -> Includes:
|
||||
if specs is None:
|
||||
return []
|
||||
if isinstance(specs, str):
|
||||
return [_parse_include_spec(specs, parent)]
|
||||
if isinstance(specs, list):
|
||||
ret: Includes = []
|
||||
for spec in specs:
|
||||
if not isinstance(spec, str):
|
||||
raise TypeError(f'Unsupported include entry: {spec!r}')
|
||||
ret.append(_parse_include_spec(spec, parent))
|
||||
return ret
|
||||
raise TypeError(f'Unsupported include format: {specs!r}')
|
||||
specs = [specs]
|
||||
if not isinstance(specs, list):
|
||||
raise TypeError(f'Unsupported include format: {specs!r}')
|
||||
ret: Includes = []
|
||||
for spec in specs:
|
||||
if not isinstance(spec, str):
|
||||
raise TypeError(f'Unsupported include entry: {spec!r}')
|
||||
ret.extend(_parse_include_spec(spec, parent))
|
||||
return ret
|
||||
|
||||
# -- Include target-path merging -----------------------------------------------
|
||||
|
||||
|
|
|
|||
|
|
@ -1016,6 +1016,115 @@ class TestIncludeWithPath:
|
|||
assert data['plain_key'] == 'plain_val'
|
||||
assert data['section']['target_key'] == 'target_val'
|
||||
|
||||
# -- jw.include globbing --------------------------------------------------------
|
||||
|
||||
class TestIncludeGlobbing:
|
||||
"""Tests for glob support in jw.include file specs."""
|
||||
|
||||
def test_glob_multiple_files(self, temp_dir: Callable) -> None:
|
||||
"""All glob matches are included."""
|
||||
base = temp_dir(
|
||||
[
|
||||
('conf/a.yaml', 'from_a: 1\n'),
|
||||
('conf/b.yaml', 'from_b: 2\n'),
|
||||
('main.yaml', 'jw.include: conf/*.yaml\n'),
|
||||
]
|
||||
)
|
||||
data = load_yaml(pathlib.Path(base) / 'main.yaml')
|
||||
assert data['from_a'] == 1
|
||||
assert data['from_b'] == 2
|
||||
|
||||
def test_glob_lexical_order(self, temp_dir: Callable) -> None:
|
||||
"""Matches are included in lexical order, later files win."""
|
||||
base = temp_dir(
|
||||
[
|
||||
('conf/1.yaml', 'order: first\nshared: one\n'),
|
||||
('conf/10.yaml', 'order: ten\n'),
|
||||
('conf/2.yaml', 'order: second\nshared: two\n'),
|
||||
('main.yaml', 'jw.include: conf/*.yaml\n'),
|
||||
]
|
||||
)
|
||||
data = load_yaml(pathlib.Path(base) / 'main.yaml')
|
||||
# Lexical order: 1.yaml, 10.yaml, 2.yaml
|
||||
assert data['order'] == 'second'
|
||||
assert data['shared'] == 'two'
|
||||
|
||||
def test_glob_char_class(self, temp_dir: Callable) -> None:
|
||||
"""Character classes match like other glob syntax."""
|
||||
base = temp_dir(
|
||||
[
|
||||
('conf/g1.yaml', 'one: 1\n'),
|
||||
('conf/g2.yaml', 'two: 2\n'),
|
||||
('conf/g3.yaml', 'three: 3\n'),
|
||||
('main.yaml', 'jw.include: conf/g[12].yaml\n'),
|
||||
]
|
||||
)
|
||||
data = load_yaml(pathlib.Path(base) / 'main.yaml')
|
||||
assert data['one'] == 1
|
||||
assert data['two'] == 2
|
||||
assert 'three' not in data
|
||||
|
||||
def test_glob_question_mark(self, temp_dir: Callable) -> None:
|
||||
"""A question mark matches exactly one character."""
|
||||
base = temp_dir(
|
||||
[
|
||||
('conf/g1.yaml', 'one: 1\n'),
|
||||
('conf/g12.yaml', 'twelve: 12\n'),
|
||||
('main.yaml', 'jw.include: conf/g?.yaml\n'),
|
||||
]
|
||||
)
|
||||
data = load_yaml(pathlib.Path(base) / 'main.yaml')
|
||||
assert data['one'] == 1
|
||||
assert 'twelve' not in data
|
||||
|
||||
def test_glob_no_match_raises(self, temp_dir: Callable) -> None:
|
||||
"""A non-optional glob matching no files raises."""
|
||||
base = temp_dir([('main.yaml', 'jw.include: missing/*.yaml\n')])
|
||||
with pytest.raises(ValueError, match = 'matches no files'):
|
||||
load_yaml(pathlib.Path(base) / 'main.yaml')
|
||||
|
||||
def test_glob_optional_no_match(self, temp_dir: Callable) -> None:
|
||||
"""An optional glob matching no files contributes nothing."""
|
||||
base = temp_dir([('main.yaml', 'jw.include: -missing/*.yaml\n')])
|
||||
data = load_yaml(pathlib.Path(base) / 'main.yaml')
|
||||
assert data == {}
|
||||
|
||||
def test_glob_with_target_path(self, temp_dir: Callable) -> None:
|
||||
"""Each match is merged at the target path, in lexical order."""
|
||||
base = temp_dir(
|
||||
[
|
||||
('conf/a.yaml', 'first: a\nshared: from_a\n'),
|
||||
('conf/b.yaml', 'shared: from_b\nextra: b\n'),
|
||||
('main.yaml', 'jw.include: section|conf/*.yaml\n'),
|
||||
]
|
||||
)
|
||||
data = load_yaml(pathlib.Path(base) / 'main.yaml')
|
||||
assert data['section']['first'] == 'a'
|
||||
# Existing content at the target path wins, so a.yaml's 'shared'
|
||||
# beats b.yaml's; b.yaml still contributes its new key
|
||||
assert data['section']['shared'] == 'from_a'
|
||||
assert data['section']['extra'] == 'b'
|
||||
|
||||
def test_glob_absolute_path(self, temp_dir: Callable) -> None:
|
||||
"""Absolute glob paths work, not just relative ones."""
|
||||
base = temp_dir(
|
||||
[
|
||||
('conf/a.yaml', 'from_a: 1\n'),
|
||||
('conf/b.yaml', 'from_b: 2\n'),
|
||||
]
|
||||
)
|
||||
main = pathlib.Path(base) / 'main.yaml'
|
||||
main.write_text(f'jw.include: {base}/conf/*.yaml\n')
|
||||
data = load_yaml(main)
|
||||
assert data['from_a'] == 1
|
||||
assert data['from_b'] == 2
|
||||
|
||||
def test_glob_self_include_raises(self, temp_dir: Callable) -> None:
|
||||
"""A glob matching the including file itself is a cycle."""
|
||||
base = temp_dir([('main.yaml', 'jw.include: "*.yaml"\n')])
|
||||
with pytest.raises(ValueError, match = 'Cyclic YAML include'):
|
||||
load_yaml(pathlib.Path(base) / 'main.yaml')
|
||||
|
||||
# -- jw.include with target path ------------------------------------------------
|
||||
|
||||
class TestPathResolution:
|
||||
|
|
|
|||
Loading…
Reference in a new issue