Coverage for /Users/les/Projects/crackerjack/crackerjack/py313.py: 0%
118 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import subprocess
2import typing
3from enum import Enum, auto
4from pathlib import Path
5from typing import Any, Self, TypedDict
8class CommandRunner[TReturn]:
9 def run_command(self, cmd: list[str], **kwargs: Any) -> TReturn: ...
12class CommandResult(TypedDict):
13 success: bool
14 exit_code: int
15 stdout: str
16 stderr: str
17 command: list[str]
18 duration_ms: float
21def process_command_output(result: CommandResult) -> tuple[bool, str]:
22 match result:
23 case {"success": True, "stdout": stdout} if stdout.strip():
24 return (True, stdout)
25 case {"success": True}:
26 return (True, "Command completed successfully with no output")
27 case {"success": False, "exit_code": code, "stderr": stderr} if code == 127:
28 return (False, f"Command not found: {stderr}")
29 case {"success": False, "exit_code": code} if code > 0:
30 return (False, f"Command failed with exit code {code}: {result['stderr']}")
31 case _:
32 pass
33 return (False, "Unknown command result pattern")
36class HookStatus(Enum):
37 SUCCESS = auto()
38 FAILURE = auto()
39 SKIPPED = auto()
40 ERROR = auto()
43class HookResult(TypedDict):
44 status: HookStatus
45 hook_id: str
46 output: str
47 files: list[str]
50def analyze_hook_result(result: HookResult) -> str:
51 match result:
52 case {"status": HookStatus.SUCCESS, "hook_id": hook_id}:
53 return f"✅ Hook {hook_id} passed successfully"
54 case {"status": HookStatus.FAILURE, "hook_id": hook_id, "output": output} if (
55 "fixable" in output
56 ):
57 return f"🔧 Hook {hook_id} failed with fixable issues"
58 case {"status": HookStatus.FAILURE, "hook_id": hook_id}:
59 return f"❌ Hook {hook_id} failed"
60 case {"status": HookStatus.SKIPPED, "hook_id": hook_id}:
61 return f"⏩ Hook {hook_id} was skipped"
62 case {"status": HookStatus.ERROR, "hook_id": hook_id, "output": output}:
63 return f"💥 Hook {hook_id} encountered an error: {output}"
64 case _:
65 pass
66 return "Unknown hook result pattern"
69class ModernConfigManager:
70 def __init__(self, config_path: Path) -> None:
71 self.config_path = config_path
72 self.config: dict[str, Any] = {}
74 def load(self) -> Self:
75 return self
77 def update(self, key: str, value: Any) -> Self:
78 self.config[key] = value
79 return self
81 def save(self) -> Self:
82 return self
85def categorize_file(file_path: Path) -> str:
86 path_str = str(file_path)
87 name = file_path
88 match path_str:
89 case s if name.suffix == ".py" and "/ tests /" in s:
90 return "Python Test File"
91 case s if name.suffix == ".py" and "__init__.py" in name.name:
92 return "Python Module Init"
93 case s if name.suffix == ".py":
94 return "Python Source File"
95 case s if name.suffix in {".md", ".rst", ".txt"}:
96 return "Documentation File"
97 case s if name.stem.startswith(".") or name.name in {
98 ".gitignore",
99 ".pre-commit-config.yaml",
100 }:
101 return "Configuration File"
102 case _:
103 pass
104 return "Unknown File Type"
107def process_hook_results[T, R](
108 results: list[T],
109 success_handler: typing.Callable[[T], R],
110 failure_handler: typing.Callable[[T], R],
111) -> list[R]:
112 processed_results: list[R] = []
113 for result in results:
114 if (
115 isinstance(result, dict)
116 and "status" in result
117 and result["status"] == HookStatus.SUCCESS
118 ):
119 processed_results.append(success_handler(result))
120 else:
121 processed_results.append(failure_handler(result))
122 return processed_results
125class EnhancedCommandRunner:
126 def __init__(self, working_dir: Path | None = None) -> None:
127 self.working_dir = working_dir
129 def run(self, cmd: list[str], **kwargs: Any) -> CommandResult:
130 import time
132 start_time = time.time()
133 try:
134 process = subprocess.run(
135 cmd,
136 check=False,
137 capture_output=True,
138 text=True,
139 cwd=self.working_dir,
140 **kwargs,
141 )
142 duration_ms = (time.time() - start_time) * 1000
143 return CommandResult(
144 success=process.returncode == 0,
145 exit_code=process.returncode,
146 stdout=process.stdout,
147 stderr=process.stderr,
148 command=cmd,
149 duration_ms=duration_ms,
150 )
151 except subprocess.SubprocessError as e:
152 duration_ms = (time.time() - start_time) * 1000
153 return CommandResult(
154 success=False,
155 exit_code=-1,
156 stdout="",
157 stderr=str(e),
158 command=cmd,
159 duration_ms=duration_ms,
160 )
162 def handle_result(self, result: CommandResult) -> tuple[bool, str]:
163 return process_command_output(result)
166def clean_python_code(code: str) -> str:
167 lines = code.splitlines()
168 cleaned_lines: list[str] = []
169 for line in lines:
170 match line.strip():
171 case "":
172 if not cleaned_lines or cleaned_lines[-1].strip():
173 cleaned_lines.append("")
174 case s if s.startswith(("import ", "from ")):
175 cleaned_lines.append(line)
176 case s if s.startswith("#"):
177 continue
178 case s if "#" in s and (
179 not any(
180 skip in s for skip in ("# noqa", "# type: ", "# pragma", "# skip")
181 )
182 ):
183 code_part = line.split("#", 1)[0].rstrip()
184 if code_part:
185 cleaned_lines.append(code_part)
186 case s if s.startswith(('"""', "'''")):
187 continue
188 case _:
189 cleaned_lines.append(line)
190 return "\n".join(cleaned_lines)