Automatically tell users that dict args must be valid JSON in CLI (#17577)

Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
This commit is contained in:
Harry Mellor
2025-05-02 13:24:55 +01:00
committed by GitHub
parent 6d1479ca4b
commit 785d75a03b
3 changed files with 15 additions and 13 deletions

View File

@@ -150,7 +150,7 @@ def get_kwargs(cls: ConfigType) -> dict[str, Any]:
# Get the help text for the field
name = field.name
help = cls_docs[name]
help = cls_docs[name].strip()
# Escape % for argparse
help = help.replace("%", "%%")
@@ -165,6 +165,7 @@ def get_kwargs(cls: ConfigType) -> dict[str, Any]:
type_hints.add(field.type)
# Set other kwargs based on the type hints
json_tip = "\n\nShould be a valid JSON string."
if contains_type(type_hints, bool):
# Creates --no-<name> and --<name> flags
kwargs[name]["action"] = argparse.BooleanOptionalAction
@@ -201,6 +202,7 @@ def get_kwargs(cls: ConfigType) -> dict[str, Any]:
elif contains_type(type_hints, dict):
# Dict arguments will always be optional
kwargs[name]["type"] = optional_type(json.loads)
kwargs[name]["help"] += json_tip
elif (contains_type(type_hints, str)
or any(is_not_builtin(th) for th in type_hints)):
kwargs[name]["type"] = str