Esempio n. 1
0
def main():
    global fire_obj
    last_command = []

    args = parse_args(sys.argv[1:])
    args_data = args.data

    if args.recipe:
        print(Chepy(*args_data).load_recipe(args.recipe).o)
    else:
        args_data.append("-")

        history_file = config.history_path
        session = PromptSession(
            history=FileHistory(history_file),
            style=get_style(),
            wrap_lines=True,
            auto_suggest=AutoSuggestFromHistory(),
        )
        try:
            while True:
                prompt = session.prompt(
                    prompt_message(fire_obj=fire_obj),
                    bottom_toolbar=bottom_toolbar(fire_obj),
                    completer=FuzzyCompleter(
                        merge_completers([CustomCompleter(), chepy_cli.CliCompleter()])
                    ),
                    validator=CustomValidator(),
                    rprompt=get_current_type(fire_obj),
                )

                # check and output any commands that start with cli_
                if re.match(r"^\!", prompt):
                    print(magenta(subprocess.getoutput(re.sub(r"^\!\s?", "", prompt))))
                # check if line is a comment
                elif re.match(r"^#", prompt):
                    print(cyan(prompt))
                # get help for a method
                elif re.match(r"^\?", prompt):
                    _method_name = re.match(r"^\?(\s?)+([\w_]+)", prompt).group(2)
                    chepy_cli.get_doc(_method_name)
                # check if method called is a cli method
                elif re.search(r"^cli_.+", prompt):
                    cli_method = prompt.split()[0]
                    cli_args = re.search(r"--(\w+)\s([\w\W]+)", prompt)
                    # Show errors encountered
                    if cli_method == "cli_show_errors":
                        getattr(chepy_cli, "cli_show_errors")(errors)
                    # show the current plugin path
                    elif cli_method == "cli_plugin_path":
                        getattr(chepy_cli, "cli_plugin_path")(config)
                    # Edit the current state
                    elif cli_method == "cli_edit_state":
                        try:
                            getattr(chepy_cli, "cli_edit_state")(fire_obj, args_data)
                            args_data = args_data[0 : args_data.index("-")] + ["-"]
                        except:
                            e_type, e_msg, e_traceback = sys.exc_info()
                            print(red(e_type.__name__), yellow("Could not edit state"))
                    # Go back one step
                    elif cli_method == "cli_go_back":
                        args_data = args_data[: -len(last_command + ["-"])]
                        print(cyan("Go back: {}".format(last_command)))
                    # Delete the cli history file
                    elif cli_method == "cli_delete_history":
                        Path(config.history_path).unlink()
                    elif cli_args:
                        getattr(chepy_cli, cli_method)(
                            fire_obj, **{cli_args.group(1): cli_args.group(2)}
                        )
                    else:
                        getattr(chepy_cli, cli_method)(fire_obj)

                else:
                    for method in chepy:
                        if not method.startswith("_") and not isinstance(
                            getattr(Chepy, method), property
                        ):
                            fire.decorators._SetMetadata(
                                getattr(Chepy, method),
                                fire.decorators.ACCEPTS_POSITIONAL_ARGS,
                                False,
                            )
                    args_data += prompt.split()
                    if args_data[-1] != "-":
                        args_data.append("-")
                    try:
                        last_command = prompt.split() + ["-"]
                        fire_obj = fire.Fire(Chepy, command=args_data)
                    # handle required args for methods
                    except fire.core.FireExit:
                        args_data = args_data[: -len(last_command)]
                    except TypeError as e:
                        print(red(e.message))
                    except SystemExit:
                        sys.exit()
                    except:
                        # go back to last working arg
                        e_type, e_msg, e_traceback = sys.exc_info()
                        print(red(e_type.__name__), yellow(e_msg.__str__()))
                        args_data = args_data[: -len(last_command)]
                        continue
        except KeyboardInterrupt:
            print(green("\nOKBye"))
            sys.exit()
Esempio n. 2
0
def get_doc(method: str):
    """Get docs for a method"""
    try:
        print(yellow(getattr(Chepy, method).__doc__))
    except:
        print(red(pformat("Could not find docs...")))
Esempio n. 3
0
def cli_plugin_path(config):
    """Print the current plugin path
    """
    print(yellow(str(config.plugin_path)))
Esempio n. 4
0
def main():
    global fire_obj
    last_command = []

    args = parse_args(sys.argv[1:])
    args_data = args.data

    args_data.append("-")

    history_file = config.history_path
    session = PromptSession(
        history=FileHistory(history_file),
        style=get_style(),
        wrap_lines=True,
        auto_suggest=AutoSuggestFromHistory(),
    )
    try:
        while True:
            prompt = session.prompt(
                prompt_message(fire_obj=fire_obj),
                bottom_toolbar=bottom_toolbar(fire_obj),
                completer=FuzzyCompleter(
                    merge_completers([CustomCompleter(), chepy_cli.CliCompleter()])
                ),
                validator=CustomValidator(),
                rprompt=get_current_type(fire_obj),
            )

            # check and output any commands that start with cli_
            if re.match(r"^\!", prompt):
                print(subprocess.getoutput(re.sub(r"^\!\s?", "", prompt)))
            elif re.search(r"^cli_.+", prompt):
                cli_method = prompt.split()[0]
                cli_args = re.search(r"--(\w+)\s(\w+)", prompt)
                if cli_method == "cli_show_errors":
                    getattr(chepy_cli, "cli_show_errors")(errors)
                elif cli_method == "cli_go_back":
                    args_data = args_data[: -len(last_command + ["-"])]
                    print(cyan("Go back: {}".format(last_command)))
                elif cli_method == "cli_delete_history":
                    Path(config.history_path).unlink()
                elif cli_args:
                    getattr(chepy_cli, cli_method)(
                        fire_obj, **{cli_args.group(1): cli_args.group(2)}
                    )
                else:
                    getattr(chepy_cli, cli_method)(fire_obj)

            else:
                for method in chepy:
                    if not method.startswith("_") and not isinstance(
                        getattr(Chepy, method), property
                    ):
                        fire.decorators._SetMetadata(
                            getattr(Chepy, method),
                            fire.decorators.ACCEPTS_POSITIONAL_ARGS,
                            False,
                        )
                args_data += prompt.split()
                if args_data[-1] != "-":
                    args_data.append("-")
                try:
                    last_command = prompt.split() + ["-"]
                    fire_obj = fire.Fire(Chepy, command=args_data)
                except:
                    # go back to last working arg
                    e_type, e_msg, e_traceback = sys.exc_info()
                    print(red(e_type.__name__), yellow(e_msg.__str__()))
                    args_data = args_data[: -len(last_command)]
                    continue
    except KeyboardInterrupt:
        print("OKBye")
        sys.exit()