Coverage for /Users/les/Projects/crackerjack/crackerjack/code_cleaner.py: 0%
558 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 ast
2import re
3import typing as t
4from dataclasses import dataclass
5from enum import Enum
6from pathlib import Path
7from typing import Protocol
9from pydantic import BaseModel, ConfigDict
10from rich.console import Console
12from .errors import ErrorCode, ExecutionError
13from .services.backup_service import BackupMetadata, PackageBackupService
14from .services.secure_path_utils import (
15 AtomicFileOperations,
16 SecurePathValidator,
17)
18from .services.security_logger import (
19 SecurityEventLevel,
20 SecurityEventType,
21 get_security_logger,
22)
25class CompiledPatterns:
26 def __init__(self) -> None:
27 self.docstring_patterns = [
28 re.compile(r'^\s*""".*?"""\s*$', re.MULTILINE | re.DOTALL),
29 re.compile(r"^\s*'''.*?'''\s*$", re.MULTILINE | re.DOTALL),
30 ]
32 self.operator_patterns: list[tuple[re.Pattern[str], str]] = []
34 self.spacing_patterns = [
35 (re.compile(r", ([^ \n])"), r", \1"),
36 (re.compile(r": ([^ \n: ])"), r": \1"),
37 (re.compile(r" {2,}"), " "),
38 ]
40 self.preserved_comment_pattern = re.compile(
41 r"#.*?(?: coding: | encoding: | type: | noqa | pragma)"
42 )
44 def apply_docstring_patterns(self, code: str) -> str:
45 result = code
46 for pattern in self.docstring_patterns:
47 result = pattern.sub("", result)
48 return result
50 def apply_formatting_patterns(self, content: str) -> str:
51 for pattern, replacement in self.operator_patterns:
52 content = pattern.sub(replacement, content)
54 for pattern, replacement in self.spacing_patterns:
55 content = pattern.sub(replacement, content)
57 return content
59 def has_preserved_comment(self, line: str) -> bool:
60 return (
61 line.strip().startswith("#! /")
62 or self.preserved_comment_pattern.search(line) is not None
63 )
66_compiled_patterns = CompiledPatterns()
69class CleaningStepResult(Enum):
70 SUCCESS = "success"
71 FAILED = "failed"
72 SKIPPED = "skipped"
75@dataclass
76class CleaningResult:
77 file_path: Path
78 success: bool
79 steps_completed: list[str]
80 steps_failed: list[str]
81 warnings: list[str]
82 original_size: int
83 cleaned_size: int
84 backup_metadata: BackupMetadata | None = None
87@dataclass
88class PackageCleaningResult:
89 total_files: int
90 successful_files: int
91 failed_files: int
92 file_results: list[CleaningResult]
93 backup_metadata: BackupMetadata | None
94 backup_restored: bool = False
95 overall_success: bool = False
98class FileProcessorProtocol(Protocol):
99 def read_file_safely(self, file_path: Path) -> str: ...
100 def write_file_safely(self, file_path: Path, content: str) -> None: ...
101 def backup_file(self, file_path: Path) -> Path: ...
104class CleaningStepProtocol(Protocol):
105 def __call__(self, code: str, file_path: Path) -> str: ...
107 @property
108 def name(self) -> str: ...
111class ErrorHandlerProtocol(Protocol):
112 def handle_file_error(
113 self,
114 file_path: Path,
115 error: Exception,
116 step: str,
117 ) -> None: ...
118 def log_cleaning_result(self, result: CleaningResult) -> None: ...
121class FileProcessor(BaseModel):
122 model_config = ConfigDict(arbitrary_types_allowed=True, extra="allow")
124 console: Console
125 logger: t.Any = None
126 base_directory: Path | None = None
127 security_logger: t.Any = None
129 def model_post_init(self, _: t.Any) -> None:
130 if self.logger is None:
131 import logging
133 self.logger = logging.getLogger("crackerjack.code_cleaner.file_processor")
135 if self.security_logger is None:
136 self.security_logger = get_security_logger()
138 def read_file_safely(self, file_path: Path) -> str:
139 validated_path = SecurePathValidator.validate_file_path(
140 file_path, self.base_directory
141 )
142 SecurePathValidator.validate_file_size(validated_path)
144 self.security_logger.log_security_event(
145 SecurityEventType.FILE_CLEANED,
146 SecurityEventLevel.LOW,
147 f"Reading file for cleaning: {validated_path}",
148 file_path=validated_path,
149 )
151 try:
152 return validated_path.read_text(encoding="utf-8")
154 except UnicodeDecodeError:
155 for encoding in ("latin1", "cp1252"):
156 try:
157 content = validated_path.read_text(encoding=encoding)
158 self.logger.warning(
159 f"File {validated_path} read with {encoding} encoding",
160 )
161 return content
162 except UnicodeDecodeError:
163 continue
165 self.security_logger.log_validation_failed(
166 "encoding",
167 file_path,
168 "Could not decode file with any supported encoding",
169 )
171 raise ExecutionError(
172 message=f"Could not decode file {file_path}",
173 error_code=ErrorCode.FILE_READ_ERROR,
174 )
176 except ExecutionError:
177 raise
179 except Exception as e:
180 self.security_logger.log_validation_failed(
181 "file_read", file_path, f"Unexpected error during file read: {e}"
182 )
184 raise ExecutionError(
185 message=f"Failed to read file {file_path}: {e}",
186 error_code=ErrorCode.FILE_READ_ERROR,
187 ) from e
189 def write_file_safely(self, file_path: Path, content: str) -> None:
190 try:
191 AtomicFileOperations.atomic_write(file_path, content, self.base_directory)
193 self.security_logger.log_atomic_operation("write", file_path, True)
195 except ExecutionError:
196 self.security_logger.log_atomic_operation("write", file_path, False)
197 raise
199 except Exception as e:
200 self.security_logger.log_atomic_operation(
201 "write", file_path, False, error=str(e)
202 )
204 raise ExecutionError(
205 message=f"Failed to write file {file_path}: {e}",
206 error_code=ErrorCode.FILE_WRITE_ERROR,
207 ) from e
209 def backup_file(self, file_path: Path) -> Path:
210 try:
211 backup_path = AtomicFileOperations.atomic_backup_and_write(
212 file_path, file_path.read_bytes(), self.base_directory
213 )
215 self.security_logger.log_backup_created(file_path, backup_path)
217 return backup_path
219 except ExecutionError:
220 raise
222 except Exception as e:
223 self.security_logger.log_validation_failed(
224 "backup_creation", file_path, f"Backup creation failed: {e}"
225 )
227 raise ExecutionError(
228 message=f"Failed to create backup for {file_path}: {e}",
229 error_code=ErrorCode.FILE_WRITE_ERROR,
230 ) from e
233class CleaningErrorHandler(BaseModel):
234 model_config = ConfigDict(arbitrary_types_allowed=True)
236 console: Console
237 logger: t.Any = None
239 def model_post_init(self, _: t.Any) -> None:
240 if self.logger is None:
241 import logging
243 self.logger = logging.getLogger("crackerjack.code_cleaner.error_handler")
245 def handle_file_error(self, file_path: Path, error: Exception, step: str) -> None:
246 self.console.print(
247 f"[bold bright_yellow]⚠️ Warning: {step} failed for {file_path}: {error}[/ bold bright_yellow]",
248 )
250 self.logger.warning(
251 "Cleaning step failed",
252 extra={
253 "file_path": str(file_path),
254 "step": step,
255 "error": str(error),
256 "error_type": type(error).__name__,
257 },
258 )
260 def log_cleaning_result(self, result: CleaningResult) -> None:
261 if result.success:
262 self.console.print(
263 f"[green]✅ Cleaned {result.file_path}[/ green] "
264 f"({result.original_size} → {result.cleaned_size} bytes)",
265 )
266 else:
267 self.console.print(
268 f"[red]❌ Failed to clean {result.file_path}[/ red] "
269 f"({len(result.steps_failed)} steps failed)",
270 )
272 if result.warnings:
273 for warning in result.warnings:
274 self.console.print(f"[yellow]⚠️ {warning}[/ yellow]")
276 self.logger.info(
277 "File cleaning completed",
278 extra={
279 "file_path": str(result.file_path),
280 "success": result.success,
281 "steps_completed": result.steps_completed,
282 "steps_failed": result.steps_failed,
283 "original_size": result.original_size,
284 "cleaned_size": result.cleaned_size,
285 },
286 )
289class CleaningPipeline(BaseModel):
290 model_config = ConfigDict(arbitrary_types_allowed=True)
292 file_processor: t.Any
293 error_handler: t.Any
294 console: Console
295 logger: t.Any = None
297 def model_post_init(self, _: t.Any) -> None:
298 if self.logger is None:
299 import logging
301 self.logger = logging.getLogger("crackerjack.code_cleaner.pipeline")
303 def clean_file(
304 self,
305 file_path: Path,
306 cleaning_steps: list[CleaningStepProtocol],
307 ) -> CleaningResult:
308 self.logger.info(f"Starting clean_file for {file_path}")
309 try:
310 original_code = self.file_processor.read_file_safely(file_path)
311 original_size = len(original_code.encode("utf-8"))
313 result = self._apply_cleaning_pipeline(
314 original_code,
315 file_path,
316 cleaning_steps,
317 )
319 cleaned_size = original_size
320 if result.success and result.cleaned_code != original_code:
321 self.file_processor.write_file_safely(file_path, result.cleaned_code)
322 cleaned_size = len(result.cleaned_code.encode("utf-8"))
324 cleaning_result = CleaningResult(
325 file_path=file_path,
326 success=result.success,
327 steps_completed=result.steps_completed,
328 steps_failed=result.steps_failed,
329 warnings=result.warnings,
330 original_size=original_size,
331 cleaned_size=cleaned_size,
332 )
334 self.error_handler.log_cleaning_result(cleaning_result)
335 return cleaning_result
337 except Exception as e:
338 self.error_handler.handle_file_error(file_path, e, "file_processing")
339 return CleaningResult(
340 file_path=file_path,
341 success=False,
342 steps_completed=[],
343 steps_failed=["file_processing"],
344 warnings=[],
345 original_size=0,
346 cleaned_size=0,
347 )
349 @dataclass
350 class PipelineResult:
351 cleaned_code: str
352 success: bool
353 steps_completed: list[str]
354 steps_failed: list[str]
355 warnings: list[str]
357 def _apply_cleaning_pipeline(
358 self,
359 code: str,
360 file_path: Path,
361 cleaning_steps: list[CleaningStepProtocol],
362 ) -> PipelineResult:
363 current_code = code
364 steps_completed: list[str] = []
365 steps_failed: list[str] = []
366 warnings: list[str] = []
367 overall_success = True
369 for step in cleaning_steps:
370 try:
371 step_result = step(current_code, file_path)
372 current_code = step_result
373 steps_completed.append(step.name)
375 self.logger.debug(
376 "Cleaning step completed",
377 extra={"step": step.name, "file_path": str(file_path)},
378 )
380 except Exception as e:
381 self.error_handler.handle_file_error(file_path, e, step.name)
382 steps_failed.append(step.name)
383 warnings.append(f"{step.name} failed: {e}")
385 self.logger.warning(
386 "Cleaning step failed, continuing with original code",
387 extra={
388 "step": step.name,
389 "file_path": str(file_path),
390 "error": str(e),
391 },
392 )
394 if steps_failed:
395 success_ratio = len(steps_completed) / (
396 len(steps_completed) + len(steps_failed)
397 )
398 overall_success = success_ratio >= 0.7
400 return self.PipelineResult(
401 cleaned_code=current_code,
402 success=overall_success,
403 steps_completed=steps_completed,
404 steps_failed=steps_failed,
405 warnings=warnings,
406 )
409class CodeCleaner(BaseModel):
410 model_config = ConfigDict(arbitrary_types_allowed=True, extra="allow")
412 console: Console
413 file_processor: t.Any = None
414 error_handler: t.Any = None
415 pipeline: t.Any = None
416 logger: t.Any = None
417 base_directory: Path | None = None
418 security_logger: t.Any = None
419 backup_service: t.Any = None
421 def model_post_init(self, _: t.Any) -> None:
422 if self.logger is None:
423 import logging
425 self.logger = logging.getLogger("crackerjack.code_cleaner")
427 if self.base_directory is None:
428 self.base_directory = Path.cwd()
430 if self.file_processor is None:
431 self.file_processor = FileProcessor(
432 console=self.console, base_directory=self.base_directory
433 )
435 if self.error_handler is None:
436 self.error_handler = CleaningErrorHandler(console=self.console)
438 if self.pipeline is None:
439 self.pipeline = CleaningPipeline(
440 file_processor=self.file_processor,
441 error_handler=self.error_handler,
442 console=self.console,
443 )
445 if self.security_logger is None:
446 self.security_logger = get_security_logger()
448 if self.backup_service is None:
449 self.backup_service = PackageBackupService()
451 def clean_file(self, file_path: Path) -> CleaningResult:
452 cleaning_steps = [
453 self._create_line_comment_step(),
454 self._create_docstring_step(),
455 self._create_whitespace_step(),
456 self._create_formatting_step(),
457 ]
459 return self.pipeline.clean_file(file_path, cleaning_steps)
461 def clean_files(
462 self, pkg_dir: Path | None = None, use_backup: bool = True
463 ) -> list[CleaningResult] | PackageCleaningResult:
464 """Clean package files with optional backup protection.
466 Args:
467 pkg_dir: Package directory to clean (defaults to current directory)
468 use_backup: Whether to use backup protection (default: True for safety)
470 Returns:
471 PackageCleaningResult with backup protection (default), list[CleaningResult] if use_backup=False (legacy)
472 """
473 if use_backup:
474 # Use the comprehensive backup system for maximum safety
475 package_result = self.clean_files_with_backup(pkg_dir)
476 self.logger.info(
477 f"Package cleaning with backup completed: "
478 f"success={package_result.overall_success}, "
479 f"restored={package_result.backup_restored}"
480 )
481 return package_result
483 # Legacy non-backup mode (deprecated, kept for compatibility)
484 self.console.print(
485 "[yellow]⚠️ WARNING: Running without backup protection. "
486 "Consider using use_backup=True for safety.[/yellow]"
487 )
489 if pkg_dir is None:
490 pkg_dir = Path.cwd()
492 python_files = list(pkg_dir.rglob("*.py"))
494 files_to_process = [
495 file_path
496 for file_path in python_files
497 if self.should_process_file(file_path)
498 ]
500 results: list[CleaningResult] = []
501 self.logger.info(f"Starting clean_files for {len(files_to_process)} files")
503 cleaning_steps = [
504 self._create_line_comment_step(),
505 self._create_docstring_step(),
506 self._create_whitespace_step(),
507 self._create_formatting_step(),
508 ]
510 for file_path in files_to_process:
511 result = self.pipeline.clean_file(file_path, cleaning_steps)
512 results.append(result)
514 return results
516 def clean_files_with_backup(
517 self, pkg_dir: Path | None = None
518 ) -> PackageCleaningResult:
519 validated_pkg_dir = self._prepare_package_directory(pkg_dir)
521 self.logger.info(
522 f"Starting safe package cleaning with backup: {validated_pkg_dir}"
523 )
524 self.console.print(
525 "[cyan]🛡️ Starting package cleaning with backup protection...[/cyan]"
526 )
528 backup_metadata: BackupMetadata | None = None
530 try:
531 backup_metadata = self._create_backup(validated_pkg_dir)
532 files_to_process = self._find_files_to_process(validated_pkg_dir)
534 if not files_to_process:
535 return self._handle_no_files_to_process(backup_metadata)
537 cleaning_result = self._execute_cleaning_with_backup(
538 files_to_process, backup_metadata
539 )
541 return self._finalize_cleaning_result(cleaning_result, backup_metadata)
543 except Exception as e:
544 return self._handle_critical_error(e, backup_metadata)
546 def _prepare_package_directory(self, pkg_dir: Path | None) -> Path:
547 if pkg_dir is None:
548 pkg_dir = Path.cwd()
550 return SecurePathValidator.validate_file_path(pkg_dir, self.base_directory)
552 def _create_backup(self, validated_pkg_dir: Path) -> BackupMetadata:
553 self.console.print(
554 "[yellow]📦 Creating backup of all package files...[/yellow]"
555 )
557 backup_metadata = self.backup_service.create_package_backup(
558 validated_pkg_dir, self.base_directory
559 )
561 self.console.print(
562 f"[green]✅ Backup created: {backup_metadata.backup_id}[/green] "
563 f"({backup_metadata.total_files} files, {backup_metadata.total_size} bytes)"
564 )
566 return backup_metadata
568 def _find_files_to_process(self, validated_pkg_dir: Path) -> list[Path]:
569 python_files = list(validated_pkg_dir.rglob("*.py"))
570 return [
571 file_path
572 for file_path in python_files
573 if self.should_process_file(file_path)
574 ]
576 def _handle_no_files_to_process(
577 self, backup_metadata: BackupMetadata
578 ) -> PackageCleaningResult:
579 self.console.print("[yellow]⚠️ No files found to process[/yellow]")
580 self.backup_service.cleanup_backup(backup_metadata)
582 return PackageCleaningResult(
583 total_files=0,
584 successful_files=0,
585 failed_files=0,
586 file_results=[],
587 backup_metadata=None,
588 backup_restored=False,
589 overall_success=True,
590 )
592 def _execute_cleaning_with_backup(
593 self, files_to_process: list[Path], backup_metadata: BackupMetadata
594 ) -> dict[str, t.Any]:
595 self.console.print(f"[cyan]🧹 Cleaning {len(files_to_process)} files...[/cyan]")
597 cleaning_steps = [
598 self._create_line_comment_step(),
599 self._create_docstring_step(),
600 self._create_whitespace_step(),
601 self._create_formatting_step(),
602 ]
604 file_results: list[CleaningResult] = []
605 cleaning_errors: list[Exception] = []
607 for file_path in files_to_process:
608 try:
609 result = self.pipeline.clean_file(file_path, cleaning_steps)
610 result.backup_metadata = backup_metadata
611 file_results.append(result)
613 if not result.success:
614 cleaning_errors.append(
615 ExecutionError(
616 message=f"Cleaning failed for {file_path}: {result.steps_failed}",
617 error_code=ErrorCode.CODE_CLEANING_ERROR,
618 )
619 )
620 except Exception as e:
621 cleaning_errors.append(e)
622 file_results.append(
623 CleaningResult(
624 file_path=file_path,
625 success=False,
626 steps_completed=[],
627 steps_failed=["file_processing"],
628 warnings=[f"Exception during cleaning: {e}"],
629 original_size=0,
630 cleaned_size=0,
631 backup_metadata=backup_metadata,
632 )
633 )
635 return {
636 "file_results": file_results,
637 "cleaning_errors": cleaning_errors,
638 "files_to_process": files_to_process,
639 }
641 def _finalize_cleaning_result(
642 self, cleaning_result: dict[str, t.Any], backup_metadata: BackupMetadata
643 ) -> PackageCleaningResult:
644 file_results = cleaning_result["file_results"]
645 cleaning_errors = cleaning_result["cleaning_errors"]
646 files_to_process = cleaning_result["files_to_process"]
648 successful_files = sum(1 for result in file_results if result.success)
649 failed_files = len(file_results) - successful_files
651 if cleaning_errors or failed_files > 0:
652 return self._handle_cleaning_failure(
653 backup_metadata,
654 file_results,
655 files_to_process,
656 successful_files,
657 failed_files,
658 cleaning_errors,
659 )
661 return self._handle_cleaning_success(
662 backup_metadata, file_results, files_to_process, successful_files
663 )
665 def _handle_cleaning_failure(
666 self,
667 backup_metadata: BackupMetadata,
668 file_results: list[CleaningResult],
669 files_to_process: list[Path],
670 successful_files: int,
671 failed_files: int,
672 cleaning_errors: list[Exception],
673 ) -> PackageCleaningResult:
674 self.console.print(
675 f"[red]❌ Cleaning failed ({failed_files} files failed). "
676 f"Restoring from backup...[/red]"
677 )
679 self.logger.error(
680 f"Package cleaning failed with {len(cleaning_errors)} errors, "
681 f"restoring from backup {backup_metadata.backup_id}"
682 )
684 self.backup_service.restore_from_backup(backup_metadata, self.base_directory)
686 self.console.print("[green]✅ Files restored from backup successfully[/green]")
688 return PackageCleaningResult(
689 total_files=len(files_to_process),
690 successful_files=successful_files,
691 failed_files=failed_files,
692 file_results=file_results,
693 backup_metadata=backup_metadata,
694 backup_restored=True,
695 overall_success=False,
696 )
698 def _handle_cleaning_success(
699 self,
700 backup_metadata: BackupMetadata,
701 file_results: list[CleaningResult],
702 files_to_process: list[Path],
703 successful_files: int,
704 ) -> PackageCleaningResult:
705 self.console.print(
706 f"[green]✅ Package cleaning completed successfully![/green] "
707 f"({successful_files} files cleaned)"
708 )
710 self.backup_service.cleanup_backup(backup_metadata)
712 return PackageCleaningResult(
713 total_files=len(files_to_process),
714 successful_files=successful_files,
715 failed_files=0,
716 file_results=file_results,
717 backup_metadata=None,
718 backup_restored=False,
719 overall_success=True,
720 )
722 def _handle_critical_error(
723 self, error: Exception, backup_metadata: BackupMetadata | None
724 ) -> PackageCleaningResult:
725 self.logger.error(f"Critical error during package cleaning: {error}")
726 self.console.print(f"[red]💥 Critical error: {error}[/red]")
728 backup_restored = False
730 if backup_metadata:
731 backup_restored = self._attempt_emergency_restoration(backup_metadata)
733 return PackageCleaningResult(
734 total_files=0,
735 successful_files=0,
736 failed_files=0,
737 file_results=[],
738 backup_metadata=backup_metadata,
739 backup_restored=backup_restored,
740 overall_success=False,
741 )
743 def _attempt_emergency_restoration(self, backup_metadata: BackupMetadata) -> bool:
744 try:
745 self.console.print(
746 "[yellow]🔄 Attempting emergency restoration...[/yellow]"
747 )
748 self.backup_service.restore_from_backup(
749 backup_metadata, self.base_directory
750 )
751 self.console.print("[green]✅ Emergency restoration completed[/green]")
752 return True
754 except Exception as restore_error:
755 self.logger.error(f"Emergency restoration failed: {restore_error}")
756 self.console.print(
757 f"[red]💥 Emergency restoration failed: {restore_error}[/red]\n"
758 f"[yellow]⚠️ Manual restoration may be needed from: "
759 f"{backup_metadata.backup_directory}[/yellow]"
760 )
761 return False
763 def restore_from_backup_metadata(self, backup_metadata: BackupMetadata) -> None:
764 """Manually restore from backup metadata.
766 Args:
767 backup_metadata: Backup metadata containing restoration information
768 """
769 self.console.print(
770 f"[yellow]🔄 Manually restoring from backup: {backup_metadata.backup_id}[/yellow]"
771 )
773 self.backup_service.restore_from_backup(backup_metadata, self.base_directory)
775 self.console.print(
776 f"[green]✅ Manual restoration completed from backup: "
777 f"{backup_metadata.backup_id}[/green]"
778 )
780 def create_emergency_backup(self, pkg_dir: Path | None = None) -> BackupMetadata:
781 """Create an emergency backup before potentially risky operations.
783 Args:
784 pkg_dir: Package directory to backup (defaults to current directory)
786 Returns:
787 BackupMetadata for the created backup
788 """
789 validated_pkg_dir = self._prepare_package_directory(pkg_dir)
791 self.console.print(
792 "[cyan]🛡️ Creating emergency backup before risky operation...[/cyan]"
793 )
795 backup_metadata = self._create_backup(validated_pkg_dir)
797 self.console.print(
798 f"[green]✅ Emergency backup created: {backup_metadata.backup_id}[/green]"
799 )
801 return backup_metadata
803 def restore_emergency_backup(self, backup_metadata: BackupMetadata) -> bool:
804 """Restore from an emergency backup with enhanced error handling.
806 Args:
807 backup_metadata: Backup metadata for restoration
809 Returns:
810 True if restoration succeeded, False otherwise
811 """
812 try:
813 self.console.print(
814 f"[yellow]🔄 Restoring emergency backup: {backup_metadata.backup_id}[/yellow]"
815 )
817 self.backup_service.restore_from_backup(
818 backup_metadata, self.base_directory
819 )
821 self.console.print(
822 f"[green]✅ Emergency backup restored successfully: {backup_metadata.backup_id}[/green]"
823 )
825 return True
827 except Exception as e:
828 self.logger.error(f"Emergency backup restoration failed: {e}")
829 self.console.print(
830 f"[red]💥 Emergency backup restoration failed: {e}[/red]\n"
831 f"[yellow]⚠️ Manual intervention required. Backup location: "
832 f"{backup_metadata.backup_directory}[/yellow]"
833 )
835 return False
837 def verify_backup_integrity(self, backup_metadata: BackupMetadata) -> bool:
838 """Verify the integrity of a backup without restoring it.
840 Args:
841 backup_metadata: Backup metadata to verify
843 Returns:
844 True if backup is valid and can be restored, False otherwise
845 """
846 try:
847 validation_result = self.backup_service._validate_backup(backup_metadata)
849 if validation_result.is_valid:
850 self.console.print(
851 f"[green]✅ Backup verification passed: {backup_metadata.backup_id}[/green] "
852 f"({validation_result.total_validated} files verified)"
853 )
854 return True
855 else:
856 self.console.print(
857 f"[red]❌ Backup verification failed: {backup_metadata.backup_id}[/red]"
858 )
860 for error in validation_result.validation_errors[
861 :3
862 ]: # Show first 3 errors
863 self.console.print(f"[red] • {error}[/red]")
865 if len(validation_result.validation_errors) > 3:
866 remaining = len(validation_result.validation_errors) - 3
867 self.console.print(f"[red] ... and {remaining} more errors[/red]")
869 return False
871 except Exception as e:
872 self.logger.error(f"Backup verification failed with exception: {e}")
873 self.console.print(f"[red]💥 Backup verification error: {e}[/red]")
874 return False
876 def list_available_backups(self) -> list[Path]:
877 """List all available backup directories.
879 Returns:
880 List of backup directory paths
881 """
882 if (
883 not self.backup_service.backup_root
884 or not self.backup_service.backup_root.exists()
885 ):
886 self.console.print("[yellow]⚠️ No backup root directory found[/yellow]")
887 return []
889 try:
890 backup_dirs = [
891 path
892 for path in self.backup_service.backup_root.iterdir()
893 if path.is_dir() and path.name.startswith("backup_")
894 ]
896 if backup_dirs:
897 self.console.print(
898 f"[cyan]📦 Found {len(backup_dirs)} available backups:[/cyan]"
899 )
900 for backup_dir in sorted(backup_dirs):
901 self.console.print(f" • {backup_dir.name}")
902 else:
903 self.console.print("[yellow]⚠️ No backups found[/yellow]")
905 return backup_dirs
907 except Exception as e:
908 self.logger.error(f"Failed to list backups: {e}")
909 self.console.print(f"[red]💥 Error listing backups: {e}[/red]")
910 return []
912 def should_process_file(self, file_path: Path) -> bool:
913 try:
914 validated_path = SecurePathValidator.validate_file_path(
915 file_path, self.base_directory
916 )
918 SecurePathValidator.validate_file_size(validated_path)
920 ignore_patterns = {
921 "__pycache__",
922 ".git",
923 ".venv",
924 "site-packages",
925 ".pytest_cache",
926 "build",
927 "dist",
928 "tests",
929 "test",
930 "examples",
931 "example",
932 }
934 for parent in validated_path.parents:
935 if parent.name in ignore_patterns:
936 return False
938 should_process = not (
939 validated_path.name.startswith(".") or validated_path.suffix != ".py"
940 )
942 if should_process:
943 self.security_logger.log_security_event(
944 SecurityEventType.FILE_CLEANED,
945 SecurityEventLevel.LOW,
946 f"File approved for processing: {validated_path}",
947 file_path=validated_path,
948 )
950 return should_process
952 except ExecutionError as e:
953 self.security_logger.log_validation_failed(
954 "file_processing_check",
955 file_path,
956 f"File failed security validation: {e}",
957 )
959 return False
961 except Exception as e:
962 self.logger.warning(f"Unexpected error checking file {file_path}: {e}")
963 return False
965 def _create_line_comment_step(self) -> CleaningStepProtocol:
966 return self._LineCommentStep()
968 def _create_docstring_step(self) -> CleaningStepProtocol:
969 return self._DocstringStep()
971 class _DocstringStep:
972 name = "remove_docstrings"
974 def _is_docstring_node(self, node: ast.AST) -> bool:
975 body = getattr(node, "body", None)
976 return (
977 hasattr(node, "body")
978 and body is not None
979 and len(body) > 0
980 and isinstance(body[0], ast.Expr)
981 and isinstance(body[0].value, ast.Constant)
982 and isinstance(body[0].value.value, str)
983 )
985 def _find_docstrings(self, tree: ast.AST) -> list[ast.AST]:
986 docstring_nodes: list[ast.AST] = []
987 finder = self._DocstringFinder(docstring_nodes, self._is_docstring_node)
988 finder.visit(tree)
989 return docstring_nodes
991 class _DocstringFinder(ast.NodeVisitor):
992 def __init__(
993 self,
994 docstring_nodes: list[ast.AST],
995 is_docstring_node: t.Callable[[ast.AST], bool],
996 ):
997 self.docstring_nodes = docstring_nodes
998 self.is_docstring_node = is_docstring_node
1000 def _add_if_docstring(self, node: ast.AST) -> None:
1001 if self.is_docstring_node(node) and hasattr(node, "body"):
1002 body: list[ast.stmt] = getattr(node, "body")
1003 self.docstring_nodes.append(body[0])
1004 self.generic_visit(node)
1006 def visit_Module(self, node: ast.Module) -> None:
1007 self._add_if_docstring(node)
1009 def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
1010 self._add_if_docstring(node)
1012 def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
1013 self._add_if_docstring(node)
1015 def visit_ClassDef(self, node: ast.ClassDef) -> None:
1016 self._add_if_docstring(node)
1018 def __call__(self, code: str, file_path: Path) -> str:
1019 try:
1020 tree = ast.parse(code, filename=str(file_path))
1021 except SyntaxError:
1022 return self._regex_fallback_removal(code)
1024 docstring_nodes = self._find_docstrings(tree)
1026 if not docstring_nodes:
1027 return code
1029 lines = code.split("\n")
1030 lines_to_remove: set[int] = set()
1032 for node in docstring_nodes:
1033 start_line = getattr(node, "lineno", 1)
1034 end_line = getattr(node, "end_lineno", start_line)
1036 lines_to_remove.update(range(start_line, end_line + 1))
1038 result_lines = [
1039 line for i, line in enumerate(lines, 1) if i not in lines_to_remove
1040 ]
1042 result = "\n".join(result_lines)
1043 return self._regex_fallback_removal(result)
1045 def _regex_fallback_removal(self, code: str) -> str:
1046 return _compiled_patterns.apply_docstring_patterns(code)
1048 class _LineCommentStep:
1049 name = "remove_line_comments"
1051 def __call__(self, code: str, file_path: Path) -> str:
1052 lines = code.split("\n")
1054 processed_lines = [self._process_line_for_comments(line) for line in lines]
1055 return "\n".join(processed_lines)
1057 def _process_line_for_comments(self, line: str) -> str:
1058 if not line.strip() or self._is_preserved_comment_line(line):
1059 return line
1060 return self._remove_comment_from_line(line)
1062 def _is_preserved_comment_line(self, line: str) -> bool:
1063 stripped = line.strip()
1064 if not stripped.startswith("#"):
1065 return False
1066 return self._has_preserved_pattern(stripped)
1068 def _has_preserved_pattern(self, stripped_line: str) -> bool:
1069 return _compiled_patterns.has_preserved_comment(stripped_line)
1071 def _remove_comment_from_line(self, line: str) -> str:
1072 if '"' not in line and "'" not in line and "#" not in line:
1073 return line
1075 result_chars = []
1076 in_string = False
1077 quote_char = None
1078 i = 0
1079 length = len(line)
1081 while i < length:
1082 char = line[i]
1084 if not in_string:
1085 if char == "#":
1086 break
1087 elif char in ('"', "'"):
1088 in_string = True
1089 quote_char = char
1090 elif char == quote_char and (i == 0 or line[i - 1] != "\\"):
1091 in_string = False
1092 quote_char = None
1094 result_chars.append(char)
1095 i += 1
1097 return "".join(result_chars).rstrip()
1099 def _create_docstring_finder_class(
1100 self,
1101 docstring_nodes: list[ast.AST],
1102 ) -> type[ast.NodeVisitor]:
1103 class DocstringFinder(ast.NodeVisitor):
1104 def _is_docstring_node(self, node: ast.AST) -> bool:
1105 body = getattr(node, "body", None)
1106 return (
1107 hasattr(node, "body")
1108 and body is not None
1109 and len(body) > 0
1110 and isinstance(body[0], ast.Expr)
1111 and isinstance(body[0].value, ast.Constant)
1112 and isinstance(body[0].value.value, str)
1113 )
1115 def _add_if_docstring(self, node: ast.AST) -> None:
1116 if self._is_docstring_node(node) and hasattr(node, "body"):
1117 body: list[ast.stmt] = getattr(node, "body")
1118 docstring_nodes.append(body[0])
1119 self.generic_visit(node)
1121 def visit_Module(self, node: ast.Module) -> None:
1122 self._add_if_docstring(node)
1124 def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
1125 self._add_if_docstring(node)
1127 def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
1128 self._add_if_docstring(node)
1130 def visit_ClassDef(self, node: ast.ClassDef) -> None:
1131 self._add_if_docstring(node)
1133 return DocstringFinder
1135 def _create_whitespace_step(self) -> CleaningStepProtocol:
1136 class WhitespaceStep:
1137 name = "remove_extra_whitespace"
1139 _whitespace_pattern = re.compile(r" {2,}")
1141 def __call__(self, code: str, file_path: Path) -> str:
1142 lines = code.split("\n")
1143 cleaned_lines: list[str] = []
1144 empty_line_count = 0
1146 for line in lines:
1147 cleaned_line = line.rstrip()
1149 if not cleaned_line.strip():
1150 empty_line_count += 1
1151 if empty_line_count <= 2:
1152 cleaned_lines.append("")
1153 else:
1154 empty_line_count = 0
1155 leading_whitespace = len(cleaned_line) - len(
1156 cleaned_line.lstrip()
1157 )
1158 content = cleaned_line.lstrip()
1160 content = self._whitespace_pattern.sub(" ", content)
1162 cleaned_line = cleaned_line[:leading_whitespace] + content
1163 cleaned_lines.append(cleaned_line)
1165 while cleaned_lines and not cleaned_lines[-1].strip():
1166 cleaned_lines.pop()
1168 result = "\n".join(cleaned_lines)
1169 if result and not result.endswith("\n"):
1170 result += "\n"
1172 return result
1174 return WhitespaceStep()
1176 def _create_formatting_step(self) -> CleaningStepProtocol:
1177 class FormattingStep:
1178 name = "format_code"
1180 def _is_preserved_comment_line(self, line: str) -> bool:
1181 stripped = line.strip()
1182 if not stripped.startswith("#"):
1183 return False
1184 return _compiled_patterns.has_preserved_comment(line)
1186 def __call__(self, code: str, file_path: Path) -> str:
1187 lines = code.split("\n")
1188 formatted_lines: list[str] = []
1190 for line in lines:
1191 if line.strip():
1192 if self._is_preserved_comment_line(line):
1193 formatted_lines.append(line)
1194 continue
1196 leading_whitespace = len(line) - len(line.lstrip())
1197 content = line.lstrip()
1199 content = _compiled_patterns.apply_formatting_patterns(content)
1201 formatted_line = line[:leading_whitespace] + content
1202 formatted_lines.append(formatted_line)
1203 else:
1204 formatted_lines.append(line)
1206 return "\n".join(formatted_lines)
1208 return FormattingStep()
1210 def remove_line_comments(self, code: str, file_path: Path | None = None) -> str:
1211 file_path = file_path or Path("temp.py")
1212 step = self._create_line_comment_step()
1213 return step(code, file_path)
1215 def remove_docstrings(self, code: str, file_path: Path | None = None) -> str:
1216 file_path = file_path or Path("temp.py")
1217 step = self._create_docstring_step()
1218 return step(code, file_path)
1220 def remove_extra_whitespace(self, code: str, file_path: Path | None = None) -> str:
1221 file_path = file_path or Path("temp.py")
1222 step = self._create_whitespace_step()
1223 return step(code, file_path)
1225 def format_code(self, code: str, file_path: Path | None = None) -> str:
1226 file_path = file_path or Path("temp.py")
1227 step = self._create_formatting_step()
1228 return step(code, file_path)