import json
from typing import Any, Callable, Dict, List, Optional, Union
def serialize_cli_args(args: Dict[str, Any], schema: Dict[str, str]) -> str:
"""Serializes CLI arguments to JSON with schema validation and defensive checks.
Args:
args: Dictionary of CLI arguments (e.g., {"--name": "John", "--age": 30}).
schema: Dictionary defining the expected type of each argument.
(e.g., {"--name": "string", "--age": "integer"})
Returns:
JSON string representation of the validated arguments.
Raises ValueError if validation fails.
"""
validated_args: Dict[str, Any] = {}
for arg_name, arg_type in schema.items():
if arg_name in args:
value = args[arg_name]
if arg_type == "string":
if not isinstance(value, str):
raise ValueError(f"Argument '{arg_name}' must be a string, got {type(value)}")
validated_args[arg_name] = value
elif arg_type == "integer":
if not isinstance(value, int):
try:
validated_args[arg_name] = int(value) #attempt conversion
except (ValueError, TypeError):
raise ValueError(f"Argument '{arg_name}' must be an integer, got {type(value)}")
else:
validated_args[arg_name] = value
elif arg_type == "float":
if not isinstance(value, (int, float)):
try:
validated_args[arg_name] = float(value) #attempt conversion
except (ValueError, TypeError):
raise ValueError(f"Argument '{arg_name}' must be a float, got {type(value)}")
else:
validated_args[arg_name] = value
elif arg_type == "boolean":
if not isinstance(value, bool):
if isinstance(value, str):
value = value.lower()
if value in ("true", "1", "yes"):
validated_args[arg_name] = True
elif value in ("false", "0", "no"):
validated_args[arg_name] = False
else:
raise ValueError(f"Argument '{arg_name}' must be a boolean, got {type(value)}")
else:
raise ValueError(f"Argument '{arg_name}' must be a boolean, got {type(value)}")
else:
validated_args[arg_name] = value
elif arg_type == "list":
if not isinstance(value, list):
raise ValueError(f"Argument '{arg_name}' must be a list, got {type(value)}")
validated_args[arg_name] = value
else:
raise ValueError(f"Unsupported argument type: {arg_type} for argument '{arg_name}'")
elif arg_name in schema:
raise ValueError(f"Missing required argument: '{arg_name}'")
return json.dumps(validated_args, indent=2)
Add your comment