Skip to content

Commit 309191a

Browse files
committed
Support multiple scheme files.
1 parent fc89ad2 commit 309191a

8 files changed

Lines changed: 1929 additions & 1857 deletions

File tree

‎map_machine/mapper.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,9 @@ def render_map(arguments: argparse.Namespace) -> None:
350350
fatal(f"Scheme `{arguments.scheme}` not found.")
351351
sys.exit(1)
352352
else:
353-
scheme: Scheme = Scheme.from_file(scheme_path)
353+
scheme: Scheme = Scheme.from_file(
354+
scheme_path, workspace.find_scheme_path
355+
)
354356
if scheme is None:
355357
fatal(f"Failed to load scheme from `{arguments.scheme}`.")
356358
sys.exit(1)

‎map_machine/scheme.py‎

Lines changed: 73 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
)
2929

3030
if TYPE_CHECKING:
31+
from collections.abc import Callable
3132
from pathlib import Path
3233

3334
__author__ = "Sergey Vartanov"
@@ -339,6 +340,66 @@ def get_priority(self, tags: Tags) -> float:
339340
return 1000.0 * layer + self.priority
340341

341342

343+
def _merge_contents(
344+
base: dict[str, Any], overlay: dict[str, Any]
345+
) -> dict[str, Any]:
346+
"""Merge two scheme content dicts.
347+
348+
Lists are concatenated, dicts are merged (overlay wins on key
349+
conflicts), and scalar values are overridden by the overlay.
350+
"""
351+
merged: dict[str, Any] = {}
352+
for key in set(base) | set(overlay):
353+
if key not in overlay:
354+
merged[key] = base[key]
355+
elif key not in base:
356+
merged[key] = overlay[key]
357+
elif isinstance(base[key], list) and isinstance(overlay[key], list):
358+
merged[key] = base[key] + overlay[key]
359+
elif isinstance(base[key], dict) and isinstance(overlay[key], dict):
360+
merged[key] = {**base[key], **overlay[key]}
361+
else:
362+
merged[key] = overlay[key]
363+
return merged
364+
365+
366+
def _load_with_includes(
367+
file_name: Path,
368+
find_scheme_path: Callable[[str], Path | None] | None = None,
369+
) -> dict[str, Any]:
370+
"""Load a scheme YAML file, recursively resolving `include`.
371+
372+
:param file_name: path to the YAML scheme file.
373+
:param find_scheme_path: callback that resolves a scheme identifier
374+
(e.g. `"default"`) to a file path.
375+
"""
376+
with file_name.open(encoding="utf-8") as input_file:
377+
content: dict[str, Any] = yaml.safe_load(input_file.read())
378+
if not content:
379+
message: str = f"Scheme file {file_name} is empty."
380+
raise ValueError(message)
381+
382+
includes: list[str] = content.pop("include", [])
383+
if isinstance(includes, str):
384+
includes = [includes]
385+
386+
base: dict[str, Any] = {}
387+
for identifier in includes:
388+
path: Path | None = None
389+
if find_scheme_path is not None:
390+
path = find_scheme_path(identifier)
391+
if path is None:
392+
path = file_name.parent / f"{identifier}.yml"
393+
if not path.is_file():
394+
message = f"Included scheme `{identifier}` not found."
395+
raise FileNotFoundError(message)
396+
base = _merge_contents(
397+
base, _load_with_includes(path, find_scheme_path)
398+
)
399+
400+
return _merge_contents(base, content)
401+
402+
342403
def _yaml_str(value: bool | str | float) -> str: # noqa: FBT001
343404
"""Convert a YAML value to string.
344405
@@ -420,18 +481,21 @@ def __init__(self, content: dict[str, Any]) -> None:
420481
self.cache: dict[str, tuple[IconSet, int]] = {}
421482

422483
@classmethod
423-
def from_file(cls, file_name: Path) -> Scheme:
484+
def from_file(
485+
cls,
486+
file_name: Path,
487+
find_scheme_path: Callable[[str], Path | None] | None = None,
488+
) -> Scheme:
424489
"""Get scheme from file.
425490
426-
:param file_name: name of the scheme file with tags, colors, and tag key
427-
specification
491+
:param file_name: name of the scheme file with tags, colors, and
492+
tag key specification
493+
:param find_scheme_path: optional callback that resolves a scheme
494+
identifier to a file path (used to resolve `include`
495+
entries)
428496
"""
429-
with file_name.open(encoding="utf-8") as input_file:
430-
content: dict[str, Any] = yaml.safe_load(input_file.read())
431-
if not content:
432-
message: str = "Scheme file is empty."
433-
raise ValueError(message)
434-
return cls(content)
497+
content = _load_with_includes(file_name, find_scheme_path)
498+
return cls(content)
435499

436500
def get_color(self, color_string: str) -> Color:
437501
"""Get any color.

0 commit comments

Comments
 (0)