Esempio n. 1
0
    def resolve_file_conversion(remote_file: GoogleDriveFile) -> str:
        """
        A function to take in a remote file and return to the caller a string that represents the file extension to use
        for this file. This exists to let users who may not know what conversion are available see all options that are
        available to them given a document type so they can download the file as the one best suited to their needs.

        Parameters:
            remote_file (GoogleDriveFile): The remote file who we are attempting to get the conversion for

        Returns:
            conversion_opts[user_input] (str): The file extension we are converting this file to
        """

        while 1:

            # Print the helpful prompt on what the user is choosing and cache the supported conversions list for this
            # file
            print_formatted_text(ANSI(f"\x1b[36mWhat file type would you like to convert \"{remote_file['title']}\" to?"))
            conversion_opts = [ext for ext, link in SUPPORTED_FILE_TYPES.items() if link in remote_file['exportLinks']]

            # Print out all of the possible conversion's for this document and their associated number
            for choice, conversion in enumerate(conversion_opts):
                print_formatted_text(f"[{choice + 1}]: {conversion}")

            try:
                # Prompt the user for their choice of the file types printed out above
                user_input = int(prompt(ANSI(f'\x1b[36mChoose [1-{len(conversion_opts)}]: '))) - 1

                # If the user input a valid index then return the conversion extension they desire
                if 0 <= user_input < len(conversion_opts):
                    return conversion_opts[user_input]

            # If the user input a non integer cast-able value then inform them to use the numbers
            except ValueError:
                print_formatted_text(ANSI('\x1b[31mPlease input the integer that corresponds to your desired file type'))
Esempio n. 2
0
 def run(self, args):
     curr_module = core.get_current_module()
     headers = ['\x1b[96m%s\x1b[0m' % s for s in
                ['Name', 'Current value', 'Type',
                 'Required', 'Default value', 'Description']]
     items = [[n, core.module_input[
         n] if n in core.module_input else '\x1b[91m-\x1b[0m\x1b[97m',
               p.type.__name__, p.required,
               p.default if p.default else '\x1b[91m-\x1b[0m\x1b[97m',
               p.description] for n, p in
              curr_module.input.items()]
     core.logger.info('Module input parameters:')
     print()
     print_formatted_text(
         ANSI(tabulate(
             [['\x1b[97m%s\x1b[0m' % str(s) for s in row] for row in
              items],
             headers=headers,
             tablefmt='psql')))
     print()
     if curr_module.output:
         headers = ['\x1b[96m%s\x1b[0m' % s for s in
                    ['Name', 'Description']]
         items = list(curr_module.output.items())
         core.logger.info('Module output parameters:')
         print_formatted_text(
             ANSI(tabulate(
                 [['\x1b[97m%s\x1b[0m' % str(s) for s in row] for row in
                  items],
                 headers=headers,
                 tablefmt='psql')))
         print()
Esempio n. 3
0
    def on_enter_alter_definitions(self):
        click.echo('\n')

        _alter_resources = confirm(
            ANSI(
                click.style(self._TEXT_ASKALTERRESOURCES,
                            fg=self.CLICK_PROMPT_FG_COLOR)))
        if _alter_resources:
            # open editor
            self._edit_file_with_editor(self.settings.resources_path)
            self._read_resources_file()
            self._parse_resources()
            self.settings.solver.set_resources(self.settings.resources)

        _alter_deployments = confirm(
            ANSI(
                click.style(self._TEXT_ASKALTERWORKLOADS,
                            fg=self.CLICK_PROMPT_FG_COLOR)))
        if _alter_deployments:
            # open editor
            self.settings.dsl_content = self._edit_content_with_editor(
                self.settings.dsl_content)
            self.settings.dsl_importer.reset_app_modules()
            self._parse_dsl()
            self.settings.solver.set_deployment_entities(
                self.settings.deployment_entities)

        self.start_matching()
Esempio n. 4
0
def filterTable(buff):
    global searching
    global selected
    global filteredList
    global table
    global passwords
    global page

    selected = 0
    searching = False

    filteredList = []
    for pwd in passwords:
        found = False
        for attr in pwd:
            if (pwd[attr] and not found):
                found = toPlain(input_field.text) in toPlain(pwd[attr])
            else:
                pass
        if (found):
            filteredList.append(pwd)

    text = ANSI("")
    if len(filteredList) == 0:
        text = ANSI(bcolors.FAIL + "No matches..." + bcolors.ENDC)
    else:
        if page != -1:
            page = 0
        text = getFormattedTable(selected, filteredList)

    table.content.text = text
