|
| 1 | +# coding=utf-8 |
| 2 | +""" |
| 3 | +A cmd2 script that saves the help text for every command and sub-commands to a file |
| 4 | +This is meant to be run with pyscript within a cmd2 session. |
| 5 | +""" |
| 6 | + |
| 7 | +import argparse |
| 8 | +import os |
| 9 | +import sys |
| 10 | +import tempfile |
| 11 | +from typing import List |
| 12 | + |
| 13 | + |
| 14 | +def get_sub_commands(parser: argparse.ArgumentParser) -> List[str]: |
| 15 | + """Returns a list of sub-commands for an ArgumentParser""" |
| 16 | + |
| 17 | + sub_cmds = [] |
| 18 | + |
| 19 | + # Check if this is parser has sub-commands |
| 20 | + if parser is not None and parser._subparsers is not None: |
| 21 | + |
| 22 | + # Find the _SubParsersAction for the sub-commands of this parser |
| 23 | + for action in parser._subparsers._actions: |
| 24 | + if isinstance(action, argparse._SubParsersAction): |
| 25 | + for sub_cmd, sub_cmd_parser in action.choices.items(): |
| 26 | + sub_cmds.append(sub_cmd) |
| 27 | + |
| 28 | + # Look for nested sub-commands |
| 29 | + for nested_sub_cmd in get_sub_commands(sub_cmd_parser): |
| 30 | + sub_cmds.append('{} {}'.format(sub_cmd, nested_sub_cmd)) |
| 31 | + |
| 32 | + break |
| 33 | + |
| 34 | + return sub_cmds |
| 35 | + |
| 36 | + |
| 37 | +# Make sure we have access to self |
| 38 | +if 'self' not in globals(): |
| 39 | + print("Run 'set locals_in_py true' and then rerun this script") |
| 40 | + |
| 41 | +# Make sure the user passed in an output file |
| 42 | +elif len(sys.argv) != 2: |
| 43 | + print("Usage: {} <output_file>".format(os.path.basename(sys.argv[0]))) |
| 44 | +else: |
| 45 | + outfile = sys.argv[1] |
| 46 | + |
| 47 | + # Get a list of all commands and help topics and then filter out duplicates |
| 48 | + to_print = set(self.get_all_commands()) | set(self.get_help_topics()) |
| 49 | + |
| 50 | + # Create a script that will call help on each command and topic and write its output to a file |
| 51 | + with tempfile.NamedTemporaryFile(mode='w+t', delete=False) as temp: |
| 52 | + |
| 53 | + # First delete any existing output file |
| 54 | + temp.write('!rm -f {}\n'.format(outfile)) |
| 55 | + |
| 56 | + for item in to_print: |
| 57 | + temp.write('help {} >> {}\n'.format(item, outfile)) |
| 58 | + |
| 59 | + # Add any sub-commands |
| 60 | + for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)): |
| 61 | + temp.write('help {} {} >> {}\n'.format(item, subcmd, outfile)) |
| 62 | + |
| 63 | + # Have the script delete itself as its last step |
| 64 | + temp.write('!rm -f {}\n'.format(temp.name)) |
| 65 | + |
| 66 | + # Tell cmd2 to run the script as its next command |
| 67 | + self.cmdqueue.insert(0, "load '{}'".format(temp.name)) |
0 commit comments