| 405 | |
| 406 | |
| 407 | class KeyValuePairLoadCommand(resource.ResourceCommand): |
| 408 | pk_argument_name = "name" |
| 409 | display_attributes = ["name", "value"] |
| 410 | |
| 411 | def __init__(self, resource, *args, **kwargs): |
| 412 | help_text = ( |
| 413 | "Load a list of %s from file." % resource.get_plural_display_name().lower() |
| 414 | ) |
| 415 | super(KeyValuePairLoadCommand, self).__init__( |
| 416 | resource, "load", help_text, *args, **kwargs |
| 417 | ) |
| 418 | |
| 419 | self.parser.add_argument( |
| 420 | "-c", |
| 421 | "--convert", |
| 422 | action="store_true", |
| 423 | help=( |
| 424 | "Convert non-string types (hash, array, boolean," |
| 425 | " int, float) to a JSON string before loading it" |
| 426 | " into the datastore." |
| 427 | ), |
| 428 | ) |
| 429 | self.parser.add_argument( |
| 430 | "file", |
| 431 | help=( |
| 432 | "JSON/YAML file containing the %s(s) to load" |
| 433 | % resource.get_plural_display_name().lower() |
| 434 | ), |
| 435 | ) |
| 436 | |
| 437 | @resource.add_auth_token_to_kwargs_from_cli |
| 438 | def run(self, args, **kwargs): |
| 439 | # normalize the file path to allow for relative files to be specified |
| 440 | file_path = os.path.normpath(pjoin(os.getcwd(), args.file)) |
| 441 | |
| 442 | # load the data (JSON/YAML) from the file |
| 443 | kvps = resource.load_meta_file(file_path) |
| 444 | |
| 445 | instances = [] |
| 446 | # bail out if file was empty |
| 447 | if not kvps: |
| 448 | return instances |
| 449 | |
| 450 | # if the data is not a list (ie. it's a single entry) |
| 451 | # then make it a list so our process loop is generic |
| 452 | if not isinstance(kvps, list): |
| 453 | kvps = [kvps] |
| 454 | |
| 455 | for item in kvps: |
| 456 | # parse required KeyValuePair properties |
| 457 | name = item["name"] |
| 458 | value = item["value"] |
| 459 | |
| 460 | # parse optional KeyValuePair properties |
| 461 | scope = item.get("scope", DEFAULT_CUD_SCOPE) |
| 462 | user = item.get("user", None) |
| 463 | encrypted = item.get("encrypted", False) |
| 464 | secret = item.get("secret", False) |