|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | | -__all__: list[str] = ["_DICT_LIST_FIELDS", "_LIST_STR_FIELDS", "_STR_FIELDS"] |
| 3 | +import typing |
| 4 | + |
| 5 | +if typing.TYPE_CHECKING: |
| 6 | + from collections.abc import Callable |
| 7 | + |
| 8 | + |
| 9 | +__all__: list[str] = ["_process_dynamic_metadata"] |
4 | 10 |
|
5 | 11 |
|
6 | 12 | # Name is not dynamically settable, so not in this list |
|
23 | 29 | ] |
24 | 30 | ) |
25 | 31 |
|
26 | | -_DICT_LIST_FIELDS = frozenset( |
27 | | - [ |
28 | | - "urls", |
29 | | - "optional-dependencies", |
30 | | - ] |
31 | | -) |
| 32 | +T = typing.TypeVar("T", bound="str | list[str] | dict[str, str] | dict[str, list[str]]") |
| 33 | + |
| 34 | + |
| 35 | +def _process_dynamic_metadata(field: str, action: Callable[[str], str], result: T) -> T: |
| 36 | + """ |
| 37 | + Helper function for processing the an action on the various possible metadata fields. |
| 38 | + """ |
| 39 | + |
| 40 | + if field in _STR_FIELDS: |
| 41 | + if not isinstance(result, str): |
| 42 | + msg = f"Field {field!r} must be a string" |
| 43 | + raise RuntimeError(msg) |
| 44 | + return action(result) # type: ignore[return-value] |
| 45 | + if field in _LIST_STR_FIELDS: |
| 46 | + if not (isinstance(result, list) and all(isinstance(r, str) for r in result)): |
| 47 | + msg = f"Field {field!r} must be a list of strings" |
| 48 | + raise RuntimeError(msg) |
| 49 | + return [action(r) for r in result] # type: ignore[return-value] |
| 50 | + if field == "urls": |
| 51 | + if not isinstance(result, dict) or not all( |
| 52 | + isinstance(v, str) for v in result.values() |
| 53 | + ): |
| 54 | + msg = "Field 'urls' must be a dictionary of strings" |
| 55 | + raise RuntimeError(msg) |
| 56 | + return {k: action(v) for k, v in result.items()} # type: ignore[return-value] |
| 57 | + if field == "optional-dependencies": |
| 58 | + if not isinstance(result, dict) or not all( |
| 59 | + isinstance(v, list) for v in result.values() |
| 60 | + ): |
| 61 | + msg = "Field 'optional-dependencies' must be a dictionary of lists" |
| 62 | + raise RuntimeError(msg) |
| 63 | + return {k: [action(r) for r in v] for k, v in result.items()} # type: ignore[return-value] |
| 64 | + |
| 65 | + msg = f"Unsupported field {field!r} for action" |
| 66 | + raise RuntimeError(msg) |
0 commit comments