Exemple #1
0
def terminal():
    """Terminal Menu"""

    bootup()
    process_input = False
    t_controller = TerminalController()

    if config_terminal.DEFAULT_CONTEXT:
        if config_terminal.DEFAULT_CONTEXT in t_controller.CHOICES_MENUS:
            try:
                print("")
                process_input = t_controller.switch(
                    config_terminal.DEFAULT_CONTEXT.lower())
            except SystemExit:
                print("")
        else:
            print("\nInvalid DEFAULT_CONTEXT config selected!", "\n")

    if not process_input:
        t_controller.print_help()
        parsed_stdin = False

        while True:
            if gtff.ENABLE_QUICK_EXIT:
                print("Quick exit enabled")
                break

            # Get input command from stdin or user
            if not parsed_stdin and len(sys.argv) > 1:
                an_input = " ".join(sys.argv[1:])
                print(f"{get_flair()}> {an_input}")
                parsed_stdin = True

            elif session and gtff.USE_PROMPT_TOOLKIT:
                an_input = session.prompt(f"{get_flair()}> ",
                                          completer=t_controller.completer)

            else:
                an_input = input(f"{get_flair()}> ")

            # Is command empty
            if not an_input:
                print("")
                continue

            # Process list of commands selected by user
            try:
                process_input = t_controller.switch(an_input)
                # None - Keep loop
                # True - Quit or Reset based on flag
                # False - Keep loop and show help menu

                if process_input is not None:
                    # Quit terminal
                    if process_input:
                        break

                    t_controller.print_help()

            except SystemExit:
                print("The command selected doesn't exist\n")
                continue

        if not gtff.ENABLE_QUICK_EXIT:
            # Check if the user wants to reset application
            if an_input == "reset" or t_controller.update_succcess:
                ret_code = reset()
                if ret_code != 0:
                    print_goodbye()
            else:
                print_goodbye()
Exemple #2
0
def terminal(jobs_cmds: List[str] = None, appName: str = "gst"):
    """Terminal Menu"""
    # TODO: HELP WANTED! Refactor the appName setting if a more elegant solution comes up
    if gtff.PACKAGED_APPLICATION:
        appName = "gst_packaged"

    setup_logging(appName)
    logger.info("START")
    log_settings()

    if jobs_cmds is not None and jobs_cmds:
        logger.info("INPUT: %s", "/".join(jobs_cmds))

    export_path = ""
    if jobs_cmds and "export" in jobs_cmds[0]:
        export_path = jobs_cmds[0].split("/")[0].split(" ")[1]
        jobs_cmds = ["/".join(jobs_cmds[0].split("/")[1:])]

    ret_code = 1
    t_controller = TerminalController(jobs_cmds)
    an_input = ""

    if export_path:
        # If the path selected does not start from the user root, give relative location from terminal root
        if export_path[0] == "~":
            export_path = export_path.replace("~", os.environ["HOME"])
        elif export_path[0] != "/":
            export_path = os.path.join(
                os.path.dirname(os.path.abspath(__file__)), export_path)

        # Check if the directory exists
        if os.path.isdir(export_path):
            console.print(
                f"Export data to be saved in the selected folder: '{export_path}'"
            )
        else:
            os.makedirs(export_path)
            console.print(
                f"[green]Folder '{export_path}' successfully created.[/green]")
        gtff.EXPORT_FOLDER_PATH = export_path

    bootup()
    if not jobs_cmds:
        welcome_message()
        t_controller.print_help()

    env_files = [f for f in os.listdir() if f.endswith(".env")]
    if env_files:
        global env_file
        env_file = env_files[0]
        dotenv.load_dotenv(env_file)
    else:
        # create env file
        Path(".env")

    while ret_code:
        if gtff.ENABLE_QUICK_EXIT:
            console.print("Quick exit enabled")
            break

        # There is a command in the queue
        if t_controller.queue and len(t_controller.queue) > 0:
            # If the command is quitting the menu we want to return in here
            if t_controller.queue[0] in ("q", "..", "quit"):
                print_goodbye()
                break

            if gtff.ENABLE_EXIT_AUTO_HELP and len(t_controller.queue) > 1:
                t_controller.queue = t_controller.queue[1:]

            # Consume 1 element from the queue
            an_input = t_controller.queue[0]
            t_controller.queue = t_controller.queue[1:]

            # Print the current location because this was an instruction and we want user to know what was the action
            if an_input and an_input.split(
                    " ")[0] in t_controller.CHOICES_COMMANDS:
                console.print(f"{get_flair()} / $ {an_input}")

        # Get input command from user
        else:
            # Get input from user using auto-completion
            if session and gtff.USE_PROMPT_TOOLKIT:
                try:
                    an_input = session.prompt(
                        f"{get_flair()} / $ ",
                        completer=t_controller.completer,
                        search_ignore_case=True,
                    )
                except KeyboardInterrupt:
                    print_goodbye()
                    break
            # Get input from user without auto-completion
            else:
                an_input = input(f"{get_flair()} / $ ")

        try:
            # Process the input command
            t_controller.queue = t_controller.switch(an_input)
            if an_input in ("q", "quit", "..", "exit"):
                print_goodbye()
                break

            # Check if the user wants to reset application
            if an_input in ("r", "reset") or t_controller.update_success:
                ret_code = reset(
                    t_controller.queue if t_controller.queue else [])
                if ret_code != 0:
                    print_goodbye()
                    break

        except SystemExit:
            logger.exception(
                "The command '%s' doesn't exist on the / menu.",
                an_input,
            )
            console.print(
                f"\nThe command '{an_input}' doesn't exist on the / menu",
                end="")
            similar_cmd = difflib.get_close_matches(
                an_input.split(" ")[0] if " " in an_input else an_input,
                t_controller.controller_choices,
                n=1,
                cutoff=0.7,
            )
            if similar_cmd:
                if " " in an_input:
                    candidate_input = (
                        f"{similar_cmd[0]} {' '.join(an_input.split(' ')[1:])}"
                    )
                    if candidate_input == an_input:
                        an_input = ""
                        t_controller.queue = []
                        console.print("\n")
                        continue
                    an_input = candidate_input
                else:
                    an_input = similar_cmd[0]

                console.print(f" Replacing by '{an_input}'.")
                t_controller.queue.insert(0, an_input)
            else:
                console.print("\n")
