Team Ai
Apppublic

Jack1808/Claude_Code

sourceHugging Faceupdated 4mo agoView on Hugging Face
0likes
command_utils.py140 linesDownload Raw Back to api
1"""Command parsing utilities for API optimizations."""2 3import shlex4 5 6def extract_command_prefix(command: str) -> str:7    """Extract the command prefix for fast prefix detection.8 9    Parses a shell command safely, handling environment variables and10    command injection attempts. Returns the command prefix suitable11    for quick identification.12 13    Returns:14        Command prefix (e.g., "git", "git commit", "npm install")15        or "none" if no valid command found16    """17    if "`" in command or "$(" in command:18        return "command_injection_detected"19 20    try:21        parts = shlex.split(command, posix=False)22        if not parts:23            return "none"24 25        env_prefix = []26        cmd_start = 027        for i, part in enumerate(parts):28            if "=" in part and not part.startswith("-"):29                env_prefix.append(part)30                cmd_start = i + 131            else:32                break33 34        if cmd_start >= len(parts):35            return "none"36 37        cmd_parts = parts[cmd_start:]38        if not cmd_parts:39            return "none"40 41        first_word = cmd_parts[0]42        two_word_commands = {43            "git",44            "npm",45            "docker",46            "kubectl",47            "cargo",48            "go",49            "pip",50            "yarn",51        }52 53        if first_word in two_word_commands and len(cmd_parts) > 1:54            second_word = cmd_parts[1]55            if not second_word.startswith("-"):56                return f"{first_word} {second_word}"57            return first_word58        return first_word if not env_prefix else " ".join(env_prefix) + " " + first_word59 60    except ValueError:61        return command.split()[0] if command.split() else "none"62 63 64def extract_filepaths_from_command(command: str, output: str) -> str:65    """Extract file paths from a command locally without API call.66 67    Determines if the command reads file contents and extracts paths accordingly.68    Commands like ls/dir/find just list files, so return empty.69    Commands like cat/head/tail actually read contents, so extract the file path.70 71    Returns:72        Filepath extraction result in <filepaths> format73    """74    listing_commands = {75        "ls",76        "dir",77        "find",78        "tree",79        "pwd",80        "cd",81        "mkdir",82        "rmdir",83        "rm",84    }85 86    reading_commands = {"cat", "head", "tail", "less", "more", "bat", "type"}87 88    try:89        parts = shlex.split(command, posix=False)90        if not parts:91            return "<filepaths>\n</filepaths>"92 93        base_cmd = parts[0].split("/")[-1].split("\\")[-1].lower()94 95        if base_cmd in listing_commands:96            return "<filepaths>\n</filepaths>"97 98        if base_cmd in reading_commands:99            filepaths = []100            for part in parts[1:]:101                if part.startswith("-"):102                    continue103                filepaths.append(part)104 105            if filepaths:106                paths_str = "\n".join(filepaths)107                return f"<filepaths>\n{paths_str}\n</filepaths>"108            return "<filepaths>\n</filepaths>"109 110        if base_cmd == "grep":111            flags_with_args = {"-e", "-f", "-m", "-A", "-B", "-C"}112            pattern_provided_via_flag = False113            positional: list[str] = []114 115            skip_next = False116            for part in parts[1:]:117                if skip_next:118                    skip_next = False119                    continue120 121                if part.startswith("-"):122                    if part in flags_with_args:123                        if part in {"-e", "-f"}:124                            pattern_provided_via_flag = True125                        skip_next = True126                    continue127 128                positional.append(part)129 130            filepaths = positional if pattern_provided_via_flag else positional[1:]131            if filepaths:132                paths_str = "\n".join(filepaths)133                return f"<filepaths>\n{paths_str}\n</filepaths>"134            return "<filepaths>\n</filepaths>"135 136        return "<filepaths>\n</filepaths>"137 138    except Exception:139        return "<filepaths>\n</filepaths>"140