示例#1
0
文件: apps.py 项目: wwwald/Packages
    def _customcmd_apply_args(self, cmd_lines, args_str):
        try:
            args = kpu.cmdline_split(args_str)
        except:
            traceback.print_exc()
            return cmd_lines

        final_cmd_lines = []
        for cmdline in cmd_lines:
            try:
                arg0 = kpu.cmdline_split(cmdline)[0]
                resolved_arg0 = kpu.shell_resolve_exe_path(arg0)
                if resolved_arg0 is not None:
                    arg0 = resolved_arg0
            except:
                traceback.print_exc()
                return cmd_lines

            start_pos = 0
            while True:
                rem = self.REGEX_PLACEHOLDER.search(cmdline, start_pos)
                if not rem:
                    break

                placeholder = rem.group(1)
                if placeholder in ("*", "args"):
                    args_str = args_str.strip()
                    cmdline = cmdline[0:rem.start()] + args_str + cmdline[rem.end():]
                    start_pos = rem.start() + len(args_str)
                elif placeholder in ("q*", "qargs"):
                    if not len(args):
                        cmdline = cmdline[0:rem.start()] + cmdline[rem.end():]
                        start_pos = rem.start()
                    else:
                        quoted_args = kpu.cmdline_quote(args, force_quote=True)
                        cmdline = cmdline[0:rem.start()] + quoted_args + cmdline[rem.end():]
                        start_pos = rem.start() + len(quoted_args)
                else:
                    force_quote = False
                    if placeholder[0] == "q":
                        force_quote = True
                        placeholder = placeholder[1:]

                    arg_idx = int(placeholder)
                    if arg_idx == 0:
                        quoted_arg = kpu.cmdline_quote(arg0, force_quote=force_quote)
                    else:
                        arg_idx = arg_idx - 1
                        quoted_arg = kpu.cmdline_quote(
                            args[arg_idx] if arg_idx < len(args) else "",
                            force_quote=force_quote)

                    cmdline = cmdline[0:rem.start()] + quoted_arg + cmdline[rem.end():]
                    start_pos = rem.start() + len(quoted_arg)

            final_cmd_lines.append(cmdline)

        return final_cmd_lines
示例#2
0
文件: apps.py 项目: wwwald/Packages
    def on_execute(self, item, action):
        # item's category is assumed to be self.ITEMCAT_CUSTOMCMD

        cmd_name = item.target()
        if cmd_name not in self.custom_cmds:
            self.warn('Could not execute item "{}". Custom command "{}" not found.'.format(item.label(), cmd_name))
            return

        custcmd = self.custom_cmds[cmd_name]

        cmd_lines = self._customcmd_apply_args(custcmd['cmds'][:], item.raw_args())
        for cmdline in cmd_lines:
            try:
                args = kpu.cmdline_split(cmdline)
                kpu.shell_execute(
                    args[0], args=args[1:],
                    verb="runas" if custcmd['elevated'] else "",
                    detect_nongui=custcmd['auto_terminal'])
            except:
                traceback.print_exc()
示例#3
0
 def convert(self, data):
     return kpu.cmdline_split(data)