Esempio n. 5
0
    def resolve_mnemonic_conflict(matching_filenames: List[GoogleDriveFile]) -> GoogleDriveFile:
        """
        A function to ask the user to resolve any mnemonic conflicts that can arise because of how Google Drive
        works. Since Google Drive has display names that are not unique and since we want to use traditional file
        pathing as much as possible it is possible that a filename may correspond to many different files. In that case
        we need to ask the user which one they meant to reference with their query

        Parameters:
            matching_filenames (List[GoogleDriveFile]): A list of all google drive files matched the query by the user

        Returns:
            file_ids[response] (GoogleDriveFile): The GoogleDriveFile whose ID was entered by the user when prompted
        """

        # Cache a dictionary linking all file ids to their corresponding file objects
        file_ids = {file['id']: file for file in matching_filenames}

        while 1:

            # Let the user know what is going wrong before anything else
            print_formatted_text(ANSI("\x1b[31mThere are multiple files with the same filename given!\n"))

            # Until the user provides the info we want keep printing the matching files
            for file in matching_filenames:
                pretty_date = file['modifiedDate'][:file['modifiedDate'].index('.')].replace('T', ' ')
                print_formatted_text(ANSI(f"\x1b[36mDisplay Name: \x1b[37m{file['title']} \x1b[36mLast Modified: "
                                          f"\x1b[37m{pretty_date} \x1b[36mFile ID: \x1b[37m{file['id']}"))

            # Newline for terminal readability and prompt the user to resolve the conflict
            print_formatted_text("")
            response = prompt(ANSI('\x1b[31mPlease copy/paste the ID of the file to which you were referring: '))

            # If the user's response is a valid key then return the associated file
            if response in file_ids.keys():
                return file_ids[response]
Esempio n. 6
0
 async def run(self):
     self.clear_output()
     if self.json["cell_type"] == "code":
         code = self.input_buffer.text.strip()
         if code:
             if self not in self.notebook.executing_cells.values():
                 self.notebook.dirty = True
                 executing_text = rich_print("\nIn [*]:", style="green")
                 self.input_prefix.content = FormattedTextControl(
                     text=ANSI(executing_text))
                 self.notebook.execution_count += 1
                 execution_count = self.notebook.execution_count
                 msg_id = uuid.uuid4().hex
                 self.notebook.msg_id_2_execution_count[
                     msg_id] = execution_count
                 self.notebook.executing_cells[execution_count] = self
                 await self.notebook.kd.execute(self.input_buffer.text,
                                                msg_id=msg_id)
                 del self.notebook.executing_cells[execution_count]
                 text = rich_print(
                     f"\nIn [{execution_count}]:",
                     style="green",
                 )
                 self.input_prefix.content = FormattedTextControl(
                     text=ANSI(text))
                 self.json["execution_count"] = execution_count
                 if self.notebook.app:
                     self.notebook.app.invalidate()
         else:
             self.clear_output()
     else:
         self.clear_output()
Esempio n. 7
0
def do_sync_repo(progress: ProgressBar, repo_path: Path, repo_data: Repository):
    """
    Perform synchronization of one repository
    :param progress: ProgressBar instance
    :param repo_path: Path to repository
    :param repo_data: Repository data
    :return: True if successful
    """
    pb = progress()
    pb.label = ANSI(ui.format_item(str(repo_data.path), ("track", repo_data.track)))

    if not repo_path.exists():
        repo = git.Repo.init(repo_path)
        repo.create_remote("origin", repo_data.url)

    try:
        repo = vcs_git.RepoTool(repo_path, repo_data.url)
    except vcs_git.InvalidRepository:
        pb.label = ANSI(ui.format_item_error(f"Unable to open {repo_data.path!s}", "Invalid repository"))
        return False

    # Fetch
    fetch_result = repo.fetch(repo_data.track)

    # Warn if ahead
    if fetch_result.ahead:
        pb.label = ANSI(
            ui.format_item_error(f"Skipped {repo_data.path!s}", err=f"Ahead by {len(fetch_result.ahead)} commit(s)")
        )
        return False

    status = repo.get_status()

    # Warn if dirty
    if status.is_dirty:
        pb.label = ANSI(ui.format_item_error(f"Skipped {repo_data.path!s}", err="Workspace is dirty"))
        return False

    current_commit = status.head
    new_commit = fetch_result.fetch_head

    extras = []

    if current_commit is None:
        extras.append(f"Checked out {repo_data.track}")
    elif current_commit == new_commit:
        extras.append(f"Already up to date")
    else:
        extras.append(("update", f"{str(current_commit)[0:7]} -> {str(new_commit)[0:7]}"))
        extras.append(("commits", len(fetch_result.behind)))

    repo.checkout("origin/" + repo_data.track, repo_data.track)
    pb.label = ANSI(ui.format_item_ok(str(repo_data.path), *extras))

    return True
