CLI arg parser based on an argument table.
| 176 | |
| 177 | |
| 178 | class ArgTableArgParser(CLIArgParser): |
| 179 | """CLI arg parser based on an argument table.""" |
| 180 | |
| 181 | def __init__(self, argument_table, command_table=None): |
| 182 | # command_table is an optional subcommand_table. If it's passed |
| 183 | # in, then we'll update the argparse to parse a 'subcommand' argument |
| 184 | # and populate the choices field with the command table keys. |
| 185 | super().__init__( |
| 186 | formatter_class=self.Formatter, |
| 187 | add_help=False, |
| 188 | usage=USAGE, |
| 189 | conflict_handler='resolve', |
| 190 | ) |
| 191 | if command_table is None: |
| 192 | command_table = {} |
| 193 | self._build(argument_table, command_table) |
| 194 | |
| 195 | def _build(self, argument_table, command_table): |
| 196 | for arg_name in argument_table: |
| 197 | argument = argument_table[arg_name] |
| 198 | argument.add_to_parser(self) |
| 199 | if command_table: |
| 200 | self.add_argument( |
| 201 | 'subcommand', |
| 202 | action=CommandAction, |
| 203 | command_table=command_table, |
| 204 | nargs='?', |
| 205 | ) |
| 206 | |
| 207 | def parse_known_args(self, args, namespace=None): |
| 208 | if len(args) == 1 and args[0] == 'help': |
| 209 | namespace = argparse.Namespace() |
| 210 | namespace.help = 'help' |
| 211 | return namespace, [] |
| 212 | else: |
| 213 | return super().parse_known_args(args, namespace) |
| 214 | |
| 215 | |
| 216 | class SubCommandArgParser(ArgTableArgParser): |
no outgoing calls