Skip to content

Commit f646314

Browse files
committed
Actually implement the CLI "payload" option
Signed-off-by: Mathias L. Baumann <[email protected]>
1 parent 32573fe commit f646314

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

src/frequenz/client/dispatch/__main__.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,13 @@
1717
from prompt_toolkit.patch_stdout import patch_stdout
1818
from prompt_toolkit.shortcuts import CompleteStyle
1919

20-
from ._cli_types import FuzzyDateTime, FuzzyIntRange, FuzzyTimeDelta, SelectorParamType
20+
from ._cli_types import (
21+
FuzzyDateTime,
22+
FuzzyIntRange,
23+
FuzzyTimeDelta,
24+
JsonParamType,
25+
SelectorParamType,
26+
)
2127
from ._client import Client
2228

2329
DEFAULT_DISPATCH_API_HOST = "88.99.25.81"
@@ -104,7 +110,9 @@ async def list_(ctx: click.Context, /, **filters: Any) -> None:
104110
@click.argument("selector", required=True, type=SelectorParamType())
105111
@click.option("--active", "-a", type=bool, default=True)
106112
@click.option("--dry-run", "-d", type=bool, default=False)
107-
@click.option("--payload", type=str, help="JSON payload for the dispatch")
113+
@click.option(
114+
"--payload", "-p", type=JsonParamType(), help="JSON payload for the dispatch"
115+
)
108116
@click.option("--recurrence", type=str, help="Recurrence rule (see documentation)")
109117
@click.pass_context
110118
async def create(

src/frequenz/client/dispatch/_cli_types.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
"""Types for the CLI client."""
55

6+
import json
67
from datetime import datetime, timedelta, timezone
78
from typing import Any, cast
89

@@ -167,3 +168,36 @@ def convert(
167168
param,
168169
ctx,
169170
)
171+
172+
173+
class JsonParamType(click.ParamType):
174+
"""Click parameter type for JSON strings."""
175+
176+
name = "json"
177+
178+
def convert(
179+
self, value: Any, param: click.Parameter | None, ctx: click.Context | None
180+
) -> dict[str, Any]:
181+
"""Convert the input value into a dictionary.
182+
183+
Args:
184+
value: The input value (string).
185+
param: The Click parameter object.
186+
ctx: The Click context object.
187+
188+
Returns:
189+
A dictionary parsed from the input JSON string.
190+
"""
191+
if isinstance(value, dict): # Already a dictionary
192+
return value
193+
194+
try:
195+
if not value.startswith("{"):
196+
value = "{" + value
197+
if not value.endswith("}"):
198+
value = value + "}"
199+
200+
return cast(dict[str, Any], json.loads(value))
201+
202+
except ValueError as e:
203+
self.fail(f"Invalid JSON string: {value}. Error: {e}", param, ctx)

0 commit comments

Comments
 (0)