Exemple #3
0
def terminal(jobs_cmds: List[str] = None):
    """Terminal Menu"""
    setup_logging("gst")
    logger.info("START")
    logger.info("Python: %s", platform.python_version())
    logger.info("OS: %s", platform.system())
    log_settings()

    if jobs_cmds is not None and jobs_cmds:
        logger.info("INPUT: %s", "/".join(jobs_cmds))

    ret_code = 1
    t_controller = TerminalController(jobs_cmds)
    an_input = ""

    bootup()
    if not jobs_cmds:
        welcome_message()
        t_controller.print_help()

    while ret_code:
        if gtff.ENABLE_QUICK_EXIT:
            console.print("Quick exit enabled")
            break

        # There is a command in the queue
        if t_controller.queue and len(t_controller.queue) > 0:
            # If the command is quitting the menu we want to return in here
            if t_controller.queue[0] in ("q", "..", "quit"):
                print_goodbye()
                break

            if gtff.ENABLE_EXIT_AUTO_HELP and len(t_controller.queue) > 1:
                t_controller.queue = t_controller.queue[1:]

            # Consume 1 element from the queue
            an_input = t_controller.queue[0]
            t_controller.queue = t_controller.queue[1:]

            # Print the current location because this was an instruction and we want user to know what was the action
            if an_input and an_input.split(
                    " ")[0] in t_controller.CHOICES_COMMANDS:
                console.print(f"{get_flair()} / $ {an_input}")

        # Get input command from user
        else:
            # Get input from user using auto-completion
            if session and gtff.USE_PROMPT_TOOLKIT:
                try:
                    an_input = session.prompt(
                        f"{get_flair()} / $ ",
                        completer=t_controller.completer,
                        search_ignore_case=True,
                    )
                except KeyboardInterrupt:
                    print_goodbye()
                    break
            # Get input from user without auto-completion
            else:
                an_input = input(f"{get_flair()} / $ ")

        try:
            # Process the input command
            t_controller.queue = t_controller.switch(an_input)
            if an_input in ("q", "quit", "..", "exit"):
                print_goodbye()
                break

            # Check if the user wants to reset application
            if an_input in ("r", "reset") or t_controller.update_succcess:
                ret_code = reset(
                    t_controller.queue if t_controller.queue else [])
                if ret_code != 0:
                    print_goodbye()
                    break

        except SystemExit:
            logger.exception(
                "The command '%s' doesn't exist on the / menu.",
                an_input,
            )
            console.print(
                f"\nThe command '{an_input}' doesn't exist on the / menu",
                end="")
            similar_cmd = difflib.get_close_matches(
                an_input.split(" ")[0] if " " in an_input else an_input,
                t_controller.controller_choices,
                n=1,
                cutoff=0.7,
            )
            if similar_cmd:
                if " " in an_input:
                    candidate_input = (
                        f"{similar_cmd[0]} {' '.join(an_input.split(' ')[1:])}"
                    )
                    if candidate_input == an_input:
                        an_input = ""
                        t_controller.queue = []
                        console.print("\n")
                        continue
                    an_input = candidate_input
                else:
                    an_input = similar_cmd[0]

                console.print(f" Replacing by '{an_input}'.")
                t_controller.queue.insert(0, an_input)
            else:
                console.print("\n")
