def run(): """ The main cli function. """ # create an argparse instance parser = argparse.ArgumentParser(prog='newslynx/nlynx') parser.add_argument('--no-color', dest='no_color', action="store_true", default=False, help='Disable colored logging.') # add the subparser "container" subparser = parser.add_subparsers(help='Subcommands', dest='cmd') subcommands = setup(subparser) # parse the arguments + options opts, kwargs = parser.parse_known_args() kwargs = parse_runtime_args(kwargs) # run the necessary subcommand if opts.cmd not in subcommands: subcommands echo_error(RuntimeError("No such subcommand."), no_color=opts.no_color) try: subcommands[opts.cmd](opts, **kwargs) except KeyboardInterrupt as e: echo('Interrupted by user, exiting', color=Fore.YELLOW, no_color=opts.no_color) sys.exit(2) # interrupt except Exception as e: tb = format_exc() echo_error(e, tb, no_color=opts.no_color) sys.exit(1)
def run(opts, **kwargs): # connect to the api api = API( apikey=opts.apikey, org=opts.org, api_url=opts.api_url, raise_errors=opts.raise_errors) # get the collection cobj = getattr(api, opts.collection, None) if not cobj: e = RuntimeError("Error: Collection '{}' does not exist." .format(opts.collection)) echo_error(e) echo("Choose from the following collections:\n\t- {}" .format(opts.collection, "\n\t- {}".join(COLLECTIONS)), color = fore.WHITE) sys.exit(1) # allow for `-` instead of `_`: if opts.method: opts.method = opts.method.replace('-', "_") mobj = getattr(cobj, opts.method, None) if not mobj: options = CMD_TREE[opts.collection] if opts.method != 'ls': e = RuntimeError("Method '{}' does not exist for collection '{}'" .format(opts.method, opts.collection)) echo_error(e, no_color=opts.no_color) else: echo("/{}".format(opts.collection), color=Fore.BLUE, no_color=opts.no_color) msg = "choose from the following methods:\n\t- {}"\ .format( "\n\t- ".join(options)) echo(msg, color=Fore.YELLOW, no_color=opts.no_color) sys.exit(1) # parse body file / json string. kwargs.update(load_data(opts.data, opts)) # execute method try: res = mobj(**kwargs) except KeyboardInterrupt as e: echo_error("Interrupted by user. Exiting.", color=Fore.YELLOW, no_color=opts.no_color) sys.exit(2) # interrupt except Exception as e: tb = format_exc() echo_error(e, tb, no_color=opts.no_color) sys.exit(1) # stream output if isgenerator(res): for r in res: sys.stdout.write(serialize.obj_to_json(r) +"\n") # stream else: sys.stdout.write(serialize.obj_to_json(res)) sys.exit(0)