Coverage for /Users/les/Projects/crackerjack/crackerjack/services/config.py: 0%
208 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 as t
3from pathlib import Path
5from rich.console import Console
7from crackerjack.dynamic_config import DynamicConfigGenerator, generate_config_for_mode
8from crackerjack.models.protocols import OptionsProtocol
11class ConfigurationService:
12 def __init__(self, console: Console, pkg_path: Path) -> None:
13 self.console = console
14 self.pkg_path = pkg_path
15 self.config_generator = DynamicConfigGenerator()
17 def update_precommit_config(self, options: OptionsProtocol) -> bool:
18 try:
19 mode = self._determine_config_mode(options)
20 config_temp_path = generate_config_for_mode(mode)
21 if not config_temp_path:
22 self.console.print("[yellow]⚠️ No configuration generated[/ yellow]")
23 return False
25 config_file = self.pkg_path / ".pre-commit-config.yaml"
26 config_content = config_temp_path.read_text()
28 from crackerjack.services.filesystem import FileSystemService
30 config_content = FileSystemService.clean_trailing_whitespace_and_newlines(
31 config_content
32 )
33 config_file.write_text(config_content)
35 self._temp_config_path = config_temp_path
36 self.console.print("[green]✅[/ green] Pre-commit configuration generated")
38 if getattr(options, "update_precommit", False):
39 success = self._run_precommit_autoupdate()
40 if success:
41 self.console.print("[green]✅[/ green] Pre-commit hooks updated")
42 else:
43 self.console.print(
44 "[yellow]⚠️[/ yellow] Pre-commit autoupdate had issues"
45 )
47 self._update_dynamic_config_versions()
49 return True
50 except Exception as e:
51 self.console.print(
52 f"[red]❌[/ red] Failed to generate pre-commit config: {e}",
53 )
54 return False
56 def get_temp_config_path(self) -> Path | None:
57 return getattr(self, "_temp_config_path", None)
59 def _determine_config_mode(self, options: OptionsProtocol) -> str:
60 if options.experimental_hooks:
61 return "experimental"
62 if hasattr(options, "test") and options.test:
63 return "comprehensive"
64 return "comprehensive"
66 def validate_config(self) -> bool:
67 try:
68 config_file = self.pkg_path / ".pre-commit-config.yaml"
69 if not config_file.exists():
70 self.console.print(
71 "[yellow]⚠️ No pre-commit configuration found[/ yellow]",
72 )
73 return False
74 import yaml
76 with config_file.open() as f:
77 yaml_result = yaml.safe_load(f)
78 _ = (
79 t.cast("dict[str, t.Any]", yaml_result)
80 if yaml_result is not None
81 else {}
82 )
83 self.console.print("[green]✅[/ green] Pre-commit configuration is valid")
84 return True
85 except Exception as e:
86 self.console.print(f"[red]❌[/ red] Configuration validation failed: {e}")
87 return False
89 def backup_config(self) -> Path | None:
90 try:
91 config_file = self.pkg_path / ".pre-commit-config.yaml"
92 if not config_file.exists():
93 return None
94 import time
96 timestamp = int(time.time())
97 backup_file = self.pkg_path / f".pre-commit-config.yaml.backup.{timestamp}"
98 backup_file.write_text(config_file.read_text())
99 self.console.print(
100 f"[cyan]💾[/ cyan] Configuration backed up to {backup_file.name}",
101 )
102 return backup_file
103 except Exception as e:
104 self.console.print(
105 f"[yellow]⚠️[/ yellow] Failed to backup configuration: {e}",
106 )
107 return None
109 def restore_config(self, backup_file: Path) -> bool:
110 try:
111 if not backup_file.exists():
112 self.console.print(
113 f"[red]❌[/ red] Backup file not found: {backup_file}",
114 )
115 return False
116 config_file = self.pkg_path / ".pre-commit-config.yaml"
117 config_file.write_text(backup_file.read_text())
118 self.console.print(
119 f"[green]✅[/ green] Configuration restored from {backup_file.name}",
120 )
121 return True
122 except Exception as e:
123 self.console.print(f"[red]❌[/ red] Failed to restore configuration: {e}")
124 return False
126 def get_config_info(self) -> dict[str, t.Any]:
127 try:
128 config_file = self.pkg_path / ".pre-commit-config.yaml"
129 if not config_file.exists():
130 return {"exists": False}
131 import yaml
133 with config_file.open() as f:
134 yaml_result = yaml.safe_load(f)
135 config_data = (
136 t.cast("dict[str, t.Any]", yaml_result)
137 if isinstance(yaml_result, dict)
138 else {}
139 )
140 repos = config_data.get("repos", [])
141 if not isinstance(repos, list):
142 repos = []
143 hook_count = sum(
144 len(repo.get("hooks", [])) for repo in repos if isinstance(repo, dict)
145 )
146 stat = config_file.stat()
148 return {
149 "exists": True,
150 "file_size": stat.st_size,
151 "modified_time": stat.st_mtime,
152 "repo_count": len([r for r in repos if isinstance(r, dict)]),
153 "hook_count": hook_count,
154 "repos": [
155 {
156 "repo": repo.get("repo", "unknown"),
157 "rev": repo.get("rev", "unknown"),
158 "hooks": len(repo.get("hooks", [])),
159 }
160 for repo in repos
161 if isinstance(repo, dict)
162 ],
163 }
164 except Exception as e:
165 return {"exists": True, "error": str(e)}
167 def update_pyproject_config(self, options: OptionsProtocol) -> bool:
168 try:
169 pyproject_file = self.pkg_path / "pyproject.toml"
170 if not pyproject_file.exists():
171 self.console.print("[yellow]⚠️ No pyproject.toml found[/ yellow]")
172 return False
173 from tomllib import loads
175 from tomli_w import dumps
177 with pyproject_file.open() as f:
178 content = f.read()
179 config = loads(content)
180 if "tool" not in config:
181 config["tool"] = {}
182 if "ruff" not in config["tool"]:
183 config["tool"]["ruff"] = {
184 "target-version": "py313",
185 "line-length": 88,
186 "fix": True,
187 "unsafe-fixes": True,
188 "show-fixes": True,
189 "output-format": "full",
190 }
191 config["tool"]["ruff"]["format"] = {"docstring - code-format": True}
192 config["tool"]["ruff"]["lint"] = {
193 "extend-select": ["C901", "F", "I", "UP"],
194 "ignore": ["E402", "F821"],
195 "fixable": ["ALL"],
196 }
197 if "pytest" not in config["tool"]:
198 config["tool"]["pytest"] = {
199 "ini_options": {
200 "asyncio_mode": "auto",
201 "timeout": 300,
202 "addopts": "- - cov=crackerjack - - cov-report=term",
203 "markers": [
204 "unit: marks test as a unit test",
205 "benchmark: mark test as a benchmark",
206 "integration: marks test as an integration test",
207 "no_leaks: detect asyncio task leaks",
208 ],
209 },
210 }
212 from crackerjack.services.filesystem import FileSystemService
214 content = dumps(config)
215 content = FileSystemService.clean_trailing_whitespace_and_newlines(content)
216 with pyproject_file.open("w") as f:
217 f.write(content)
218 self.console.print(
219 "[green]✅[/ green] pyproject.toml configuration updated"
220 )
221 return True
222 except Exception as e:
223 self.console.print(f"[red]❌[/ red] Failed to update pyproject.toml: {e}")
224 return False
226 def _run_precommit_autoupdate(self) -> bool:
227 import subprocess
229 try:
230 self.console.print("[cyan]🔄[/ cyan] Running pre-commit autoupdate...")
231 result = self._execute_precommit_autoupdate()
233 if result.returncode == 0:
234 self._display_autoupdate_results(result.stdout)
235 return True
236 else:
237 self._handle_autoupdate_error(result.stderr)
238 return False
240 except subprocess.TimeoutExpired:
241 self.console.print("[red]❌[/ red] Pre-commit autoupdate timed out")
242 return False
243 except Exception as e:
244 self.console.print(
245 f"[red]❌[/ red] Failed to run pre-commit autoupdate: {e}"
246 )
247 return False
249 def _execute_precommit_autoupdate(self) -> subprocess.CompletedProcess[str]:
250 return subprocess.run(
251 ["uv", "run", "pre-commit", "autoupdate"],
252 cwd=self.pkg_path,
253 capture_output=True,
254 text=True,
255 timeout=60,
256 )
258 def _display_autoupdate_results(self, stdout: str) -> None:
259 if self._has_updates(stdout):
260 for line in stdout.split("\n"):
261 if self._is_update_line(line):
262 self.console.print(f"[dim] {line.strip()}[/ dim]")
264 def _has_updates(self, stdout: str) -> bool:
265 stdout_lower = stdout.lower()
266 return "updating" in stdout_lower or "updated" in stdout_lower
268 def _is_update_line(self, line: str) -> bool:
269 return "updating" in line.lower() or "- >" in line
271 def _handle_autoupdate_error(self, stderr: str) -> None:
272 if stderr:
273 self.console.print(
274 f"[yellow]Pre-commit autoupdate stderr: [/ yellow] {stderr}"
275 )
277 def _update_dynamic_config_versions(self) -> None:
278 try:
279 self.console.print("[cyan]🔄[/ cyan] Updating dynamic config versions...")
281 version_updates = self._extract_version_updates()
282 if version_updates:
283 self._update_dynamic_config_file(version_updates)
285 except Exception as e:
286 self.console.print(
287 f"[yellow]⚠️[/ yellow] Failed to update dynamic config versions: {e}"
288 )
290 def _extract_version_updates(self) -> dict[str, str]:
291 config_file = self.pkg_path / ".pre-commit-config.yaml"
292 if not config_file.exists():
293 return {}
295 import yaml
297 with config_file.open() as f:
298 config = yaml.safe_load(f)
300 if not config or "repos" not in config:
301 return {}
303 version_updates = {}
304 repos = config.get("repos", []) if isinstance(config, dict) else []
305 for repo in repos:
306 repo_url = repo.get("repo", "")
307 rev = repo.get("rev", "")
308 if repo_url and rev:
309 version_updates[repo_url] = rev
311 return version_updates
313 def _update_dynamic_config_file(self, version_updates: dict[str, str]) -> None:
314 dynamic_config_path = self.pkg_path / "crackerjack" / "dynamic_config.py"
315 if dynamic_config_path.exists():
316 self._apply_version_updates(dynamic_config_path, version_updates)
318 def _apply_version_updates(
319 self, config_path: Path, version_updates: dict[str, str]
320 ) -> None:
321 try:
322 content = config_path.read_text()
323 updated = False
325 for repo_url, new_rev in version_updates.items():
326 import re
328 pattern = rf'("repo": "{re.escape(repo_url)}".*?"rev": )"([^"]+)"'
329 replacement = rf'\1"{new_rev}"'
331 new_content = re.sub(pattern, replacement, content, flags=re.DOTALL)
332 if new_content != content:
333 content = new_content
334 updated = True
335 self.console.print(f"[dim] Updated {repo_url} to {new_rev}[/ dim]")
337 if updated:
338 config_path.write_text(content)
339 self.console.print("[green]✅[/ green] Dynamic config versions updated")
341 except Exception as e:
342 self.console.print(
343 f"[yellow]⚠️[/ yellow] Failed to apply version updates: {e}"
344 )