示例#4
0
    def on_suggest(self, user_input, items_chain):
        command = ""
        if not items_chain or items_chain[-1].category(
        ) != kp.ItemCategory.KEYWORD:
            return

        if not user_input:
            command = ""

        if self.should_terminate(0.3):
            return

        optlist = []
        args = []
        try:
            optlist, args = getopt.getopt(kpu.cmdline_split(user_input),
                                          "L:p:command:")
            optlist = dict(optlist)
            if "-p" in optlist.keys() and optlist["-p"].lower(
            ) not in self.PLATFORM_LIST:
                raise getopt.GetoptError(
                    "The platform entered is either incorrect or not yet supported."
                )
            if "-L" in optlist.keys(
            ) and optlist["-L"] not in self.LANGUAGE_LIST:
                raise getopt.GetoptError(
                    "The language entered is either incorrect or not yet supported."
                )
            command = "-".join(args)
        except getopt.GetoptError as options_error:
            self.set_suggestions(
                [
                    self.create_error_item(
                        label="Invalid input format",
                        short_desc=str(options_error),
                        target="error",
                    )
                ],
                kp.Match.ANY,
                kp.Sort.NONE,
            )
            return

        # If command list is empty, notify the user that there was
        # an error while saving tldr pages to local cache.
        if len(self.commands) == 0:
            self.set_suggestions(
                [
                    self.create_error_item(
                        label="The command index is empty.",
                        short_desc=
                        "Retry updating page cache as there may have been a problem during the operation.",
                    )
                ],
                kp.Match.ANY,
                kp.Sort.NONE,
            )
            return

        if command in self.commands:
            language_list = self.config["language"] + (
                ["en"] if "en" not in self.config["language"] else [])
            if "-L" in optlist.keys():
                language_list = [optlist["-L"]]

            platform = optlist["-p"].lower() if "-p" in optlist.keys(
            ) else self.config["platform"]
            platform_list = [platform, "common"] + [
                p for p in self.PLATFORM_LIST if p != platform
            ]

            suggestions = []
            found_in_host = True
            found_in_platform = ""
            break_from_loop = False
            for platform in platform_list:
                platform_dir_path = os.path.join(platform, command + ".md")
                for language in language_list:
                    language_dir_path = "pages" + ("" if language == "en" else
                                                   ("." + language))
                    command_path = os.path.join(self.cache_path,
                                                language_dir_path,
                                                platform_dir_path)
                    if os.path.exists(command_path):
                        suggestions = self._parse_page(command_path)

                        # Check if the command is not found in the host platform
                        if platform not in (platform_list[0], "common"):
                            found_in_host = False
                            found_in_platform = platform
                        break_from_loop = True
                        break
                if break_from_loop:
                    break

            if len(suggestions) == 0:
                language_dir = os.path.join(
                    self.cache_path,
                    "pages" + ("" if language_list[-1] == "en" else
                               ("." + language_list[-1])),
                )
                # If language directory exists and the user overrides the language at runtime,
                # it means that the command is not available in that particular language
                if os.path.exists(language_dir) and "-L" in optlist.keys():
                    suggestions = [
                        self.create_error_item(
                            label="No results found for '{}' command in '{}'.".
                            format(command.replace("-", " "),
                                   language_list[-1]),
                            short_desc=
                            "tldr page for '{}' command is not yet available for the specified language."
                            .format(command.replace("-", " ")),
                        ),
                        self.create_item(
                            category=kp.ItemCategory.URL,
                            label=
                            "Contribute tldr page for '{}' command in '{}'.".
                            format(command.replace("-", " "),
                                   language_list[-1]),
                            short_desc="URL: " + self.TRANSLATION_URL,
                            target=self.TRANSLATION_URL,
                            args_hint=kp.ItemArgsHint.FORBIDDEN,
                            hit_hint=kp.ItemHitHint.IGNORE,
                        ),
                    ]

                # If the language directory does not exist, then possibly
                # the local cache for the language is not available
                else:
                    suggestions = [
                        self.create_error_item(
                            label="Locally cached tldr pages for '{}' not found."
                            .format(language_list[-1]),
                            short_desc=
                            "Try adding '{}' to the language option in the config file or updating the page cache."
                            .format(language_list[-1]),
                        )
                    ]

            # If suggestions are returned and the command is not
            # available for host platform, notify the user
            elif not found_in_host:
                suggestions = [
                    self.create_error_item(
                        label="'{}' command not found for {}.".format(
                            command.replace("-", " "), platform_list[0]),
                        short_desc="Showing results for {}.".format(
                            found_in_platform),
                    )
                ] + suggestions
            self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)

        # Notify user that the command is not yet available in tldr pages
        elif user_input and len(args) != 0:
            self.set_suggestions(
                [
                    self.create_error_item(
                        label=
                        "'{}' command not found. Ensure that the command is correct."
                        .format(command.replace("-", " ")),
                        short_desc=
                        "If the command is correct, it may not yet be available in tldr pages.",
                    ),
                    self.create_item(
                        category=kp.ItemCategory.URL,
                        label="Request tldr page for '{}' command.".format(
                            command.replace("-", " ")),
                        short_desc="URL: " +
                        self.ISSUE_URL.format(command.replace("-", " ")),
                        target=self.ISSUE_URL.format(command),
                        args_hint=kp.ItemArgsHint.FORBIDDEN,
                        hit_hint=kp.ItemHitHint.IGNORE,
                    ),
                ],
                kp.Match.ANY,
                kp.Sort.NONE,
            )