Esempio n. 8
0
def print_detect_ansi(val, *more_vals, **kwargs):
    """
    If any val has escape codes, wrap all the vals in ANSI and print with
    print_formatted_text.  Otherwise, print with plain old python print.
    This is much faster than printing everything with print_formatted_text.
    """
    has_escape = '\x1b' in val or any(['\x1b' in more_vals])
    if has_escape:
        print_formatted_text(ANSI(val), *[ANSI(v) for v in more_vals],
                             **kwargs)
    else:
        print(val, *more_vals, **kwargs)
Esempio n. 9
0
 def nb_prompt(self) -> Union[str, ANSI]:
     prompt = f'<{{}}{self.current.get_type()}{{}}> {self.current.get_name()}$ '
     if self.options['color']:
         if isinstance(self.current, archive_paths.ArchivePath):
             prompt = ANSI(prompt.format('\x1b[31;1m', '\x1b[0m'))
         elif isinstance(self.current, paths.VirtualDirPath):
             prompt = ANSI(prompt.format('\x1b[36;1m', '\x1b[0m'))
         else:
             prompt = ANSI(prompt.format('\x1b[34;1m', '\x1b[0m'))
     else:
         prompt = prompt.format('', '')
     return prompt
Esempio n. 10
0
def main(ctx, verbose, script):
	'''Runs SCRIPT as a Dish shell script, or runs an interactive shell if it is
	not specified.

	GitHub repository: https://github.com/dullbananas/dish
	'''
	interactive = script.isatty()
	interpreter = Interpreter(
		ctx=ctx,
		verbose=verbose,
	)

	if interactive:
		from prompt_toolkit import PromptSession, ANSI
		from prompt_toolkit.history import FileHistory
		from prompt_toolkit.lexers import PygmentsLexer
		from prompt_toolkit.auto_suggest import ThreadedAutoSuggest
		from .autosuggest import DishSuggest, CombinedSuggest, FileSuggest
		from .syntax_highlighting import DishHighlight
		from pygments.lexers.shell import BashLexer

		history_path = os.path.expanduser('~/.dish-history')
		open(history_path, 'a').close()
		psession = PromptSession(
			auto_suggest=ThreadedAutoSuggest(CombinedSuggest(objects=[
				DishSuggest(ctx=ctx),
				FileSuggest(ctx=ctx),
			])),
			history=FileHistory(history_path),
			lexer=DishHighlight(interpreter=interpreter),
			mouse_support=True,
		)

		gprompt = ctx.obj.generate_prompt

		while True:
			prompt1 = ANSI(gprompt('PS1'))
			prompt2 = ANSI(gprompt('PS2'))
			line = psession.prompt(prompt1)
			needs_more = interpreter.feed(line)
			while needs_more:
				line = psession.prompt(prompt2)
				needs_more = interpreter.feed(line)

	else:
		while True:
			line = script.readline()
			if line == '':
				break
			else:
				interpreter.feed(line[:-1])
Esempio n. 11
0
File: cell.py Progetto: zkan/nbterm
 async def run(self):
     if self.notebook.executing_cells[0] is not self:
         self.clear_output()
     if self.json["cell_type"] == "code":
         code = self.input_buffer.text.strip()
         if code:
             executing_text = rich_print("\nIn [*]:",
                                         self.notebook.console,
                                         style="green",
                                         end="")
             if self.notebook.executing_cells[0] is self:
                 already_executing = True
             else:
                 already_executing = False
                 self.input_prefix.content = FormattedTextControl(
                     text=ANSI(executing_text))
             if self.notebook.idle is None:
                 self.notebook.idle = asyncio.Event()
             else:
                 while True:
                     await self.notebook.idle.wait()
                     if self.notebook.executing_cells[0] is self:
                         break
                 self.notebook.idle.clear()
             if already_executing:
                 self.input_prefix.content = FormattedTextControl(
                     text=ANSI(executing_text))
                 self.clear_output()
             await self.notebook.kd.execute(self.input_buffer.text)
             text = rich_print(
                 f"\nIn [{self.notebook.execution_count}]:",
                 self.notebook.console,
                 style="green",
                 end="",
             )
             self.input_prefix.content = FormattedTextControl(
                 text=ANSI(text))
             self.json["execution_count"] = self.notebook.execution_count
             self.notebook.execution_count += 1
             if self.notebook.app:
                 self.notebook.app.invalidate()
             self.notebook.executing_cells.remove(self)
             self.notebook.idle.set()
         else:
             self.clear_output()
     else:
         self.clear_output()
         self.notebook.executing_cells.remove(self)
