SUBCOMMANDS Dictionary

Sometimes it is desirable to have subcommands. Subcommands allow your CLI to work in a way similar to the git cli, where you have multiple routines that all can be called from a single command.

This example shows how multiple subcommands can be defined and utilized.

CLI_CONFIG = {
    "name": {
        "subcommands": ["test", "apply"],
    },
    "weight": {},
    "power": {
        "subcommands": ["apply"],
    },
}
CONFIG = {
    "name": {
        "default": "frank",
        "help": "Enter the name to use",
    },
    "weight": {
        "default": "150",
        "help": "Enter how heavy it should be",
    },
    "power": {
        "default": "100",
        "help": "Enter how powerful it should be",
    },
}

SUBCOMMANDS = {
    "test": {
        "help": "Used to test",
        "desc": "When running in test mode, things will be tested",
    },
    "apply": {
        "help": "Used to apply",
        "desc": "When running in apply mode, things will be applied",
    },
}

In this example we see that the option name will be available under the subcommands test and apply. The option power will be available only under the subcommand apply and the option weight is globally available.

Detecting the Subparser

When the subparser is used the desired subparser is set on the hub as the variable hub.SUBPARSER. This makes it easy to know what subparser is being used anywhere in your code:

def run(hub):
    if hub.SUBPARSER == "test":
        run_test()
    elif hub.SUBPARSER == "apply":
        run_apply()

Global Subcommand Options

Sometimes an option should be made available to all subcommands, including the root of the command. It is easy to do this! Just add the option _global_ to the list of subcommands.

CLI_CONFIG = {
    "name": {
        "subcommands": ["_global_"],
    },
}
CONFIG = {
    "name": {
        "default": "frank",
        "help": "Enter the name to use",
}

SUBCOMMANDS = {
    "test": {
        "help": "Used to test",
        "desc": "When running in test mode, things will be tested",
    },
    "apply": {
        "help": "Used to apply",
        "desc": "When running in apply mode, things will be applied",
    },
}

In the above example, the –name option is made available to the root and all subcommands.