Coverage for /Users/les/Projects/crackerjack/crackerjack/services/filesystem.py: 0%
173 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 shutil
2from collections.abc import Iterator
3from pathlib import Path
5from crackerjack.errors import ErrorCode, FileError, ResourceError
8class FileSystemService:
9 @staticmethod
10 def clean_trailing_whitespace_and_newlines(content: str) -> str:
11 lines = content.splitlines()
12 cleaned_lines = [line.rstrip() for line in lines]
14 result = "\n".join(cleaned_lines)
15 if result and not result.endswith("\n"):
16 result += "\n"
18 return result
20 def read_file(self, path: str | Path) -> str:
21 try:
22 path_obj = Path(path) if isinstance(path, str) else path
23 if not path_obj.exists():
24 raise FileError(
25 message=f"File does not exist: {path_obj}",
26 details=f"Attempted to read file at {path_obj.absolute()}",
27 recovery="Check file path and ensure file exists",
28 )
29 return path_obj.read_text(encoding="utf-8")
30 except PermissionError as e:
31 raise FileError(
32 message=f"Permission denied reading file: {path}",
33 error_code=ErrorCode.PERMISSION_ERROR,
34 details=str(e),
35 recovery="Check file permissions and user access rights",
36 ) from e
37 except UnicodeDecodeError as e:
38 raise FileError(
39 message=f"Unable to decode file as UTF-8: {path}",
40 error_code=ErrorCode.FILE_READ_ERROR,
41 details=str(e),
42 recovery="Ensure file is text - based and UTF-8 encoded",
43 ) from e
44 except OSError as e:
45 raise FileError(
46 message=f"System error reading file: {path}",
47 error_code=ErrorCode.FILE_READ_ERROR,
48 details=str(e),
49 recovery="Check disk space and file system integrity",
50 ) from e
52 def write_file(self, path: str | Path, content: str) -> None:
53 try:
54 path_obj = Path(path) if isinstance(path, str) else path
55 try:
56 path_obj.parent.mkdir(parents=True, exist_ok=True)
57 except OSError as e:
58 raise FileError(
59 message=f"Cannot create parent directories for: {path}",
60 error_code=ErrorCode.FILE_WRITE_ERROR,
61 details=str(e),
62 recovery="Check disk space and directory permissions",
63 ) from e
65 if path_obj.name in {".pre-commit-config.yaml", "pyproject.toml"}:
66 content = self.clean_trailing_whitespace_and_newlines(content)
68 path_obj.write_text(content, encoding="utf-8")
69 except PermissionError as e:
70 raise FileError(
71 message=f"Permission denied writing file: {path}",
72 error_code=ErrorCode.PERMISSION_ERROR,
73 details=str(e),
74 recovery="Check file and directory permissions",
75 ) from e
76 except OSError as e:
77 if "No space left on device" in str(e):
78 raise ResourceError(
79 message=f"Insufficient disk space to write file: {path}",
80 details=str(e),
81 recovery="Free up disk space and try again",
82 ) from e
83 raise FileError(
84 message=f"System error writing file: {path}",
85 error_code=ErrorCode.FILE_WRITE_ERROR,
86 details=str(e),
87 recovery="Check disk space and file system integrity",
88 ) from e
90 def exists(self, path: str | Path) -> bool:
91 try:
92 path_obj = Path(path) if isinstance(path, str) else path
93 return path_obj.exists()
94 except OSError:
95 return False
97 def mkdir(self, path: str | Path, parents: bool = False) -> None:
98 try:
99 path_obj = Path(path) if isinstance(path, str) else path
100 path_obj.mkdir(parents=parents, exist_ok=True)
101 except PermissionError as e:
102 raise FileError(
103 message=f"Permission denied creating directory: {path}",
104 error_code=ErrorCode.PERMISSION_ERROR,
105 details=str(e),
106 recovery="Check parent directory permissions",
107 ) from e
108 except FileExistsError as e:
109 if not parents:
110 raise FileError(
111 message=f"Directory already exists: {path}",
112 details=str(e),
113 recovery="Use exist_ok=True or check if directory exists first",
114 ) from e
115 except OSError as e:
116 if "No space left on device" in str(e):
117 raise ResourceError(
118 message=f"Insufficient disk space to create directory: {path}",
119 details=str(e),
120 recovery="Free up disk space and try again",
121 ) from e
122 raise FileError(
123 message=f"System error creating directory: {path}",
124 error_code=ErrorCode.FILE_WRITE_ERROR,
125 details=str(e),
126 recovery="Check disk space and file system integrity",
127 ) from e
129 def glob(self, pattern: str, path: str | Path | None = None) -> list[Path]:
130 base_path = Path(path) if path else Path.cwd()
131 try:
132 if not base_path.exists():
133 raise FileError(
134 message=f"Base path does not exist: {base_path}",
135 details=f"Attempted to glob in {base_path.absolute()}",
136 recovery="Check base path and ensure directory exists",
137 )
138 return list(base_path.glob(pattern))
139 except PermissionError as e:
140 raise FileError(
141 message=f"Permission denied accessing directory: {base_path}",
142 error_code=ErrorCode.PERMISSION_ERROR,
143 details=str(e),
144 recovery="Check directory permissions",
145 ) from e
146 except OSError as e:
147 raise FileError(
148 message=f"System error during glob operation: {pattern}",
149 error_code=ErrorCode.FILE_READ_ERROR,
150 details=str(e),
151 recovery="Check path validity and file system integrity",
152 ) from e
154 def rglob(self, pattern: str, path: str | Path | None = None) -> list[Path]:
155 base_path = Path(path) if path else Path.cwd()
156 try:
157 if not base_path.exists():
158 raise FileError(
159 message=f"Base path does not exist: {base_path}",
160 details=f"Attempted to rglob in {base_path.absolute()}",
161 recovery="Check base path and ensure directory exists",
162 )
163 return list(base_path.rglob(pattern))
164 except PermissionError as e:
165 raise FileError(
166 message=f"Permission denied accessing directory: {base_path}",
167 error_code=ErrorCode.PERMISSION_ERROR,
168 details=str(e),
169 recovery="Check directory permissions",
170 ) from e
171 except OSError as e:
172 raise FileError(
173 message=f"System error during recursive glob operation: {pattern}",
174 error_code=ErrorCode.FILE_READ_ERROR,
175 details=str(e),
176 recovery="Check path validity and file system integrity",
177 ) from e
179 def copy_file(self, src: str | Path, dst: str | Path) -> None:
180 src_path, dst_path = self._normalize_copy_paths(src, dst)
181 self._validate_copy_source(src_path)
182 self._prepare_copy_destination(dst_path)
183 self._perform_file_copy(src_path, dst_path, src, dst)
185 def _normalize_copy_paths(
186 self, src: str | Path, dst: str | Path
187 ) -> tuple[Path, Path]:
188 src_path = Path(src) if isinstance(src, str) else src
189 dst_path = Path(dst) if isinstance(dst, str) else dst
190 return src_path, dst_path
192 def _validate_copy_source(self, src_path: Path) -> None:
193 if not src_path.exists():
194 raise FileError(
195 message=f"Source file does not exist: {src_path}",
196 details=f"Attempted to copy from {src_path.absolute()}",
197 recovery="Check source file path and ensure file exists",
198 )
199 if not src_path.is_file():
200 raise FileError(
201 message=f"Source is not a file: {src_path}",
202 details=f"Source is a {src_path.stat().st_mode} type",
203 recovery="Ensure source path points to a regular file",
204 )
206 def _prepare_copy_destination(self, dst_path: Path) -> None:
207 try:
208 dst_path.parent.mkdir(parents=True, exist_ok=True)
209 except OSError as e:
210 raise FileError(
211 message=f"Cannot create destination parent directories: {dst_path.parent}",
212 error_code=ErrorCode.FILE_WRITE_ERROR,
213 details=str(e),
214 recovery="Check disk space and directory permissions",
215 ) from e
217 def _perform_file_copy(
218 self, src_path: Path, dst_path: Path, src: str | Path, dst: str | Path
219 ) -> None:
220 try:
221 shutil.copy2(src_path, dst_path)
222 except PermissionError as e:
223 raise FileError(
224 message=f"Permission denied copying file: {src} -> {dst}",
225 error_code=ErrorCode.PERMISSION_ERROR,
226 details=str(e),
227 recovery="Check file and directory permissions",
228 ) from e
229 except shutil.SameFileError as e:
230 raise FileError(
231 message=f"Source and destination are the same file: {src}",
232 error_code=ErrorCode.FILE_WRITE_ERROR,
233 details=str(e),
234 recovery="Ensure source and destination paths are different",
235 ) from e
236 except OSError as e:
237 if "No space left on device" in str(e):
238 raise ResourceError(
239 message=f"Insufficient disk space to copy file: {src} -> {dst}",
240 details=str(e),
241 recovery="Free up disk space and try again",
242 ) from e
243 raise FileError(
244 message=f"System error copying file: {src} -> {dst}",
245 error_code=ErrorCode.FILE_WRITE_ERROR,
246 details=str(e),
247 recovery="Check disk space and file system integrity",
248 ) from e
250 def remove_file(self, path: str | Path) -> None:
251 try:
252 path_obj = Path(path) if isinstance(path, str) else path
253 if path_obj.exists():
254 if not path_obj.is_file():
255 raise FileError(
256 message=f"Path is not a file: {path_obj}",
257 details=f"Path type: {path_obj.stat().st_mode}",
258 recovery="Use appropriate method for directory removal",
259 )
260 path_obj.unlink()
261 except PermissionError as e:
262 raise FileError(
263 message=f"Permission denied removing file: {path}",
264 error_code=ErrorCode.PERMISSION_ERROR,
265 details=str(e),
266 recovery="Check file permissions and ownership",
267 ) from e
268 except OSError as e:
269 raise FileError(
270 message=f"System error removing file: {path}",
271 error_code=ErrorCode.FILE_WRITE_ERROR,
272 details=str(e),
273 recovery="Check file system integrity and try again",
274 ) from e
276 def get_file_size(self, path: str | Path) -> int:
277 try:
278 path_obj = Path(path) if isinstance(path, str) else path
279 if not path_obj.exists():
280 raise FileError(
281 message=f"File does not exist: {path_obj}",
282 details=f"Attempted to get size of {path_obj.absolute()}",
283 recovery="Check file path and ensure file exists",
284 )
285 if not path_obj.is_file():
286 raise FileError(
287 message=f"Path is not a file: {path_obj}",
288 details=f"Path type: {path_obj.stat().st_mode}",
289 recovery="Ensure path points to a regular file",
290 )
291 return path_obj.stat().st_size
292 except PermissionError as e:
293 raise FileError(
294 message=f"Permission denied accessing file: {path}",
295 error_code=ErrorCode.PERMISSION_ERROR,
296 details=str(e),
297 recovery="Check file permissions",
298 ) from e
299 except OSError as e:
300 raise FileError(
301 message=f"System error getting file size: {path}",
302 error_code=ErrorCode.FILE_READ_ERROR,
303 details=str(e),
304 recovery="Check file system integrity",
305 ) from e
307 def get_file_mtime(self, path: str | Path) -> float:
308 try:
309 path_obj = Path(path) if isinstance(path, str) else path
310 if not path_obj.exists():
311 raise FileError(
312 message=f"File does not exist: {path_obj}",
313 details=f"Attempted to get mtime of {path_obj.absolute()}",
314 recovery="Check file path and ensure file exists",
315 )
316 if not path_obj.is_file():
317 raise FileError(
318 message=f"Path is not a file: {path_obj}",
319 details=f"Path type: {path_obj.stat().st_mode}",
320 recovery="Ensure path points to a regular file",
321 )
322 return path_obj.stat().st_mtime
323 except PermissionError as e:
324 raise FileError(
325 message=f"Permission denied accessing file: {path}",
326 error_code=ErrorCode.PERMISSION_ERROR,
327 details=str(e),
328 recovery="Check file permissions",
329 ) from e
330 except OSError as e:
331 raise FileError(
332 message=f"System error getting file modification time: {path}",
333 error_code=ErrorCode.FILE_READ_ERROR,
334 details=str(e),
335 recovery="Check file system integrity",
336 ) from e
338 def read_file_chunked(
339 self,
340 path: str | Path,
341 chunk_size: int = 8192,
342 ) -> Iterator[str]:
343 try:
344 path_obj = Path(path) if isinstance(path, str) else path
345 if not path_obj.exists():
346 raise FileError(
347 message=f"File does not exist: {path_obj}",
348 details=f"Attempted to read file at {path_obj.absolute()}",
349 recovery="Check file path and ensure file exists",
350 )
352 with path_obj.open(encoding="utf-8") as file:
353 while chunk := file.read(chunk_size):
354 yield chunk
356 except PermissionError as e:
357 raise FileError(
358 message=f"Permission denied reading file: {path}",
359 error_code=ErrorCode.PERMISSION_ERROR,
360 details=str(e),
361 recovery="Check file permissions",
362 ) from e
363 except UnicodeDecodeError as e:
364 raise FileError(
365 message=f"File encoding error: {path}",
366 error_code=ErrorCode.FILE_READ_ERROR,
367 details=str(e),
368 recovery="Ensure file is encoded in UTF-8",
369 ) from e
370 except OSError as e:
371 raise FileError(
372 message=f"System error reading file: {path}",
373 error_code=ErrorCode.FILE_READ_ERROR,
374 details=str(e),
375 recovery="Check file system integrity",
376 ) from e
378 def read_lines_streaming(self, path: str | Path) -> Iterator[str]:
379 try:
380 path_obj = Path(path) if isinstance(path, str) else path
381 if not path_obj.exists():
382 raise FileError(
383 message=f"File does not exist: {path_obj}",
384 details=f"Attempted to read file at {path_obj.absolute()}",
385 recovery="Check file path and ensure file exists",
386 )
387 with path_obj.open(encoding="utf-8") as file:
388 for line in file:
389 yield line.rstrip("\n\r")
390 except PermissionError as e:
391 raise FileError(
392 message=f"Permission denied reading file: {path}",
393 error_code=ErrorCode.PERMISSION_ERROR,
394 details=str(e),
395 recovery="Check file permissions",
396 ) from e
397 except UnicodeDecodeError as e:
398 raise FileError(
399 message=f"File encoding error: {path}",
400 error_code=ErrorCode.FILE_READ_ERROR,
401 details=str(e),
402 recovery="Ensure file is encoded in UTF-8",
403 ) from e
404 except OSError as e:
405 raise FileError(
406 message=f"System error reading file: {path}",
407 error_code=ErrorCode.FILE_READ_ERROR,
408 details=str(e),
409 recovery="Check file system integrity",
410 ) from e