Esempio n. 12
0
    def _render_toolbar(self):
        """Render the formatted text for the bottom toolbar"""

        if self.manager.target is None:
            markup_result = "Active Session: [red]None[/red]"
        else:
            markup_result = f"Active Session: {self.manager.target.platform}"

        # Convert rich-style markup to prompt_toolkit formatted text
        text = rich.text.Text.from_markup(markup_result)
        segments = list(text.render(console))
        rendered = []

        # Here we take each segment's stile, invert the color and render the
        # segment text. This is because the bottom toolbar has it's colors
        # inverted.
        for i in range(len(segments)):
            style = segments[i].style.copy()
            temp = style.color
            style._color = segments[i].style.bgcolor
            style._bgcolor = temp
            rendered.append(style.render(segments[i].text))

        # Join the rendered segments to ANSI escape sequences.
        # This format can be parsed by prompt_toolkit formatted text.
        ansi_result = "".join(rendered)

        # Produce prompt_toolkit formatted text from the ANSI escaped string
        return ANSI(ansi_result)
Esempio n. 13
0
 def c_install(self, args):
     if args:
         if args.startswith('-i '):
             args = args[3:]
             optignore = True
         else:
             optignore = False
         addons = [addon.strip() for addon in args.split(',')]
         with tqdm(total=len(addons),
                   bar_format='{n_fmt}/{total_fmt} |{bar}|') as pbar:
             for addon in addons:
                 installed, name, version = self.core.add_addon(
                     addon, optignore)
                 if installed:
                     self.tableData.append(
                         [f'{AC.GREEN}Installed{AC.RESET}', name, version])
                 else:
                     self.tableData.append([
                         f'{AC.LIGHTBLACK_EX}Already installed{AC.RESET}',
                         name, version
                     ])
                 pbar.update(1)
         self.sanitize_table()
         printft(ANSI(self.table.table))
     else:
         printft(
             HTML(
                 '<ansigreen>Usage:</ansigreen>\n\tThis command accepts a comma-separated list of links as an a'
                 'rgument.\n\tOption <ansiwhite>-i</ansiwhite> will disable the client version check.\n<ansigre'
                 'en>Supported URLs:</ansigreen>\n\thttps://www.curseforge.com/wow/addons/[addon_name] <ansiwhi'
                 'te>|</ansiwhite> cf:[addon_name]\n\thttps://www.wowinterface.com/downloads/[addon_name] <ansi'
                 'white>|</ansiwhite> wowi:[addon_id]\n\thttps://www.tukui.org/addons.php?id=[addon_id] <ansiwh'
                 'ite>|</ansiwhite> tu:[addon_id]\n\thttps://www.tukui.org/classic-addons.php?id=[addon_id] <an'
                 'siwhite>|</ansiwhite> tuc:[addon_id]\n\tElvUI <ansiwhite>|</ansiwhite> ElvU'
                 'I:Dev\n\tTukui'))
Esempio n. 14
0
    def main(self):
        # Very important that we specify input and output, otherwise the
        # terminal will mostly work, but not control characters (e.g. backspace,
        # new line, etc),or ANSI escape sequences will be sent.
        #session = PromptSession(input=self.input, output=self.output)
        #print = print_formatted_text

        cmd = ConsoleCmd(input=self.input,
                         output=self.output,
                         node=self,
                         process_lock=self.process_lock,
                         process_started=self.process_started)
        cmd.cmdloop()

        while True:
            try:
                prompt = str(self.get_node("/root/Player").prompt)
                text = session.prompt(ANSI(prompt))
            except KeyboardInterrupt:
                continue
            except EOFError:
                continue
            else:
                print('You entered:', text)
                print('looking for file to execute...')
                bin_path = str(
                    ProjectSettings.globalize_path(
                        "res://system/bin/")) + "rm" + ".py"
                print('happy?')
                print(bin_path)
