|
1 | 1 | from dataclasses import dataclass |
2 | | -from typing import Any, Dict, Generic, List, Optional, TypeVar |
| 2 | +from typing import Any, Dict, Generic, List, Optional, TypeVar, Callable |
| 3 | + |
| 4 | +from scaleway_core.profile import ProfileDefaults |
3 | 5 |
|
4 | 6 | T = TypeVar("T") |
5 | 7 |
|
6 | 8 |
|
7 | 9 | @dataclass |
8 | 10 | class OneOfPossibility(Generic[T]): |
9 | 11 | param: str |
10 | | - |
11 | 12 | value: Optional[T] |
12 | | - |
13 | 13 | default: Optional[T] = None |
| 14 | + marshal_func: Optional[Callable[[T, ProfileDefaults], Dict[str, Any]]] = None |
14 | 15 |
|
15 | 16 |
|
16 | 17 | def resolve_one_of( |
17 | 18 | possibilities: List[OneOfPossibility[Any]], is_required: bool = False |
18 | | -) -> Dict[str, Any]: |
| 19 | +) -> dict[str, Any | None] | str | dict[Any, Any]: |
19 | 20 | """ |
20 | 21 | Resolves the ideal parameter and value amongst an optional list. |
| 22 | + Uses marshal_func if provided. |
21 | 23 | """ |
22 | 24 |
|
23 | | - # Get the first non-empty parameter |
| 25 | + # Try to resolve using non-None value |
24 | 26 | for possibility in possibilities: |
25 | 27 | if possibility.value is not None: |
| 28 | + if possibility.marshal_func is not None: |
| 29 | + return { |
| 30 | + possibility.param: possibility.marshal_func( |
| 31 | + possibility.value, possibility.default |
| 32 | + ) |
| 33 | + } |
26 | 34 | return {possibility.param: possibility.value} |
27 | 35 |
|
28 | | - # Get the first non-empty default |
| 36 | + # Try to resolve using non-None default |
29 | 37 | for possibility in possibilities: |
30 | 38 | if possibility.default is not None: |
| 39 | + if possibility.marshal_func is not None: |
| 40 | + # When no actual value, call with None as value |
| 41 | + return { |
| 42 | + possibility.param: possibility.marshal_func( |
| 43 | + None, possibility.default |
| 44 | + ) |
| 45 | + } |
31 | 46 | return {possibility.param: possibility.default} |
32 | 47 |
|
33 | | - # If required, raise an error |
| 48 | + # If required but unresolved, raise an error |
34 | 49 | if is_required: |
35 | 50 | possibilities_keys = " or ".join( |
36 | 51 | [possibility.param for possibility in possibilities] |
37 | 52 | ) |
38 | 53 | raise ValueError(f"one of ${possibilities_keys} must be present") |
39 | 54 |
|
40 | | - # Else, return an empty dict |
| 55 | + # Else, return empty dict |
41 | 56 | return {} |
0 commit comments