def terminal(menu_prior_to_reset=""):
    """Terminal Menu"""

    bootup()
    process_input = False
    t_controller = TerminalController()

    if config_terminal.DEFAULT_CONTEXT or menu_prior_to_reset:
        if (config_terminal.DEFAULT_CONTEXT in t_controller.CHOICES_MENUS
                or menu_prior_to_reset in t_controller.CHOICES_MENUS):
            try:
                print("")
                process_input = t_controller.switch(
                    menu_prior_to_reset
                    or config_terminal.DEFAULT_CONTEXT.lower())
                # Check if the user wants to reset application
                if process_input == MENU_RESET:
                    ret_code = reset(menu_prior_to_reset)
                    if ret_code != 0:
                        print_goodbye()

            except SystemExit:
                print("")
        else:
            print("\nInvalid DEFAULT_CONTEXT config selected!", "\n")

    if process_input != MENU_QUIT:
        t_controller.print_help()

        while True:
            if gtff.ENABLE_QUICK_EXIT:
                print("Quick exit enabled")
                break

            if session and gtff.USE_PROMPT_TOOLKIT:
                an_input = session.prompt(f"{get_flair()}> ",
                                          completer=t_controller.completer)

            else:
                an_input = input(f"{get_flair()}> ")

            # Is command empty
            if not an_input:
                print("")
                continue

            # Process list of commands selected by user
            try:
                process_input = t_controller.switch(an_input)
                # MENU_GO_BACK - Show main context menu again
                # MENU_QUIT - Quit terminal
                # MENU_RESET - Reset terminal and go back to same previous menu

                if process_input == MENU_GO_BACK:
                    t_controller.print_help()
                else:
                    break

            except SystemExit:
                print("The command selected doesn't exist\n")
                continue

        if not gtff.ENABLE_QUICK_EXIT:
            # Check if the user wants to reset application
            if (an_input == "reset" or t_controller.update_succcess
                    or process_input == MENU_RESET):
                ret_code = reset(an_input if an_input != "reset" else "")
                if ret_code != 0:
                    print_goodbye()
            else:
                print_goodbye()
    else:
        print_goodbye()
Exemple #5
0
 def test_reset(self, mock):
     # pylint: disable=unused-argument
     terminal_helper.reset()
Exemple #6
0
def terminal(jobs_cmds: List[str] = None):
    """Terminal Menu"""
    setup_logging()

    logger.info("Terminal started")

    ret_code = 1
    t_controller = TerminalController(jobs_cmds)
    an_input = ""

    if not jobs_cmds:
        bootup()

    while ret_code:
        if gtff.ENABLE_QUICK_EXIT:
            print("Quick exit enabled")
            break

        # There is a command in the queue
        if t_controller.queue and len(t_controller.queue) > 0:
            # If the command is quitting the menu we want to return in here
            if t_controller.queue[0] in ("q", "..", "quit"):
                print("")
                if len(t_controller.queue) > 1:
                    return t_controller.queue[1:]
                return []

            # Consume 1 element from the queue
            an_input = t_controller.queue[0]
            t_controller.queue = t_controller.queue[1:]

            # Print the current location because this was an instruction and we want user to know what was the action
            if an_input and an_input.split(
                    " ")[0] in t_controller.CHOICES_COMMANDS:
                print(f"{get_flair()} / $ {an_input}")

        # Get input command from user
        else:
            # Display help menu when entering on this menu from a level above
            if not an_input:
                t_controller.print_help()

            # Get input from user using auto-completion
            if session and gtff.USE_PROMPT_TOOLKIT:
                an_input = session.prompt(
                    f"{get_flair()} / $ ",
                    completer=t_controller.completer,
                    search_ignore_case=True,
                )
            # Get input from user without auto-completion
            else:
                an_input = input(f"{get_flair()} / $ ")

        try:
            # Process the input command
            t_controller.queue = t_controller.switch(an_input)

            if an_input in ("q", "quit", "..", "exit"):
                print_goodbye()
                break

            # Check if the user wants to reset application
            if an_input in ("r", "reset") or t_controller.update_succcess:
                ret_code = reset(
                    t_controller.queue if len(t_controller.queue) > 0 else [])
                if ret_code != 0:
                    print_goodbye()
                    break

        except SystemExit:
            print(f"\nThe command '{an_input}' doesn't exist on the / menu",
                  end="")
            similar_cmd = difflib.get_close_matches(
                an_input.split(" ")[0] if " " in an_input else an_input,
                t_controller.CHOICES,
                n=1,
                cutoff=0.7,
            )
            if similar_cmd:
                if " " in an_input:
                    candidate_input = (
                        f"{similar_cmd[0]} {' '.join(an_input.split(' ')[1:])}"
                    )
                    if candidate_input == an_input:
                        an_input = ""
                        t_controller.queue = []
                        print("\n")
                        continue
                    an_input = candidate_input
                else:
                    an_input = similar_cmd[0]

                print(f" Replacing by '{an_input}'.")
                t_controller.queue.insert(0, an_input)
            else:
                print("\n")