Esempio n. 15
0
 def show_help(self):
     self.help_mode = True
     self.help_text = rich_print(md)
     self.help_window = Window(content=FormattedTextControl(
         text=ANSI(self.help_text)))
     self.app.layout = Layout(self.help_window)
     self.help_line = 0
Esempio n. 16
0
    def __init__(self, debug: bool = True, prompt: str = "> ") -> None:
        self.debug_ = debug
        self.prompt = ANSI("> " if prompt is None else prompt)

        self.stdout = StdoutProxy(sleep_between_writes=0.5)
        self.out = create_output(self.stdout)
        self.ses = PromptSession(output=self.out)
Esempio n. 17
0
File: cell.py Progetto: zkan/nbterm
def get_output_text_and_height(outputs: List[Dict[str, Any]],
                               console: Console):
    text_list = []
    height = 0
    for output in outputs:
        if output["output_type"] == "stream":
            text = "".join(output["text"])
            height += text.count("\n") or 1
            if output["name"] == "stderr":
                # TODO: take terminal width into account
                lines = [
                    line + " " * (200 - len(line)) for line in text.split()
                ]
                text = "\n".join(lines)
                text = rich_print(text, console, style="white on red")
        elif output["output_type"] == "error":
            text = "\n".join(output["traceback"])
            height += text.count("\n") + 1
        elif output["output_type"] == "execute_result":
            text = "\n".join(output["data"].get("text/plain", ""))
            height += text.count("\n") or 1
        else:
            continue

        text_list.append(text)
    text_ansi = ANSI("".join(text_list))
    return text_ansi, height
Esempio n. 18
0
def main(ctx, verbose, script):
    '''Runs SCRIPT as a Dish shell script, or runs an interactive shell if it is
	not specified.

	GitHub repository: https://github.com/dullbananas/dish
	'''
    interactive = script.isatty()
    interpreter = Interpreter(
        ctx=ctx,
        verbose=verbose,
    )

    if interactive:
        from prompt_toolkit import PromptSession, ANSI
        from prompt_toolkit.history import FileHistory
        from prompt_toolkit.lexers import PygmentsLexer
        from pygments.lexers.shell import BashLexer

        history_path = os.path.expanduser('~/.dish-history')
        open(history_path, 'a').close()
        psession = PromptSession(
            history=FileHistory(history_path),
            lexer=PygmentsLexer(BashLexer),
            mouse_support=True,
        )

        while True:
            prompt = ANSI(ctx.obj.generate_prompt('PS1'))
            line = psession.prompt(prompt)
            interpreter.feed(line)

    else:
        while True:
            interpreter.feed(script.readline())
Esempio n. 19
0
def prompt(session):
    '''
    mec prompt
    '''
    cmd_list = readline_init(session)

    # cook our completions
    completion_dict = dict.fromkeys(cmd_list)
    completion_dict["target"] = dict.fromkeys(os.listdir("./data"))
    completion_dict["set"] = dict.fromkeys(["auto-update", "proxy-pool"])
    completion_dict["set"]["auto-update"] = dict.fromkeys(["True", "False"])

    mec_completer = NestedCompleter.from_nested_dict(completion_dict)
    mec_ps = ANSI(colors.CYAN + colors.BOLD + "\nmec > " + colors.END)

    cmd_autosuggest = ThreadedAutoSuggest(MecAutoSuggest(completions=cmd_list))

    try:
        mecprompt = PromptSession(message=mec_ps,
                                  mouse_support=True,
                                  history=FileHistory(HISTFILE),
                                  completer=mec_completer,
                                  complete_while_typing=True,
                                  reserve_space_for_menu=2,
                                  auto_suggest=cmd_autosuggest).prompt()
    except termios.error as err:
        colors.colored_print(f"[-] Fatal error: {err}", color_code=colors.RED)
        os.system("mec stop")

    return mecprompt
