Created
March 28, 2019 14:49
-
-
Save chaudum/883996d97e0252615de616d086e2e81a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse | |
import json | |
import sys | |
def add_default_args(parser): | |
parser.add_argument( | |
"--region", | |
"-r", | |
required=False, | |
choices={"eastus.azure", "eastus2.azure", "westeurope.azure"}, | |
) | |
parser.add_argument("--env", "-e", required=False, choices={"dev", "prod", "local"}) | |
parser.add_argument( | |
"--format", | |
"-f", | |
required=False, | |
choices={"json", "yaml", "tabular"}, | |
default="tabular", | |
) | |
def noop(name: str, args: argparse.Namespace): | |
pass | |
def add_subparser(parser, tree, name="__root__"): | |
if "args" in tree: | |
for arg_provider in tree["args"]: | |
parser.add_argument(arg_provider()) | |
if "commands" in tree: | |
subparsers = parser.add_subparsers() | |
for _cmd, _tree in tree["commands"].items(): | |
sub = subparsers.add_parser(_cmd, help=_tree.get("help")) | |
add_subparser(sub, _tree, _cmd) | |
else: | |
add_default_args(parser) | |
fn = tree.get("resolver", noop) | |
parser.set_defaults(resolver=lambda a: fn(name, a)) | |
def create_parser(tree): | |
parser = argparse.ArgumentParser(tree["help"]) | |
add_subparser(parser, tree) | |
return parser | |
def login(name: str, args: argparse.Namespace): | |
print(name, args) | |
def logout(name: str, args: argparse.Namespace): | |
print(name, args) | |
def me(name: str, args: argparse.Namespace): | |
print(name, args) | |
if __name__ == "__main__": | |
tree = { | |
"help": "Help for application", | |
"commands": { | |
"login": {"help": "Login to CrateDB Cloud", "resolver": login}, | |
"logout": {"help": "Login to CrateDB Cloud", "resolver": logout}, | |
"me": {"help": "Help for me command", "resolver": me, "args": []}, | |
"projects": { | |
"help": "Help for projects command", | |
"commands": { | |
"create": {"help": "Create project", "args": []}, | |
"list": {"help": "List projects", "args": []}, | |
"delete": {"help": "Delete project", "args": []}, | |
}, | |
}, | |
}, | |
} | |
parser = create_parser(tree) | |
params = parser.parse_args() | |
if "resolver" in params: | |
params.resolver(params) | |
else: | |
parser.print_help() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment