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