Esempio n. 20
0
    def on_enter_config_solver(self):
        click.echo('\n')
        click.echo('Configure solver settings:\n')

        _config = self.settings.solver.get_config()
        for setting in _config.get_settings():
            click.echo('Configure {}:\n'.format(setting.name))
            _options = setting.get_options()
            for key, option in enumerate(_options):
                click.echo('[{}] {} - {}'.format(
                    key, click.style(option.value, fg='blue'),
                    option.description))

            _list_of_options = list(range(len(_options)))
            _list_of_options = ListValidator.list_items_to_str(
                _list_of_options)

            option_completer = WordCompleter(_list_of_options)
            _option_choice = prompt(ANSI(
                click.style('\nWhich config option do you choose: ',
                            fg=self.CLICK_PROMPT_FG_COLOR)),
                                    completer=option_completer,
                                    validator=ListValidator(_list_of_options))

            setting.set_value(_options[int(_option_choice)])

        self.start_matching()
Esempio n. 21
0
    def on_enter_config_dsl(self):
        click.echo('\n')

        _importer = {
            'helm': Helm,
        }

        for plugin in plugins.plugin_manager.getPluginsOfCategory("Importer"):
            _name = plugin.name.lower()
            _importer[_name] = plugin.plugin_object

        _options = list(_importer.keys())

        if self.settings.dsl_type is None:
            prompt_completer = WordCompleter(_options)
            _dsl_type = prompt(ANSI(
                click.style(self._TEXT_ASKDSLTYPE,
                            fg=self.CLICK_PROMPT_FG_COLOR)),
                               completer=prompt_completer,
                               validator=ListValidator(_options))
            self.settings.dsl_type = _dsl_type

        try:
            self.settings.dsl_importer = _importer[self.settings.dsl_type]()
        except RequirementsError as e:
            click.echo(click.style('\n[Error] {} '.format(e.message),
                                   fg='red'),
                       err=True)
            exit(1)

        click.echo('\n')
        _config = self.settings.dsl_importer.get_config()
        self._ask_setting_options(_config)

        self.ask_dsl()
Esempio n. 22
0
 def c_install(self, args):
     if args:
         addons = [addon.strip() for addon in args.split(',')]
         with tqdm(total=len(addons),
                   bar_format='{n_fmt}/{total_fmt} |{bar}|') as pbar:
             for addon in addons:
                 installed, name, version = self.core.add_addon(addon)
                 if installed:
                     self.tableData.append(
                         [f'{AC.GREEN}Installed{AC.RESET}', name, version])
                 else:
                     self.tableData.append([
                         f'{AC.LIGHTBLACK_EX}Already installed{AC.RESET}',
                         name, version
                     ])
                 pbar.update(1)
         printft(ANSI(self.table.table))
     else:
         printft(
             HTML(
                 '<ansigreen>Usage:</ansigreen>\n\tThis command accepts a comma-separated list of links as an a'
                 'rgument.\n<ansigreen>Supported URLs:</ansigreen>\n\thttps://www.curseforge.com/wow/addons/[ad'
                 'don_name] <ansiwhite>|</ansiwhite> cf:[addon_name]\n\thttps://www.wowinterface.com/downloads/'
                 '[addon_name] <ansiwhite>|</ansiwhite> wowi:[addon_id]\n\thttps://www.tukui.org/addons.php?id='
                 '[addon_id]\n\thttps://www.tukui.org/classic-addons.php?id=[addon_id]\n\tElvUI <ansiwhite>|</a'
                 'nsiwhite> ElvUI:Dev\n\tTukui'))
Esempio n. 23
0
 def c_uninstall(self, args):
     if args:
         addons = [
             addon.strip()
             for addon in list(reader([args], skipinitialspace=True))[0]
         ]
         with tqdm(total=len(addons),
                   bar_format='{n_fmt}/{total_fmt} |{bar}|') as pbar:
             for addon in addons:
                 name, version = self.core.del_addon(addon)
                 if name:
                     self.tableData.append([
                         f'{AC.LIGHTRED_EX}Uninstalled{AC.RESET}', name,
                         version
                     ])
                 else:
                     self.tableData.append([
                         f'{AC.LIGHTBLACK_EX}Not installed{AC.RESET}',
                         addon, ''
                     ])
                 pbar.update(1)
         self.sanitize_table()
         printft(ANSI(self.table.table))
     else:
         printft(
             HTML(
                 '<ansigreen>Usage:</ansigreen>\n\tThis command accepts a comma-separated list of links as an a'
                 'rgument.\n<ansigreen>Supported URLs:</ansigreen>\n\thttps://www.curseforge.com/wow/addons/[ad'
                 'don_name] <ansiwhite>|</ansiwhite> cf:[addon_name]\n\thttps://www.wowinterface.com/downloads/'
                 '[addon_name] <ansiwhite>|</ansiwhite> wowi:[addon_id]\n\thttps://www.tukui.org/addons.php?id='
                 '[addon_id] <ansiwhite>|</ansiwhite> tu:[addon_id]\n\thttps://www.tukui.org/classic-addons.php'
                 '?id=[addon_id] <ansiwhite>|</ansiwhite> tuc:[addon_id]\n\tElvUI <ansiwhite>|</ansiwhite> ElvU'
                 'I:Dev\n\tTukui'))
