Skip to content

Commit 91f747b

Browse files
committed
rename config "item" to "entry"
1 parent 1a161b2 commit 91f747b

File tree

6 files changed

+105
-91
lines changed

6 files changed

+105
-91
lines changed

idom/client/build_config.py

Lines changed: 62 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -23,50 +23,64 @@
2323
import idom
2424

2525

26-
ConfigItem = Dict[str, Any]
26+
ConfigEntry = Dict[str, Any]
2727

2828

2929
class BuildConfig:
3030

31-
__slots__ = "data", "_path", "_item_info"
31+
__slots__ = "data", "_path", "_entry_info"
3232
_filename = "idom-build-config.json"
33-
_default_config = {"version": idom.__version__, "items": {}}
33+
_default_config = {"version": idom.__version__, "entries": {}}
3434

3535
def __init__(self, path: Path) -> None:
3636
self._path = path / self._filename
3737
self.data = self._load()
38-
self._item_info: Dict[str, ConfigItemInfo] = {
39-
name: derive_config_item_info(item)
40-
for name, item in self.data["items"].items()
38+
self._entry_info: Dict[str, ConfigEntryInfo] = {
39+
name: derive_config_entry_info(entry)
40+
for name, entry in self.data["entries"].items()
4141
}
4242

43-
def clear_items(self) -> None:
44-
self.data["items"].clear()
45-
self._item_info.clear()
43+
def get_entry(self, source_name: str) -> ConfigEntry:
44+
return self.data["entries"][source_name]
4645

47-
def update_items(self, config_items: Iterable[Dict[str, Any]]) -> None:
46+
def get_entry_info(self, source_name: str) -> "ConfigEntryInfo":
47+
return self._entry_info[source_name]
48+
49+
def clear_entries(self) -> None:
50+
self.data["entries"].clear()
51+
self._entry_info.clear()
52+
53+
def update_entries(self, config_entries: Iterable[Dict[str, Any]]) -> None:
4854
# a useful debug assertion - the error which would result otherwise is confusing
49-
assert not isinstance(config_items, dict), "expected list, not a dict"
55+
assert not isinstance(config_entries, dict), "expected list, not a dict"
5056

5157
for conf in map(
5258
# BUG: https://github.com/python/mypy/issues/6697
53-
validate_config_item, # type: ignore
54-
config_items,
59+
validate_config_entry, # type: ignore
60+
config_entries,
5561
):
5662
src_name = conf["source_name"]
57-
self.data["items"][src_name] = conf
58-
self._item_info[src_name] = derive_config_item_info(conf)
63+
self.data["entries"][src_name] = conf
64+
self._entry_info[src_name] = derive_config_entry_info(conf)
65+
66+
def has_entry(self, source_name: str) -> bool:
67+
return source_name in self.data["entries"]
5968

60-
def has_config_item(self, source_name: str) -> bool:
61-
return source_name in self.data["items"]
69+
def entry_has_dependency(self, source_name: str, dependency: str) -> bool:
70+
name, _ = split_package_name_and_version(dependency)
71+
entry_info = self.get_entry_info(source_name)
72+
return (
73+
name in entry_info.js_dependency_aliases
74+
or name == entry_info.js_package_def.name
75+
)
6276

6377
def resolve_js_dependency_name(
6478
self,
6579
source_name: str,
6680
dependency_name: str,
6781
) -> Optional[str]:
6882
try:
69-
info = self._item_info[source_name]
83+
info = self._entry_info[source_name]
7084
except KeyError:
7185
return None
7286
if info.js_package_def is not None:
@@ -82,7 +96,7 @@ def resolve_js_dependency_name(
8296

8397
def all_js_dependencies(self) -> List[str]:
8498
deps: List[str] = []
85-
for info in self._item_info.values():
99+
for info in self._entry_info.values():
86100
if info.js_package_def is not None:
87101
deps.append(str(info.js_package_def.path))
88102
else:
@@ -91,7 +105,7 @@ def all_js_dependencies(self) -> List[str]:
91105

92106
def all_js_dependency_names(self) -> List[str]:
93107
names: List[str] = []
94-
for info in self._item_info.values():
108+
for info in self._entry_info.values():
95109
if info.js_package_def is not None:
96110
names.append(info.js_package_def.name)
97111
else:
@@ -115,9 +129,9 @@ def __repr__(self) -> str:
115129
return f"{type(self).__name__}({self.data})"
116130

117131

118-
def find_python_packages_build_config_items(
132+
def find_python_packages_build_config_entries(
119133
paths: Optional[List[str]] = None,
120-
) -> Tuple[List[ConfigItem], List[Exception]]:
134+
) -> Tuple[List[ConfigEntry], List[Exception]]:
121135
"""Find javascript dependencies declared by Python modules
122136
123137
Parameters:
@@ -129,7 +143,7 @@ def find_python_packages_build_config_items(
129143
Mapping of module names to their corresponding list of discovered dependencies.
130144
"""
131145
failures: List[Exception] = []
132-
build_configs: List[ConfigItem] = []
146+
build_configs: List[ConfigEntry] = []
133147
for module_info in iter_modules(paths):
134148
module_name = module_info.name
135149
module_loader = module_info.module_finder.find_module(module_name)
@@ -138,7 +152,7 @@ def find_python_packages_build_config_items(
138152
module_filename = module_loader.get_filename(module_name)
139153
if isinstance(module_filename, bytes): # pragma: no cover
140154
module_filename = module_filename.decode()
141-
conf = find_build_config_item_in_python_file(
155+
conf = find_build_config_entry_in_python_file(
142156
module_name, Path(module_filename)
143157
)
144158
except Exception as cause:
@@ -153,9 +167,9 @@ def find_python_packages_build_config_items(
153167
return build_configs, failures
154168

155169

156-
def find_build_config_item_in_python_file(
170+
def find_build_config_entry_in_python_file(
157171
module_name: str, module_path: Path
158-
) -> Optional[ConfigItem]:
172+
) -> Optional[ConfigEntry]:
159173
with module_path.open() as f:
160174
module_src = f.read()
161175

@@ -165,7 +179,7 @@ def find_build_config_item_in_python_file(
165179
and isinstance(node.targets[0], ast.Name)
166180
and node.targets[0].id == "idom_build_config"
167181
):
168-
config_item = validate_config_item(
182+
config_entry = validate_config_entry(
169183
{
170184
"source_name": module_name,
171185
**eval(
@@ -177,13 +191,13 @@ def find_build_config_item_in_python_file(
177191
),
178192
}
179193
)
180-
if "js_package" in config_item:
194+
if "js_package" in config_entry:
181195
js_pkg = module_path.parent.joinpath(
182-
*config_item["js_package"].split("/")
196+
*config_entry["js_package"].split("/")
183197
)
184-
config_item["js_package"] = str(js_pkg.resolve().absolute())
185-
config_item.setdefault("source_name", module_name)
186-
return config_item
198+
config_entry["js_package"] = str(js_pkg.resolve().absolute())
199+
config_entry.setdefault("source_name", module_name)
200+
return config_entry
187201

188202
return None
189203

@@ -208,49 +222,49 @@ class JsPackageDef(NamedTuple):
208222
name: str
209223

210224

211-
class ConfigItemInfo(NamedTuple):
225+
class ConfigEntryInfo(NamedTuple):
212226
js_dependency_aliases: Dict[str, str]
213227
aliased_js_dependencies: List[str]
214228
js_package_def: Optional[JsPackageDef]
215229

216230

217-
def derive_config_item_info(config_item: Dict[str, Any]) -> ConfigItemInfo:
218-
config_hash = _hash_config_item(config_item)
219-
alias_suffix = f"{config_item['source_name']}-{config_hash}"
231+
def derive_config_entry_info(config_entry: Dict[str, Any]) -> ConfigEntryInfo:
232+
config_hash = _hash_config_entry(config_entry)
233+
alias_suffix = f"{config_entry['source_name']}-{config_hash}"
220234
aliases: Dict[str, str] = {}
221235
aliased_js_deps: List[str] = []
222-
for dep in config_item.get("js_dependencies", []):
236+
for dep in config_entry.get("js_dependencies", []):
223237
dep_name = split_package_name_and_version(dep)[0]
224238
dep_alias = f"{dep_name}-{alias_suffix}"
225239
aliases[dep_name] = dep_alias
226240
aliased_js_deps.append(f"{dep_alias}@npm:{dep}")
227241

228242
js_pkg_def: Optional[JsPackageDef]
229-
if "js_package" in config_item:
230-
js_pkg_path = Path(config_item["js_package"])
243+
if "js_package" in config_entry:
244+
js_pkg_path = Path(config_entry["js_package"])
231245
js_pkg_json = js_pkg_path / "package.json"
232246
try:
233247
with js_pkg_json.open() as f:
234248
js_pkg_name = str(json.load(f)["name"])
235249
except FileNotFoundError as error:
236250
raise ValueError(
237251
f"Path to package {str(js_pkg_json)!r} specified by "
238-
f"{config_item['source_name']!r} does not exist"
252+
f"{config_entry['source_name']!r} does not exist"
239253
) from error
240254
else:
241255
js_pkg_def = JsPackageDef(path=js_pkg_path, name=js_pkg_name)
242256
else:
243257
js_pkg_def = None
244258

245-
return ConfigItemInfo(
259+
return ConfigEntryInfo(
246260
js_dependency_aliases=aliases,
247261
aliased_js_dependencies=aliased_js_deps,
248262
js_package_def=js_pkg_def,
249263
)
250264

251265

252-
def _hash_config_item(config_item: Dict[str, Any]) -> str:
253-
conf_hash = sha256(json.dumps(config_item, sort_keys=True).encode())
266+
def _hash_config_entry(config_entry: Dict[str, Any]) -> str:
267+
conf_hash = sha256(json.dumps(config_entry, sort_keys=True).encode())
254268
short_hash_int = (
255269
int(conf_hash.hexdigest(), 16)
256270
# chop off the last 8 digits (no need for that many)
@@ -263,13 +277,13 @@ def _hash_config_item(config_item: Dict[str, Any]) -> str:
263277
"type": "object",
264278
"properties": {
265279
"version": {"type": "string"},
266-
"items": {
280+
"entries": {
267281
"type": "object",
268-
"patternProperties": {".*": {"$ref": "#/definitions/ConfigItem"}},
282+
"patternProperties": {".*": {"$ref": "#/definitions/ConfigEntry"}},
269283
},
270284
},
271285
"definitions": {
272-
"ConfigItem": {
286+
"ConfigEntry": {
273287
"type": "object",
274288
"properties": {
275289
"source_name": {
@@ -291,7 +305,7 @@ def _hash_config_item(config_item: Dict[str, Any]) -> str:
291305
}
292306
},
293307
}
294-
_CONFIG_ITEM_SCHEMA = _CONFIG_SCHEMA["definitions"]["ConfigItem"]
308+
_CONFIG_ITEM_SCHEMA = _CONFIG_SCHEMA["definitions"]["ConfigEntry"]
295309

296310

297311
_V = TypeVar("_V", bound=Any)
@@ -302,6 +316,6 @@ def validate_config(value: _V) -> _V:
302316
return value
303317

304318

305-
def validate_config_item(value: _V) -> _V:
319+
def validate_config_entry(value: _V) -> _V:
306320
validate_schema(value, _CONFIG_ITEM_SCHEMA)
307321
return value

idom/client/manage.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
from .build_config import (
88
BuildConfig,
9-
ConfigItem,
10-
find_python_packages_build_config_items,
9+
ConfigEntry,
10+
find_python_packages_build_config_entries,
1111
)
1212
from .utils import open_modifiable_json, find_js_module_exports_in_source
1313

@@ -51,19 +51,19 @@ def web_module_exists(source_name: str, package_name: str) -> bool:
5151
return True
5252

5353

54-
def build(config_items: Iterable[ConfigItem] = ()) -> None:
54+
def build(config_items: Iterable[ConfigEntry] = ()) -> None:
5555
config = build_config()
5656
with console.spinner("Discovering dependencies"):
57-
py_pkg_configs, errors = find_python_packages_build_config_items()
57+
py_pkg_configs, errors = find_python_packages_build_config_entries()
5858
for e in errors: # pragma: no cover
5959
console.echo(f"{e} because {e.__cause__}", message_color="red")
60-
config.update_items(py_pkg_configs + list(config_items))
60+
config.update_entries(py_pkg_configs + list(config_items))
6161
_build_and_save_config()
6262

6363

6464
def restore() -> None:
6565
config = build_config()
66-
config.clear_items()
66+
config.clear_entries()
6767
_build_and_save_config()
6868

6969

scripts/install_doc_js_modules.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
from pathlib import Path
22

3-
from idom.client.build_config import find_build_config_item_in_python_file
3+
from idom.client.build_config import find_build_config_entry_in_python_file
44
from idom.client.manage import build, build_config
55

66

77
DOCS_PATH = Path(__file__).parent.parent / "docs"
88

99

1010
def install_doc_js_modules():
11-
config_item = find_build_config_item_in_python_file(
11+
config_item = find_build_config_entry_in_python_file(
1212
"__main__", DOCS_PATH / "main.py"
1313
)
1414
if config_item is not None:
15-
if not build_config().has_config_item(config_item["source_name"]):
15+
if not build_config().has_entry(config_item["source_name"]):
1616
build([config_item])
1717

1818

tests/conftest.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ def _clean_last_server_error(last_server_error) -> Iterator[None]:
276276
def install():
277277
def add_dependency(*packages):
278278
config = build_config()
279-
if not config.has_config_item("tests"):
279+
if not config.has_entry("tests"):
280280
build_client(
281281
[
282282
{
@@ -287,7 +287,7 @@ def add_dependency(*packages):
287287
)
288288
else:
289289
to_install = set(packages)
290-
already_installed = config.data["items"]["tests"]["js_dependencies"]
290+
already_installed = config.get_entry("tests")["js_dependencies"]
291291
not_installed_pkgs = to_install.difference(already_installed)
292292
if not_installed_pkgs:
293293
build_client(
@@ -307,11 +307,11 @@ def add_dependency(*packages):
307307
@pytest.fixture
308308
def temp_build_config():
309309
config = build_config()
310-
original_cfgs = [deepcopy(cfg) for cfg in config.data["items"].values()]
310+
original_cfgs = [deepcopy(cfg) for cfg in config.data["entries"].values()]
311311
try:
312312
yield config
313313
finally:
314-
config.update_items(original_cfgs)
314+
config.update_entries(original_cfgs)
315315
config.save()
316316

317317

0 commit comments

Comments
 (0)