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

95 statements  

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

1import asyncio 

2import hashlib 

3from concurrent.futures import ThreadPoolExecutor 

4from pathlib import Path 

5 

6from .cache import CrackerjackCache 

7 

8 

9class FileHasher: 

10 def __init__(self, cache: CrackerjackCache | None = None) -> None: 

11 self.cache = cache or CrackerjackCache() 

12 self._executor = ThreadPoolExecutor(max_workers=4) 

13 

14 def get_file_hash(self, file_path: Path, algorithm: str = "md5") -> str: 

15 if not file_path.exists(): 

16 return "" 

17 

18 cached_hash = self.cache.get_file_hash(file_path) 

19 if cached_hash: 

20 return cached_hash 

21 

22 file_hash = self._compute_file_hash(file_path, algorithm) 

23 self.cache.set_file_hash(file_path, file_hash) 

24 return file_hash 

25 

26 def get_directory_hash( 

27 self, 

28 directory: Path, 

29 patterns: list[str] | None = None, 

30 ) -> str: 

31 if patterns is None: 

32 patterns = ["*.py"] 

33 

34 file_hashes: list[str] = [] 

35 for pattern in patterns: 

36 for file_path in directory.rglob(pattern): 

37 if file_path.is_file(): 

38 file_hash = self.get_file_hash(file_path) 

39 file_hashes.append( 

40 f"{file_path.relative_to(directory)}: {file_hash}", 

41 ) 

42 

43 file_hashes.sort() 

44 combined_content = "\n".join(file_hashes) 

45 return hashlib.md5(combined_content.encode(), usedforsecurity=False).hexdigest() 

46 

47 def get_files_hash_list(self, files: list[Path]) -> list[str]: 

48 return [ 

49 self.get_file_hash(file_path) for file_path in files if file_path.exists() 

50 ] 

51 

52 async def get_files_hash_list_async(self, files: list[Path]) -> list[str]: 

53 loop = asyncio.get_running_loop() 

54 tasks = [ 

55 loop.run_in_executor(self._executor, self.get_file_hash, file_path) 

56 for file_path in files 

57 if file_path.exists() 

58 ] 

59 return await asyncio.gather(*tasks) 

60 

61 def has_files_changed(self, files: list[Path], cached_hashes: list[str]) -> bool: 

62 if len(files) != len(cached_hashes): 

63 return True 

64 

65 current_hashes = self.get_files_hash_list(files) 

66 return current_hashes != cached_hashes 

67 

68 def _compute_file_hash(self, file_path: Path, algorithm: str = "md5") -> str: 

69 hash_func = hashlib.new(algorithm) 

70 

71 try: 

72 with file_path.open("rb") as f: 

73 while chunk := f.read(8192): 

74 hash_func.update(chunk) 

75 return hash_func.hexdigest() 

76 except OSError: 

77 return "" 

78 

79 def get_project_files_hash(self, project_path: Path) -> dict[str, str]: 

80 patterns = ["*.py", "*.toml", "*.cfg", "*.ini", "*.yaml", "*.yml"] 

81 file_hashes = {} 

82 

83 for pattern in patterns: 

84 for file_path in project_path.rglob(pattern): 

85 if file_path.is_file() and not self._should_ignore_file(file_path): 

86 relative_path = str(file_path.relative_to(project_path)) 

87 file_hashes[relative_path] = self.get_file_hash(file_path) 

88 

89 return file_hashes 

90 

91 def _should_ignore_file(self, file_path: Path) -> bool: 

92 ignore_patterns = [ 

93 ".git", 

94 ".venv", 

95 "__pycache__", 

96 ".pytest_cache", 

97 ".coverage", 

98 ".crackerjack_cache", 

99 "node_modules", 

100 ".tox", 

101 "dist", 

102 "build", 

103 "*.egg-info", 

104 ] 

105 

106 path_str = str(file_path) 

107 return any(pattern in path_str for pattern in ignore_patterns) 

108 

109 def invalidate_cache(self, file_path: Path | None = None) -> None: 

110 if file_path: 

111 stat = file_path.stat() if file_path.exists() else None 

112 if stat: 

113 cache_key = f"file_hash: {file_path}: {stat.st_mtime}: {stat.st_size}" 

114 self.cache.file_hash_cache.invalidate(cache_key) 

115 else: 

116 self.cache.file_hash_cache.clear() 

117 

118 

119class SmartFileWatcher: 

120 def __init__(self, file_hasher: FileHasher) -> None: 

121 self.file_hasher = file_hasher 

122 self._watched_files: dict[Path, tuple[float, int]] = {} 

123 

124 def register_files(self, files: list[Path]) -> None: 

125 for file_path in files: 

126 if file_path.exists(): 

127 stat = file_path.stat() 

128 self._watched_files[file_path] = (stat.st_mtime, stat.st_size) 

129 

130 def check_changes(self) -> list[Path]: 

131 changed_files: list[Path] = [] 

132 

133 for file_path, (old_mtime, old_size) in self._watched_files.items(): 

134 if not file_path.exists(): 

135 changed_files.append(file_path) 

136 continue 

137 

138 stat = file_path.stat() 

139 if stat.st_mtime != old_mtime or stat.st_size != old_size: 

140 changed_files.append(file_path) 

141 self._watched_files[file_path] = (stat.st_mtime, stat.st_size) 

142 

143 return changed_files 

144 

145 def invalidate_changed_files(self) -> int: 

146 changed_files = self.check_changes() 

147 

148 for file_path in changed_files: 

149 self.file_hasher.invalidate_cache(file_path) 

150 

151 return len(changed_files)