|
22 | 22 |
|
23 | 23 | import argparse
|
24 | 24 | import ast
|
| 25 | +import datetime |
25 | 26 | import getpass
|
26 | 27 | import inspect
|
27 | 28 | import os
|
@@ -441,6 +442,32 @@ def _is_primitive_type(type_name: str) -> bool:
|
441 | 442 | }
|
442 | 443 | return type_name in primitive_types
|
443 | 444 |
|
| 445 | + @staticmethod |
| 446 | + def _python_type_from_string(type_name: str) -> type: |
| 447 | + """Return the corresponding Python *type* for a primitive type name string. |
| 448 | +
|
| 449 | + This helper is used when generating ``argparse`` CLI arguments from the |
| 450 | + OpenAPI-derived operation signatures. Without this mapping the CLI would |
| 451 | + incorrectly assume every primitive parameter is a *string*, potentially |
| 452 | + leading to type errors or unexpected behaviour when invoking the REST |
| 453 | + API. |
| 454 | + """ |
| 455 | + mapping: dict[str, type] = { |
| 456 | + "int": int, |
| 457 | + "float": float, |
| 458 | + "bool": bool, |
| 459 | + "str": str, |
| 460 | + "bytes": bytes, |
| 461 | + "list": list, |
| 462 | + "dict": dict, |
| 463 | + "tuple": tuple, |
| 464 | + "set": set, |
| 465 | + "datetime.datetime": datetime.datetime, |
| 466 | + } |
| 467 | + # Default to ``str`` to preserve previous behaviour for any unrecognised |
| 468 | + # type names while still allowing the CLI to function. |
| 469 | + return mapping.get(type_name, str) |
| 470 | + |
444 | 471 | @staticmethod
|
445 | 472 | def _create_arg(
|
446 | 473 | arg_flags: tuple,
|
@@ -507,15 +534,15 @@ def _create_args_map_from_operation(self):
|
507 | 534 | for parameter in operation.get("parameters"):
|
508 | 535 | for parameter_key, parameter_type in parameter.items():
|
509 | 536 | if self._is_primitive_type(type_name=parameter_type):
|
| 537 | + python_type = self._python_type_from_string(parameter_type) |
| 538 | + is_bool = parameter_type == "bool" |
510 | 539 | args.append(
|
511 | 540 | self._create_arg(
|
512 | 541 | arg_flags=("--" + self._sanitize_arg_parameter_key(parameter_key),),
|
513 |
| - arg_type=type(parameter_type), |
514 |
| - arg_action=argparse.BooleanOptionalAction |
515 |
| - if type(parameter_type) is bool |
516 |
| - else None, |
| 542 | + arg_type=None if is_bool else python_type, |
| 543 | + arg_action=argparse.BooleanOptionalAction if is_bool else None, # type: ignore |
517 | 544 | arg_help=f"{parameter_key} for {operation.get('name')} operation in {operation.get('parent').name}",
|
518 |
| - arg_default=False if type(parameter_type) is bool else None, |
| 545 | + arg_default=False if is_bool else None, |
519 | 546 | )
|
520 | 547 | )
|
521 | 548 | else:
|
|
0 commit comments