-
-
Notifications
You must be signed in to change notification settings - Fork 33.4k
/
Copy pathinput.py
56 lines (39 loc) · 1.45 KB
/
input.py
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
"""Deal with YAML input."""
from __future__ import annotations
from typing import Any
from .objects import Input
class UndefinedSubstitution(Exception):
"""Error raised when we find a substitution that is not defined."""
def __init__(self, input_name: str) -> None:
"""Initialize the undefined substitution exception."""
super().__init__(f"No substitution found for input {input_name}")
self.input = input
def extract_inputs(obj: Any) -> set[str]:
"""Extract input from a structure."""
found: set[str] = set()
_extract_inputs(obj, found)
return found
def _extract_inputs(obj: Any, found: set[str]) -> None:
"""Extract input from a structure."""
if isinstance(obj, Input):
found.add(obj.name)
return
if isinstance(obj, list):
for val in obj:
_extract_inputs(val, found)
return
if isinstance(obj, dict):
for val in obj.values():
_extract_inputs(val, found)
return
def substitute(obj: Any, substitutions: dict[str, Any]) -> Any:
"""Substitute values."""
if isinstance(obj, Input):
if obj.name not in substitutions:
raise UndefinedSubstitution(obj.name)
return substitutions[obj.name]
if isinstance(obj, list):
return [substitute(val, substitutions) for val in obj]
if isinstance(obj, dict):
return {key: substitute(val, substitutions) for key, val in obj.items()}
return obj