Coverage for /Users/les/Projects/crackerjack/crackerjack/services/config_integrity.py: 0%

57 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1from pathlib import Path 

2 

3from rich.console import Console 

4 

5 

6class ConfigIntegrityService: 

7 def __init__(self, console: Console, project_path: Path) -> None: 

8 self.console = console 

9 self.project_path = project_path 

10 self.cache_dir = Path.home() / ".cache" / "crackerjack" 

11 self.cache_dir.mkdir(parents=True, exist_ok=True) 

12 

13 def check_config_integrity(self) -> bool: 

14 config_files = [ 

15 ".pre-commit-config.yaml", 

16 "pyproject.toml", 

17 ] 

18 

19 drift_detected = False 

20 

21 for file_name in config_files: 

22 file_path = self.project_path / file_name 

23 if file_path.exists() and self._check_file_drift(file_path): 

24 drift_detected = True 

25 

26 if not self._has_required_config_sections(): 

27 self.console.print( 

28 "[yellow]⚠️ Configuration missing required sections[/ yellow]", 

29 ) 

30 drift_detected = True 

31 

32 return drift_detected 

33 

34 def _check_file_drift(self, file_path: Path) -> bool: 

35 cache_file = self.cache_dir / f"{file_path.name}.hash" 

36 

37 try: 

38 current_content = file_path.read_text() 

39 current_hash = hash(current_content) 

40 

41 if cache_file.exists(): 

42 from contextlib import suppress 

43 

44 with suppress(OSError, ValueError): 

45 cached_hash = int(cache_file.read_text().strip()) 

46 if current_hash != cached_hash: 

47 self.console.print( 

48 f"[yellow]⚠️ {file_path.name} has been modified manually[/ yellow]", 

49 ) 

50 return True 

51 

52 cache_file.write_text(str(current_hash)) 

53 return False 

54 

55 except OSError as e: 

56 self.console.print(f"[red]❌ Error checking {file_path.name}: {e}[/ red]") 

57 return False 

58 

59 def _has_required_config_sections(self) -> bool: 

60 pyproject = self.project_path / "pyproject.toml" 

61 if not pyproject.exists(): 

62 return False 

63 

64 try: 

65 import tomllib 

66 

67 with pyproject.open("rb") as f: 

68 config = tomllib.load(f) 

69 

70 required = ["tool.ruff", "tool.pyright", "tool.pytest.ini_options"] 

71 

72 for section in required: 

73 keys = section.split(".") 

74 current = config 

75 

76 for key in keys: 

77 if key not in current: 

78 self.console.print( 

79 f"[yellow]⚠️ Missing required config section: {section}[/ yellow]", 

80 ) 

81 return False 

82 current = current[key] 

83 

84 return True 

85 

86 except Exception as e: 

87 self.console.print(f"[red]❌ Error parsing pyproject.toml: {e}[/ red]") 

88 return False