Esempio n. 24
0
def parse_user_input(user_input: str):
    """
    A function to parse user input into a friendly form using the docopt library. We firstly need to split the user
    input on spaces unless in quotation marks (files can have spaces in names) so we need to use shlex to do this and
    subsequently separate teh command given from the arguments. Then we can attempt to return the given command along
    with the arguments parsed out by docopt. We use a simply little trick where we get the get the function pointer for
    the given command and can use __doc__ to get the docstring for docopt parsing with the arguments being everything
    in the user input that is not the command.

    Parameters:
        user_input (str): The string representing the raw user input to the shell application
    """

    try:

        # Split the full command into its parts but ignore space in quotes
        full_command = shlex.split(user_input)
        command, arguments = full_command[0], full_command[1:]

        # Attempt to parse the arguments using docopt and a function pointer to their docstring
        return command, docopt(FUNCTION_COMMANDS[command].__doc__,
                               argv=arguments)

    except (SystemExit, KeyError) as e:

        # If the error was caused by the user issuing a non-valid command then let them know
        if type(e) is KeyError:
            print_formatted_text(
                ANSI(
                    f'\x1b[31mCommand "{command}" is not recognized as a valid command!'
                ))

        # Otherwise check to make sure they user gave invalid arguments and not asking for help
        elif '-h' not in arguments and '--help' not in arguments:
            print_formatted_text(
                ANSI(
                    f'\x1b[31mInvalid arguments for command "{command}" -> {arguments}'
                ))

        # Return an empty dictionary to let execute_shell know we failed
        return command, dict()

    except ValueError:
        # If the error was caused by not closing the parenthesis then let the user know
        print_formatted_text(
            ANSI(f'\x1b[31mMissing closing quotation, so cannot parse input'))
        return '', dict()
Esempio n. 25
0
 def handle_exception(self, e):
     if len(self.tableData) > 1:
         printft(ANSI(self.table.table))
     if getattr(sys, 'frozen', False):
         printft(HTML(f'\n<ansibrightred>{str(e)}</ansibrightred>'))
     else:
         sys.tracebacklimit = 1000
         traceback.print_exc()
Esempio n. 26
0
 def c_update(self, args, addline=False, update=True, force=False):
     if len(self.core.cfCache) > 0 or len(self.core.wowiCache) > 0:
         self.core.cfCache = {}
         self.core.wowiCache = {}
     if args:
         addons = [
             addon.strip()
             for addon in list(reader([args], skipinitialspace=True))[0]
         ]
     else:
         addons = sorted(self.core.config['Addons'],
                         key=lambda k: k['Name'].lower())
         self.core.bulk_check(addons)
     with tqdm(total=len(addons),
               bar_format='{n_fmt}/{total_fmt} |{bar}|') as pbar:
         exceptions = []
         for addon in addons:
             try:
                 name, versionnew, versionold, modified = self.core.\
                     update_addon(addon if isinstance(addon, str) else addon['URL'], update, force)
                 if versionold:
                     if versionold == versionnew:
                         if modified:
                             self.tableData.append([
                                 f'{AC.LIGHTRED_EX}Modified{AC.RESET}',
                                 name, versionold
                             ])
                         else:
                             self.tableData.append([
                                 f'{AC.GREEN}Up-to-date{AC.RESET}', name,
                                 versionold
                             ])
                     else:
                         if modified:
                             self.tableData.append([
                                 f'{AC.LIGHTRED_EX}Update suppressed{AC.RESET}',
                                 name, versionold
                             ])
                         else:
                             self.tableData.append([
                                 f'{AC.YELLOW}{"Updated " if update else "Update available"}'
                                 f'{AC.RESET}', name,
                                 f'{AC.YELLOW}{versionnew}{AC.RESET}'
                             ])
                 else:
                     self.tableData.append([
                         f'{AC.LIGHTBLACK_EX}Not installed{AC.RESET}',
                         addon, ''
                     ])
             except Exception as e:
                 exceptions.append(e)
             pbar.update(1)
     self.sanitize_table()
     printft(ANSI('\n' + self.table.table if addline else self.table.table))
     if len(exceptions) > 0:
         self.handle_exception(exceptions, False)
