| 1 | from cement import Controller |
| 2 | from argparse_complete_fig import generate_completion_spec |
| 3 | |
| 4 | |
| 5 | class GenerateFigSpecController(Controller): |
| 6 | class Meta: |
| 7 | label = 'generate_fig_spec' |
| 8 | stacked_on = 'base' |
| 9 | stacked_type = 'nested' |
| 10 | description = 'Generate a fig completion spec for this CLI tool' |
| 11 | hide = True |
| 12 | |
| 13 | def _pre_argument_parsing(self): |
| 14 | controller = self.app.controller |
| 15 | meta_by_parser = {} |
| 16 | |
| 17 | for child in controller._controllers: |
| 18 | commands = child._collect_commands() |
| 19 | if commands: |
| 20 | parent = controller._get_parser_parent_by_controller(child) |
| 21 | for command in commands: |
| 22 | command_parser = parent._name_parser_map.get( |
| 23 | command['label'] |
| 24 | ) |
| 25 | meta_by_parser[command_parser] = { |
| 26 | "meta": command, |
| 27 | "type": "command" |
| 28 | } |
| 29 | if child._meta.stacked_type == "embedded": |
| 30 | continue |
| 31 | parser = controller._get_parser_by_controller(child) |
| 32 | meta_by_parser[parser] = { |
| 33 | "meta": child._meta.__dict__, |
| 34 | "type": "controller" |
| 35 | } |
| 36 | |
| 37 | def subcommand_hook(subcommand, parser): |
| 38 | parser_meta = meta_by_parser.get(parser) |
| 39 | if parser_meta is not None: |
| 40 | meta = parser_meta["meta"] |
| 41 | if meta.get("hide", False): |
| 42 | subcommand["hidden"] = True |
| 43 | if meta.get("description"): |
| 44 | subcommand["description"] = meta["description"] |
| 45 | if subcommand["name"] == "generate_fig_spec": |
| 46 | subcommand["priority"] = 0 |
| 47 | |
| 48 | def arg_filter(arg): |
| 49 | return arg.dest in ["__dispatch__", "__controller_namespace__"] |
| 50 | |
| 51 | hooks = {"subcommand": subcommand_hook} |
| 52 | spec = generate_completion_spec( |
| 53 | controller._parser, |
| 54 | hooks, |
| 55 | arg_filter, |
| 56 | "cement_complete_fig" |
| 57 | ) |
| 58 | print(spec) |
| 59 | |
| 60 | def _default(self): |
| 61 | pass |