forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.py
More file actions
59 lines (46 loc) · 1.81 KB
/
Copy pathloader.py
File metadata and controls
59 lines (46 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""Load and validate soup.yaml configs."""
from pathlib import Path
import yaml
from pydantic import ValidationError
from rich.console import Console
from soup_cli.config.schema import SoupConfig
console = Console()
def load_config(path: "Path | str") -> SoupConfig:
"""Load a soup.yaml file and return validated SoupConfig."""
path = Path(path)
raw = yaml.safe_load(path.read_text(encoding="utf-8"))
if raw is None:
console.print("[red]Config file is empty[/]")
raise SystemExit(1)
try:
config = SoupConfig(**raw)
except ValidationError as e:
console.print("[red bold]Config validation error:[/]\n")
for err in e.errors():
loc = " -> ".join(str(part) for part in err["loc"])
console.print(f" [red]{loc}:[/] {err['msg']}")
raise SystemExit(1)
return config
def load_config_from_string(yaml_str: str) -> SoupConfig:
"""Parse a YAML string and return validated SoupConfig.
Unlike load_config(), raises ValueError on errors instead of SystemExit,
making it suitable for API/UI usage.
"""
raw = yaml.safe_load(yaml_str)
if raw is None:
raise ValueError("Config is empty")
if not isinstance(raw, dict):
# A non-mapping document (e.g. a bare list "- a") would make
# SoupConfig(**raw) raise TypeError, breaking this function's
# ValueError-only contract (API/UI callers only catch ValueError).
raise ValueError(
f"Config must be a YAML mapping, got {type(raw).__name__}"
)
try:
return SoupConfig(**raw)
except ValidationError as exc:
errors = []
for err in exc.errors():
loc = " -> ".join(str(part) for part in err["loc"])
errors.append(f"{loc}: {err['msg']}")
raise ValueError("; ".join(errors))