Esempio n. 27
0
    def __init__(self, unit, lab, format, label, val):

        if 'int' in format:
            col = '\x1b[94m'
        elif 'float' in format:
            col = '\x1b[33m'
        elif 'tuple' in format:
            col = '\x1b[98m'
        elif 'str' in format:
            col = '\x1b[35m'
        elif 'bool' in format:
            col = '\x1b[92m'
        elif 'path' in format:
            col = '\x1b[91m'
        elif 'dict' in format:
            col = '\x1b[93m'

        if label == 'Type':
            tmpval = val
            continued = True
            if isinstance(tmpval, list):
                if val:
                    if isinstance(tmpval, list):
                        while continued:
                            if isinstance(tmpval, list):
                                tmpval = tmpval[0]
                            else:
                                val = 'array of ' + type(tmpval).__name__
                                continued = False
                    else:
                        val = 'list of ' + type(tmpval).__name__

            else:
                val = type(tmpval).__name__

        elif label == 'Length':
            if isinstance(val, list):
                if val:
                    tmptxt = '('
                    tmpval = val
                    continued = True
                    if isinstance(tmpval, list):
                        while continued:
                            if isinstance(tmpval, list):
                                tmptxt += str(len(tmpval))
                                tmpval = tmpval[0]
                                tmptxt += ', '
                            else:
                                continued = False
                                tmptxt = tmptxt[0:-2]+')'
                    else:
                        tmptxt = '1'
                    val = tmptxt
            else:
                val = '1'
        print_formatted_text(ANSI(col+unit+'('+lab+')' + ' : ' + label+' = ' + str(val)))
Esempio n. 28
0
File: cell.py Progetto: zkan/nbterm
 def __init__(self, notebook, cell_json: Optional[Dict[str, Any]] = None):
     self.notebook = notebook
     self.json = cell_json or empty_cell_json()
     self.input_prefix = Window(width=10)
     self.output_prefix = Window(width=10, height=0)
     input_text = "".join(self.json["source"])
     if self.json["cell_type"] == "code":
         execution_count = self.json["execution_count"] or " "
         text = rich_print(
             f"\nIn [{execution_count}]:",
             self.notebook.console,
             style="green",
             end="",
         )
         self.input_prefix.content = FormattedTextControl(text=ANSI(text))
         outputs = self.json["outputs"]
         for output in outputs:
             if "execution_count" in output:
                 text = rich_print(
                     f"Out[{output['execution_count']}]:",
                     self.notebook.console,
                     style="red",
                     end="",
                 )
                 self.output_prefix.content = FormattedTextControl(
                     text=ANSI(text))
                 break
     else:
         outputs = []
     output_text, output_height = get_output_text_and_height(
         outputs, self.notebook.console)
     self.input_window = Window()
     self.input_buffer = Buffer(on_text_changed=self.input_text_changed)
     self.input_buffer.text = input_text
     self.set_input_readonly()
     if self.json["cell_type"] == "markdown":
         self.input = HSplit(
             [ONE_ROW,
              VSplit([ONE_COL, self.input_window]), ONE_ROW])
     else:
         self.input = Frame(self.input_window)
     self.output = Window(content=FormattedTextControl(text=output_text))
     self.output.height = output_height
Esempio n. 29
0
File: cell.py Progetto: zkan/nbterm
 def set_input_readonly(self):
     if self.json["cell_type"] == "markdown":
         text = self.input_buffer.text or "Type *Markdown*"
         md = Markdown(text)
         text = rich_print(md, self.notebook.console)
     elif self.json["cell_type"] == "code":
         code = Syntax(self.input_buffer.text, self.notebook.language)
         text = rich_print(code, self.notebook.console)
     self.input_window.content = FormattedTextControl(text=ANSI(text))
     self.input_window.height = text.count("\n") or 1
Esempio n. 30
0
    def on_enter_check_results(self):

        _placement_ok = confirm(
            ANSI(
                click.style(self._TEXT_ASKPLACEMENTOK,
                            fg=self.CLICK_PROMPT_FG_COLOR)))
        if _placement_ok:
            self.export()
        else:
            self.ask_alter()