Coverage for /Users/les/Projects/crackerjack/crackerjack/api.py: 0%
316 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 asyncio
2import typing as t
3from dataclasses import dataclass
4from pathlib import Path
6from rich.console import Console
8from .code_cleaner import CleaningResult, CodeCleaner, PackageCleaningResult
9from .core.workflow_orchestrator import WorkflowOrchestrator
10from .errors import CrackerjackError, ErrorCode
11from .interactive import InteractiveCLI
12from .interactive import WorkflowOptions as InteractiveWorkflowOptions
13from .models.config import WorkflowOptions
16@dataclass
17class QualityCheckResult:
18 success: bool
19 fast_hooks_passed: bool
20 comprehensive_hooks_passed: bool
21 errors: list[str]
22 warnings: list[str]
23 duration: float
26@dataclass
27class TestResult:
28 success: bool
29 passed_count: int
30 failed_count: int
31 coverage_percentage: float
32 duration: float
33 errors: list[str]
36@dataclass
37class PublishResult:
38 success: bool
39 version: str
40 published_to: list[str]
41 errors: list[str]
44class CrackerjackAPI:
45 def __init__(
46 self,
47 project_path: Path | None = None,
48 console: Console | None = None,
49 verbose: bool = False,
50 ) -> None:
51 self.project_path = project_path or Path.cwd()
52 self.console = console or Console()
53 self.verbose = verbose
55 self.orchestrator = WorkflowOrchestrator(
56 console=self.console,
57 pkg_path=self.project_path,
58 verbose=self.verbose,
59 )
61 self.container = self.orchestrator.container
63 self._code_cleaner: CodeCleaner | None = None
64 self._interactive_cli: InteractiveCLI | None = None
66 import logging
68 self.logger = logging.getLogger("crackerjack.api")
70 @property
71 def code_cleaner(self) -> CodeCleaner:
72 if self._code_cleaner is None:
73 self._code_cleaner = CodeCleaner(
74 console=self.console, base_directory=self.project_path
75 )
76 return self._code_cleaner
78 @property
79 def interactive_cli(self) -> InteractiveCLI:
80 if self._interactive_cli is None:
81 self._interactive_cli = InteractiveCLI(console=self.console)
82 return self._interactive_cli
84 def run_quality_checks(
85 self,
86 fast_only: bool = False,
87 autofix: bool = True,
88 ) -> QualityCheckResult:
89 import asyncio
90 import time
92 start_time = time.time()
94 try:
95 self.logger.info("Starting quality checks")
97 options = self._create_options(autofix=autofix, skip_hooks=False)
99 success = asyncio.run(
100 self.orchestrator.pipeline.run_complete_workflow(options),
101 )
103 duration = time.time() - start_time
105 return QualityCheckResult(
106 success=success,
107 fast_hooks_passed=success,
108 comprehensive_hooks_passed=success if not fast_only else True,
109 errors=[] if success else ["Quality checks failed"],
110 warnings=[],
111 duration=duration,
112 )
114 except Exception as e:
115 duration = time.time() - start_time
116 self.logger.exception(f"Quality checks failed: {e}")
118 return QualityCheckResult(
119 success=False,
120 fast_hooks_passed=False,
121 comprehensive_hooks_passed=False,
122 errors=[str(e)],
123 warnings=[],
124 duration=duration,
125 )
127 def clean_code(
128 self,
129 target_dir: Path | None = None,
130 backup: bool = True,
131 safe_mode: bool = True,
132 ) -> list[CleaningResult] | PackageCleaningResult:
133 """Clean code with comprehensive backup protection.
135 Args:
136 target_dir: Directory to clean (defaults to package root)
137 backup: Whether to create backup (deprecated, always True for safety)
138 safe_mode: Use comprehensive backup system (default: True, recommended)
140 Returns:
141 PackageCleaningResult with backup metadata if safe_mode=True,
142 otherwise list[CleaningResult] for legacy compatibility
143 """
144 target_dir = target_dir or self._get_package_root()
145 self.logger.info(f"Cleaning code in {target_dir} (safe_mode={safe_mode})")
147 self._validate_code_before_cleaning(target_dir)
149 if safe_mode:
150 self.console.print(
151 "[green]🛡️ Using safe mode with comprehensive backup protection[/green]"
152 )
153 return self._execute_safe_code_cleaning(target_dir)
154 else:
155 # Note: Legacy mode still uses backup protection for safety
156 self.console.print(
157 "[yellow]⚠️ Legacy mode - backup protection still enabled for safety[/yellow]"
158 )
159 self._notify_backup_status(backup)
160 return self._execute_code_cleaning(target_dir)
162 def _validate_code_before_cleaning(self, target_dir: Path) -> None:
163 todos_found = self._check_for_todos(target_dir)
164 if todos_found:
165 self._handle_todos_found(todos_found, target_dir)
167 def _handle_todos_found(
168 self,
169 todos_found: list[tuple[Path, int, str]],
170 target_dir: Path,
171 ) -> None:
172 todo_count = len(todos_found)
173 self.console.print(f"[red]❌ Found {todo_count} TODO(s) in codebase[/ red]")
174 self.console.print(
175 "[yellow]Please resolve all TODOs before running code cleaning (-x)[/ yellow]",
176 )
178 self._display_todo_summary(todos_found, target_dir, todo_count)
180 raise CrackerjackError(
181 message=f"Found {todo_count} TODO(s) in codebase. Resolve them before cleaning.",
182 error_code=ErrorCode.VALIDATION_ERROR,
183 )
185 def _display_todo_summary(
186 self,
187 todos_found: list[tuple[Path, int, str]],
188 target_dir: Path,
189 todo_count: int,
190 ) -> None:
191 for _i, (file_path, line_no, content) in enumerate(todos_found[:5]):
192 relative_path = file_path.relative_to(target_dir)
193 self.console.print(f" {relative_path}: {line_no}: {content.strip()}")
195 if todo_count > 5:
196 self.console.print(f" ... and {todo_count - 5} more")
198 def _notify_backup_status(self, backup: bool) -> None:
199 if backup:
200 self.console.print("[yellow]Note: Backup files will be created[/ yellow]")
202 def _execute_safe_code_cleaning(self, target_dir: Path) -> PackageCleaningResult:
203 try:
204 result = self.code_cleaner.clean_files_with_backup(target_dir)
205 self._report_safe_cleaning_results(result)
206 return result
207 except Exception as e:
208 self._handle_cleaning_error(e)
210 def _execute_code_cleaning(self, target_dir: Path) -> list[CleaningResult]:
211 try:
212 # Use backup protection by default for safety
213 results = self.code_cleaner.clean_files(target_dir, use_backup=True)
215 # Handle both return types (legacy compatibility)
216 if isinstance(results, list):
217 self._report_cleaning_results(results)
218 else:
219 # PackageCleaningResult from backup mode
220 self._report_safe_cleaning_results(results)
221 results = results.file_results # Extract list for compatibility
223 return results
224 except Exception as e:
225 self._handle_cleaning_error(e)
227 def _report_safe_cleaning_results(self, result: PackageCleaningResult) -> None:
228 if result.overall_success:
229 self.console.print(
230 f"[green]🎉 Package cleaning completed successfully![/green] "
231 f"({result.successful_files}/{result.total_files} files cleaned)"
232 )
233 else:
234 self.console.print(
235 f"[red]❌ Package cleaning failed![/red] "
236 f"({result.failed_files}/{result.total_files} files failed)"
237 )
239 if result.backup_restored:
240 self.console.print(
241 "[yellow]⚠️ Files were automatically restored from backup[/yellow]"
242 )
244 if result.backup_metadata:
245 self.console.print(
246 f"[blue]📦 Backup available at: {result.backup_metadata.backup_directory}[/blue]"
247 )
249 def _report_cleaning_results(self, results: list[CleaningResult]) -> None:
250 successful = sum(1 for r in results if r.success)
251 failed = len(results) - successful
253 if successful > 0:
254 self.console.print(
255 f"[green]✅ Successfully cleaned {successful} files[/ green]",
256 )
257 if failed > 0:
258 self.console.print(f"[red]❌ Failed to clean {failed} files[/ red]")
260 def _handle_cleaning_error(self, error: Exception) -> t.NoReturn:
261 self.logger.error(f"Code cleaning failed: {error}")
262 raise CrackerjackError(
263 message=f"Code cleaning failed: {error}",
264 error_code=ErrorCode.CODE_CLEANING_ERROR,
265 ) from error
267 def run_tests(
268 self,
269 coverage: bool = False,
270 workers: int | None = None,
271 timeout: int | None = None,
272 ) -> TestResult:
273 import time
275 start_time = time.time()
277 try:
278 self.logger.info("Running tests")
280 options = self._create_options(
281 test=True,
282 test_workers=workers or 0,
283 test_timeout=timeout or 0,
284 )
286 success = asyncio.run(
287 self.orchestrator.pipeline.run_complete_workflow(options),
288 )
290 duration = time.time() - start_time
292 return TestResult(
293 success=success,
294 passed_count=self._extract_test_passed_count(),
295 failed_count=self._extract_test_failed_count(),
296 coverage_percentage=self._extract_coverage_percentage(),
297 duration=duration,
298 errors=[] if success else ["Test execution failed"],
299 )
301 except Exception as e:
302 duration = time.time() - start_time
303 self.logger.exception(f"Test execution failed: {e}")
305 return TestResult(
306 success=False,
307 passed_count=0,
308 failed_count=0,
309 coverage_percentage=0.0,
310 duration=duration,
311 errors=[str(e)],
312 )
314 def publish_package(
315 self,
316 version_bump: str | None = None,
317 dry_run: bool = False,
318 ) -> PublishResult:
319 try:
320 self.logger.info(
321 f"Publishing package (version_bump={version_bump}, dry_run={dry_run})",
322 )
324 options = self._create_options(
325 bump=version_bump,
326 publish="pypi" if not dry_run else None,
327 )
329 success = asyncio.run(
330 self.orchestrator.pipeline.run_complete_workflow(options),
331 )
333 return PublishResult(
334 success=success,
335 version=self._extract_current_version(),
336 published_to=["pypi"] if success and not dry_run else [],
337 errors=[] if success else ["Publishing failed"],
338 )
340 except Exception as e:
341 self.logger.exception(f"Package publishing failed: {e}")
343 return PublishResult(
344 success=False,
345 version="",
346 published_to=[],
347 errors=[str(e)],
348 )
350 def run_interactive_workflow(
351 self,
352 options: InteractiveWorkflowOptions | None = None,
353 ) -> bool:
354 options = options or InteractiveWorkflowOptions()
356 self.logger.info("Starting interactive workflow")
358 try:
359 return self.interactive_cli.run_interactive_workflow(options)
360 except Exception as e:
361 self.logger.exception(f"Interactive workflow failed: {e}")
362 self.console.print(f"[red]❌ Interactive workflow failed: {e}[/ red]")
363 return False
365 def create_workflow_options(
366 self,
367 clean: bool = False,
368 test: bool = False,
369 publish: str | None = None,
370 bump: str | None = None,
371 commit: bool = False,
372 create_pr: bool = False,
373 **kwargs: t.Any,
374 ) -> WorkflowOptions:
375 from .models.config import (
376 CleaningConfig,
377 ExecutionConfig,
378 GitConfig,
379 PublishConfig,
380 TestConfig,
381 )
382 from .models.config import (
383 WorkflowOptions as ModelsWorkflowOptions,
384 )
386 verbose = kwargs.pop("verbose", False)
388 options = ModelsWorkflowOptions()
390 if clean:
391 options.cleaning = CleaningConfig(clean=True)
392 if test:
393 options.testing = TestConfig(test=True)
394 if publish or bump:
395 options.publishing = PublishConfig(publish=publish, bump=bump)
396 if commit or create_pr:
397 options.git = GitConfig(commit=commit, create_pr=create_pr)
398 if verbose:
399 options.execution = ExecutionConfig(verbose=True)
401 for key, value in kwargs.items():
402 if not hasattr(options, key):
403 setattr(options, key, value)
405 return options
407 def get_project_info(self) -> dict[str, t.Any]:
408 try:
409 pyproject_path = self.project_path / "pyproject.toml"
410 setup_py_path = self.project_path / "setup.py"
412 is_python_project = pyproject_path.exists() or setup_py_path.exists()
414 git_dir = self.project_path / ".git"
415 is_git_repo = git_dir.exists()
417 python_files = list(self.project_path.rglob("*.py"))
419 return {
420 "project_path": str(self.project_path),
421 "is_python_project": is_python_project,
422 "is_git_repo": is_git_repo,
423 "python_files_count": len(python_files),
424 "has_pyproject_toml": pyproject_path.exists(),
425 "has_setup_py": setup_py_path.exists(),
426 "has_requirements_txt": (
427 self.project_path / "requirements.txt"
428 ).exists(),
429 "has_tests": any(self.project_path.rglob("test *.py")),
430 }
432 except Exception as e:
433 self.logger.exception(f"Failed to get project info: {e}")
434 return {"error": str(e)}
436 def _create_options(self, **kwargs: t.Any) -> t.Any:
437 class Options:
438 def __init__(self, **kwargs: t.Any) -> None:
439 self.commit = False
440 self.interactive = False
441 self.no_config_updates = False
442 self.verbose = False
443 self.clean = False
444 self.test = False
445 self.autofix = True
446 self.publish = None
447 self.bump = None
448 self.test_workers = 0
449 self.test_timeout = 0
451 for key, value in kwargs.items():
452 setattr(self, key, value)
454 return Options(**kwargs)
456 def _extract_test_passed_count(self) -> int:
457 try:
458 test_manager = self.orchestrator.phases.test_manager
459 if hasattr(test_manager, "get_test_results"):
460 results = t.cast(t.Any, test_manager).get_test_results()
461 return getattr(results, "passed_count", 0)
462 return 0
463 except Exception:
464 return 0
466 def _extract_test_failed_count(self) -> int:
467 try:
468 test_manager = self.orchestrator.phases.test_manager
469 if hasattr(test_manager, "get_test_results"):
470 results = t.cast(t.Any, test_manager).get_test_results()
471 return getattr(results, "failed_count", 0)
472 return 0
473 except Exception:
474 return 0
476 def _extract_coverage_percentage(self) -> float:
477 try:
478 test_manager = self.orchestrator.phases.test_manager
479 if hasattr(test_manager, "get_test_results"):
480 results = t.cast(t.Any, test_manager).get_test_results()
481 return getattr(results, "coverage_percentage", 0.0)
482 return 0.0
483 except Exception:
484 return 0.0
486 def _extract_current_version(self) -> str:
487 try:
488 pyproject_path = self.project_path / "pyproject.toml"
489 if pyproject_path.exists():
490 import tomllib
492 with pyproject_path.open("rb") as f:
493 data = tomllib.load(f)
495 if "project" in data and "version" in data["project"]:
496 return data["project"]["version"]
497 if (
498 "tool" in data
499 and "poetry" in data["tool"]
500 and "version" in data["tool"]["poetry"]
501 ):
502 return data["tool"]["poetry"]["version"]
504 import importlib.metadata
506 try:
507 return importlib.metadata.version("crackerjack")
508 except importlib.metadata.PackageNotFoundError:
509 pass
511 return "unknown"
512 except Exception:
513 return "unknown"
515 def _check_for_todos(self, target_dir: Path) -> list[tuple[Path, int, str]]:
516 import re
518 task_pattern = re.compile(r"#.*?TODO.*", re.IGNORECASE)
519 python_files = self._get_python_files_for_todo_check(target_dir)
520 return self._scan_files_for_todos(python_files, task_pattern)
522 def _get_python_files_for_todo_check(self, target_dir: Path) -> list[Path]:
523 python_files: list[Path] = []
524 ignore_patterns = self._get_ignore_patterns()
526 for py_file in target_dir.rglob("*.py"):
527 if not self._should_skip_file(py_file, ignore_patterns):
528 python_files.append(py_file)
530 return python_files
532 def _get_ignore_patterns(self) -> set[str]:
533 return {
534 "__pycache__",
535 ".git",
536 ".venv",
537 "site-packages",
538 ".pytest_cache",
539 "build",
540 "dist",
541 "tests",
542 "test",
543 "examples",
544 "example",
545 }
547 def _should_skip_file(self, py_file: Path, ignore_patterns: set[str]) -> bool:
548 if py_file.name.startswith("."):
549 return True
551 return any(parent.name in ignore_patterns for parent in py_file.parents)
553 def _scan_files_for_todos(
554 self,
555 python_files: list[Path],
556 todo_pattern: t.Any,
557 ) -> list[tuple[Path, int, str]]:
558 todos_found: list[tuple[Path, int, str]] = []
560 for file_path in python_files:
561 file_todos = self._scan_single_file_for_todos(file_path, todo_pattern)
562 todos_found.extend(file_todos)
564 return todos_found
566 def _scan_single_file_for_todos(
567 self,
568 file_path: Path,
569 todo_pattern: t.Any,
570 ) -> list[tuple[Path, int, str]]:
571 todos: list[tuple[Path, int, str]] = []
572 from contextlib import suppress
574 with suppress(UnicodeDecodeError, PermissionError):
575 with file_path.open() as f:
576 for line_no, line in enumerate(f, 1):
577 if todo_pattern.search(line):
578 todos.append((file_path, line_no, line))
580 return todos
582 def _get_package_root(self) -> Path:
583 package_name = self._read_package_name_from_pyproject()
584 if package_name:
585 package_dir = self._find_package_directory_by_name(package_name)
586 if package_dir:
587 return package_dir
589 fallback_dir = self._find_fallback_package_directory()
590 return fallback_dir or self.project_path
592 def _read_package_name_from_pyproject(self) -> str | None:
593 pyproject_path = self.project_path / "pyproject.toml"
594 if not pyproject_path.exists():
595 return None
597 from contextlib import suppress
599 with suppress(Exception):
600 import tomllib
602 with pyproject_path.open("rb") as f:
603 data = tomllib.load(f)
605 if "project" in data and "name" in data["project"]:
606 return data["project"]["name"]
608 return None
610 def _find_package_directory_by_name(self, package_name: str) -> Path | None:
611 package_dir = self.project_path / package_name
612 if package_dir.exists() and package_dir.is_dir():
613 return package_dir
614 return None
616 def _find_fallback_package_directory(self) -> Path | None:
617 for possible_name in ("src", self.project_path.name):
618 package_dir = self.project_path / possible_name
619 if self._is_valid_python_package_directory(package_dir):
620 return package_dir
621 return None
623 def _is_valid_python_package_directory(self, directory: Path) -> bool:
624 if not (directory.exists() and directory.is_dir()):
625 return False
626 return any(directory.glob("*.py"))
629def run_quality_checks(
630 project_path: Path | None = None,
631 fast_only: bool = False,
632 autofix: bool = True,
633) -> QualityCheckResult:
634 return CrackerjackAPI(project_path=project_path).run_quality_checks(
635 fast_only=fast_only,
636 autofix=autofix,
637 )
640def clean_code(
641 project_path: Path | None = None,
642 backup: bool = True,
643 safe_mode: bool = True,
644) -> list[CleaningResult] | PackageCleaningResult:
645 return CrackerjackAPI(project_path=project_path).clean_code(
646 backup=backup, safe_mode=safe_mode
647 )
650def run_tests(project_path: Path | None = None, coverage: bool = False) -> TestResult:
651 return CrackerjackAPI(project_path=project_path).run_tests(coverage=coverage)
654def publish_package(
655 project_path: Path | None = None,
656 version_bump: str | None = None,
657 dry_run: bool = False,
658) -> PublishResult:
659 return CrackerjackAPI(project_path=project_path).publish_package(
660 version_bump=version_bump,
661 dry_run=dry_run,
662 )