Repository navigation
Expand file tree
/
Copy pathconfig.py
More file actions
149 lines (131 loc) · 5.4 KB
/
Copy pathconfig.py
File metadata and controls
149 lines (131 loc) · 5.4 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import copy
import functools
import logging
import os
from pathlib import Path
from typing import Any
import yaml
from running.modifier import Modifier
from running.runtime import Runtime
from running.suite import BenchmarkSuite
def load_class(cls, config):
return {k: cls.from_config(k, v) for (k, v) in config.items()}
KEY_CLASS_MAPPING = {
"suites": BenchmarkSuite,
"modifiers": Modifier,
"runtimes": Runtime,
}
class Configuration:
def __init__(self, kv_pairs: dict[str, Any]):
assert "includes" not in kv_pairs
assert "overrides" not in kv_pairs
self.__items = kv_pairs
def save_to_file(self, fd):
yaml.dump(self.__items, fd)
def resolve_class(self):
"""Resolve the values by instantiating instances of classes
For example, self.values["suites"] is a Dict[str, Dict[str, str]],
where in the inner dictionary contains the string representation of a
benchmark suite.
After this function returns, self.values["suites"] becomes a
Dict[str, BenchmarkSuite].
Change the KEY_CLASS_MAPPING to change which classes get resolved.
"""
for cls_name, cls in KEY_CLASS_MAPPING.items():
if cls_name in self.__items:
self.__items[cls_name] = load_class(cls, self.__items[cls_name])
if "benchmarks" in self.__items:
for suite_name, bms in self.__items["benchmarks"].items():
suite = self.__items["suites"][suite_name]
benchmarks = []
for b in bms:
benchmarks.append(suite.get_benchmark(b))
self.__items["benchmarks"][suite_name] = benchmarks
def get(self, name: str) -> Any:
return self.__items.get(name)
def override(self, selector: str, new_value: Any):
current: Any = self.__items
parts = list(selector.split("."))
for index, p in enumerate(parts):
if index == len(parts) - 1:
if p.isnumeric():
current[int(p)] = new_value
else:
current[p] = new_value
else:
if p.isnumeric():
current = current[int(p)]
else:
current = current[p]
def combine(self, other: "Configuration") -> "Configuration":
"""Combine top-level items of self.values.
Arrays are concatenated and dictionaries are updated.
"""
new_values = copy.deepcopy(self.__items)
for k, v in other.__items.items():
if k in new_values:
if type(new_values[k]) is list:
new_values[k].extend(copy.deepcopy(other.__items[k]))
else:
if type(new_values[k]) is not dict:
raise TypeError(
f"Key `{k}` has been defined in one of the "
f"included files, and the value of `{k}`, {repr(v)}, "
"is not an array or a dictionary. "
"Please use overrides instead."
)
new_values[k].update(copy.deepcopy(other.__items[k]))
else:
new_values[k] = copy.deepcopy(other.__items[k])
return Configuration(new_values)
@staticmethod
def parse_file(path: Path) -> Any:
with path.open("r") as fd:
try:
config = yaml.safe_load(fd)
return config
except yaml.YAMLError as e:
raise SyntaxError(f"Not able to parse the configuration file, {e}")
@staticmethod
def from_file(in_folder: Path, p: str) -> "Configuration":
expand_p = os.path.expandvars(p)
logging.info(
f"Loading config {p}, expanding to {expand_p}, relative to {in_folder}"
)
path = Path(expand_p)
if path.is_absolute():
logging.info(" is absolute")
else:
path = in_folder.joinpath(p)
logging.info(f" resolved to {path}")
if not path.exists():
raise ValueError(f"Configuration not found at path '{path}'")
if not path.is_file():
raise ValueError(f"Configuration at path '{path}' is not a file")
with path.open("r") as fd:
try:
config = yaml.safe_load(fd)
except yaml.YAMLError as e:
raise SyntaxError(f"Not able to parse the configuration file, {e}")
if config is None:
raise ValueError("Parsed configuration file is None")
if "includes" in config:
includes = [
Configuration.from_file(path.parent, p) for p in config["includes"]
]
base = functools.reduce(lambda left, right: left.combine(right), includes)
if "overrides" in config:
for selector, new_value in config["overrides"].items():
base.override(selector, new_value)
del config["overrides"]
del config["includes"]
final_config = Configuration(config)
final_config = base.combine(final_config)
else:
if "overrides" in config:
raise KeyError(
'You specified "overrides" but not "includes".'
" This does not make sense."
)
final_config = Configuration(config)
return final_config