Defines the CLI interface specific API
| 420 | |
| 421 | |
| 422 | class CLIInterfaceAPI(InterfaceAPI): |
| 423 | """Defines the CLI interface specific API""" |
| 424 | |
| 425 | __slots__ = ("commands", "error_exit_codes", "_output_format") |
| 426 | |
| 427 | def __init__(self, api, version="", error_exit_codes=False): |
| 428 | super().__init__(api) |
| 429 | self.commands = {} |
| 430 | self.error_exit_codes = error_exit_codes |
| 431 | |
| 432 | def __call__(self, args=None): |
| 433 | """Routes to the correct command line tool""" |
| 434 | self.api._ensure_started() |
| 435 | args = sys.argv if args is None else args |
| 436 | if not len(args) > 1 or not args[1] in self.commands: |
| 437 | print(str(self)) |
| 438 | return sys.exit(1) |
| 439 | |
| 440 | command = args.pop(1) |
| 441 | result = self.commands.get(command)() |
| 442 | |
| 443 | if self.error_exit_codes and bool(strtobool(result.decode("utf-8"))) is False: |
| 444 | sys.exit(1) |
| 445 | |
| 446 | def handlers(self): |
| 447 | """Returns all registered handlers attached to this API""" |
| 448 | return self.commands.values() |
| 449 | |
| 450 | def extend(self, cli_api, command_prefix="", sub_command="", **kwargs): |
| 451 | """Extends this CLI api with the commands present in the provided cli_api object""" |
| 452 | if sub_command and command_prefix: |
| 453 | raise ValueError( |
| 454 | "It is not currently supported to provide both a command_prefix and sub_command" |
| 455 | ) |
| 456 | |
| 457 | if sub_command: |
| 458 | self.commands[sub_command] = cli_api |
| 459 | else: |
| 460 | for name, command in cli_api.commands.items(): |
| 461 | self.commands["{}{}".format(command_prefix, name)] = command |
| 462 | |
| 463 | @property |
| 464 | def output_format(self): |
| 465 | return getattr(self, "_output_format", hug.defaults.cli_output_format) |
| 466 | |
| 467 | @output_format.setter |
| 468 | def output_format(self, formatter): |
| 469 | self._output_format = formatter |
| 470 | |
| 471 | def __str__(self): |
| 472 | output = "{0}\n\nAvailable Commands:\n\n".format(self.api.doc or self.api.name) |
| 473 | for command_name, command in self.commands.items(): |
| 474 | command_string = " - {}{}".format( |
| 475 | command_name, ": " + str(command).replace("\n", " ") if str(command) else "" |
| 476 | ) |
| 477 | output += command_string[:77] + "..." if len(command_string) > 80 else command_string |
| 478 | output += "\n" |
| 479 | return output |