Skip to content

Commit 9c876c3

Browse files
committed
Cleanup; Small fixes
1 parent 3906c7f commit 9c876c3

File tree

1 file changed

+21
-107
lines changed

1 file changed

+21
-107
lines changed

scripts/config_extractor.py

Lines changed: 21 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,10 @@
11
import json
2-
import os
32
import pathlib as pl
43
import sys
54
from typing import Literal
65
import yaml
7-
import base64
8-
import hashlib
96
import re
10-
from contextlib import contextmanager
11-
from typing import Any, Generator, Sequence
12-
13-
14-
@contextmanager
15-
def cd(path: str | os.PathLike[str]) -> Generator[None, None, None]:
16-
"""Context manager for changing the working directory"""
17-
old_wd = os.getcwd()
18-
os.chdir(path)
19-
try:
20-
yield
21-
finally:
22-
os.chdir(old_wd)
7+
from typing import Any, Sequence
238

249

2510
def filesafe(s: str, replacement: str = "-") -> str:
@@ -31,11 +16,6 @@ def filesafe(s: str, replacement: str = "-") -> str:
3116
return re.sub(r"[^\w\d-]", replacement, s).lower()
3217

3318

34-
def print_warning(msg: str) -> None:
35-
"""Prints a colored warning message to the console"""
36-
print(f"\033[93mWARNING: {msg}\033[0m")
37-
38-
3919
def multi_get(obj: dict, index: Sequence) -> Any | None: # noqa: ANN401
4020
"""
4121
Gets a value from a nested dictionary.
@@ -48,72 +28,9 @@ def multi_get(obj: dict, index: Sequence) -> Any | None: # noqa: ANN401
4828
return obj
4929

5030

51-
def multi_set(obj: dict, index: Sequence, value: Any) -> bool: # noqa: ANN401
52-
"""
53-
Sets a value in a nested dictionary.
54-
Returns True if the path exists or was able to be created
55-
and the value was set.
56-
"""
57-
for idx, i in enumerate(index):
58-
if not isinstance(obj, dict):
59-
return False
60-
61-
if idx == len(index) - 1:
62-
obj[i] = value
63-
return True
64-
65-
if i not in obj:
66-
obj[i] = {}
67-
68-
obj = obj[i]
69-
assert False
70-
71-
72-
def multi_del(obj: dict, index: Sequence) -> Any | None: # noqa: ANN401
73-
"""
74-
Deletes a value from a nested dictionary.
75-
Returns the value if the path exists and
76-
the value was deleted.
77-
"""
78-
for idx, i in enumerate(index):
79-
if not isinstance(obj, dict):
80-
return None
81-
82-
if idx == len(index) - 1:
83-
if i in obj:
84-
val = obj[i]
85-
del obj[i]
86-
return val
87-
return None
88-
89-
if i not in obj:
90-
return None
91-
92-
obj = obj[i]
93-
assert False
94-
95-
96-
def aslist(obj: Any) -> list: # noqa: ANN401
97-
"""
98-
Converts an object to a list. If the object is
99-
already a list, it is returned as is.
100-
"""
101-
if isinstance(obj, list):
102-
return obj
103-
return [obj]
104-
105-
106-
def b64_urlsafe_hash(s: str) -> str:
107-
"""
108-
Hashes a string and returns a base64 urlsafe encoded version of the hash.
109-
"""
110-
return base64.urlsafe_b64encode(hashlib.sha1(s.encode()).digest()).decode().replace("=", "")
111-
112-
11331
def fetch_and_expand_cpac_configs(
11432
cpac_dir: pl.Path,
11533
output_dir: pl.Path,
116-
checkout_sha: str,
11734
config_names_ids: dict[str, str],
11835
) -> None:
11936
"""
@@ -135,11 +52,15 @@ def fetch_and_expand_cpac_configs(
13552
conf = Preconfiguration(config_id)
13653
config_yaml_string = create_yaml_from_template(conf.dict(), "blank")
13754

138-
with open(output_dir / (filesafe(config_name) + ".yml"), "w", encoding="utf-8") as handle:
55+
with open(
56+
output_dir / (filesafe(config_name) + ".yml"), "w", encoding="utf-8"
57+
) as handle:
13958
handle.write(config_yaml_string)
14059

14160

142-
def check_cpac_config(config: dict) -> tuple[Literal[True], None] | tuple[Literal[False], Exception]:
61+
def check_cpac_config(
62+
config: dict,
63+
) -> tuple[Literal[True], None] | tuple[Literal[False], Exception]:
14364
"""Checks if the specified file is a valid C-PAC config file"""
14465
from CPAC.utils.configuration.configuration import Configuration # noqa
14566

@@ -152,58 +73,62 @@ def check_cpac_config(config: dict) -> tuple[Literal[True], None] | tuple[Litera
15273

15374
def get_cpac_config_ids() -> list[str]:
15475
from CPAC.pipeline import ALL_PIPELINE_CONFIGS
76+
15577
return ALL_PIPELINE_CONFIGS
15678

79+
15780
def fetch_and_expand_all_cpac_configs(
15881
cpac_dir: pl.Path,
15982
output_dir: pl.Path,
160-
checkout_sha: str,
16183
):
16284
config_names_ids = {i: i for i in get_cpac_config_ids()}
16385
fetch_and_expand_cpac_configs(
16486
cpac_dir=cpac_dir,
16587
output_dir=output_dir,
166-
checkout_sha=checkout_sha,
16788
config_names_ids=config_names_ids,
16889
)
16990

91+
17092
def _normalize_index_union(indices) -> list[list[str]]:
17193
if not indices:
17294
return []
17395
if isinstance(indices[0], list):
17496
return indices
17597
return [indices]
17698

99+
177100
def normalize_index_union(indices) -> list[list[str]]:
178101
re = _normalize_index_union(indices)
179102
assert all(isinstance(item, list) for item in re)
180103
assert all(isinstance(i, str) for item in re for i in item)
181104
return re
182105

183106

184-
if __name__ == "__main__":
107+
if __name__ == "__main__":
185108
import sys
186109

187110
sys.path.append(".")
188111

189112
CPAC_DIR = pl.Path(".")
190-
CONFIG_DIR = pl.Path(".")
191-
CPAC_SHA = "dc41bf4f94da07dd78aeaf2fb894e11999f34748"
113+
CONFIG_DIR = pl.Path("configs")
192114

115+
fetch_and_expand_all_cpac_configs(CPAC_DIR, CONFIG_DIR)
193116

194117
with open("nodeblock_index.json") as f:
195118
nbs = json.load(f)
196119

197120
configs = {}
198-
121+
199122
for config_path in CONFIG_DIR.glob("*.yml"):
200123
with open(config_path, "r", encoding="utf-8") as handle:
201124
config = yaml.safe_load(handle)
202125

203126
configs[config_path.stem] = config
204127

205-
def _any_true_in_config(config, multi_index_union):
206-
for path in paths:
128+
print(f"Found {len(configs)} pre-configs!")
129+
130+
def _any_true_in_config(config, multi_index_union):
131+
for path in multi_index_union:
207132
if multi_get(config, path):
208133
return True
209134
return False
@@ -217,7 +142,7 @@ def _any_true_in_config(config, multi_index_union):
217142
if not nb_configs and not nb_switchs:
218143
continue
219144

220-
paths: list[list[str]] = []
145+
paths: list[list[str]] = []
221146
if not nb_configs:
222147
paths = nb_switchs
223148
else:
@@ -233,18 +158,7 @@ def _any_true_in_config(config, multi_index_union):
233158
if _any_true_in_config(config, paths):
234159
configs_with_this_enabled.append(config_name)
235160

236-
nb['workflows'] = configs_with_this_enabled
161+
nb["workflows"] = configs_with_this_enabled
237162

238163
with open("nodeblock_index.json", "w", encoding="utf8") as handle:
239164
json.dump(nbs, handle, indent=2)
240-
241-
242-
243-
244-
245-
246-
247-
248-
249-
250-

0 commit comments

Comments
 (0)