pathflow-toolkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
path_file/utils.py ADDED
@@ -0,0 +1,509 @@
1
+ """Public utility functions for path_file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ import tempfile
10
+ from collections.abc import Generator
11
+ from datetime import timedelta
12
+ from pathlib import Path
13
+
14
+ from path_file._internal._safety import safe_path
15
+ from path_file.units import human_size, parse_duration, parse_size
16
+
17
+ # ──────────────────────────────────────────────────────────────────────────────
18
+ # SIZE & DURATION ALIASES
19
+ # ──────────────────────────────────────────────────────────────────────────────
20
+
21
+
22
+ def size(s: str | int | float) -> int:
23
+ """Parse human-readable size to bytes. Alias for parse_size."""
24
+ return parse_size(s)
25
+
26
+
27
+ def hsize(n: int, precision: int = 2) -> str:
28
+ """Format bytes to human-readable. Alias for human_size."""
29
+ return human_size(n, precision)
30
+
31
+
32
+ def duration(s: str | int | float) -> timedelta:
33
+ """Parse human-readable duration to timedelta. Alias for parse_duration."""
34
+ return parse_duration(s)
35
+
36
+
37
+ # ──────────────────────────────────────────────────────────────────────────────
38
+ # PATH UTILITIES
39
+ # ──────────────────────────────────────────────────────────────────────────────
40
+
41
+
42
+ def expand(path: str | Path) -> Path:
43
+ """Expand ~ and environment variables in path."""
44
+ return Path(os.path.expandvars(os.path.expanduser(str(path)))).resolve()
45
+
46
+
47
+ def safe_join(*parts: str | Path, base: Path | None = None) -> Path:
48
+ """Safely join path parts, optionally restricting to base directory."""
49
+ path = Path(*parts)
50
+ if base:
51
+ # Join relative to base
52
+ path = base / path
53
+ return safe_path(path, base)
54
+ return path.resolve()
55
+
56
+
57
+ def mkdir(path: str | Path, mode: int = 0o755, parents: bool = True, exist_ok: bool = True) -> Path:
58
+ """Create directory with parents. Returns the created path."""
59
+ path = Path(path)
60
+ path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
61
+ return path
62
+
63
+
64
+ def which(cmd: str) -> Path | None:
65
+ """Find executable in PATH. Returns Path or None."""
66
+ result = shutil.which(cmd)
67
+ return Path(result) if result else None
68
+
69
+
70
+ def free_space(path: str | Path) -> int:
71
+ """Get free disk space in bytes for the filesystem containing path."""
72
+ path = Path(path)
73
+ if os.name == "nt":
74
+ import ctypes
75
+
76
+ free_bytes = ctypes.c_ulonglong(0)
77
+ ctypes.windll.kernel32.GetDiskFreeSpaceExW(str(path), None, None, ctypes.byref(free_bytes))
78
+ return free_bytes.value
79
+ else:
80
+ # shutil.disk_usage uses os.statvfs(...).f_bavail * f_frsize on POSIX
81
+ return shutil.disk_usage(path).free
82
+
83
+
84
+ def disk_usage(path: str | Path) -> tuple[int, int, int]:
85
+ """Return (total, used, free) disk space in bytes."""
86
+ total, used, free = shutil.disk_usage(path)
87
+ return total, used, free
88
+
89
+
90
+ # ──────────────────────────────────────────────────────────────────────────────
91
+ # TEMPORARY DIRECTORY
92
+ # ──────────────────────────────────────────────────────────────────────────────
93
+
94
+
95
+ @contextlib.contextmanager
96
+ def tempdir(
97
+ prefix: str = "path_file_",
98
+ suffix: str = "",
99
+ dir: str | Path | None = None,
100
+ ) -> Generator[Path, None, None]:
101
+ """
102
+ Context manager for temporary directory.
103
+
104
+ Example:
105
+ with pf.tempdir() as tmp:
106
+ # use tmp
107
+ pass
108
+ # tmp is automatically cleaned up
109
+ """
110
+ with tempfile.TemporaryDirectory(prefix=prefix, suffix=suffix, dir=dir) as tmp:
111
+ yield Path(tmp)
112
+
113
+
114
+ # ──────────────────────────────────────────────────────────────────────────────
115
+ # FILE OPERATIONS
116
+ # ──────────────────────────────────────────────────────────────────────────────
117
+
118
+
119
+ def copy_file(
120
+ src: str | Path,
121
+ dest: str | Path,
122
+ overwrite: bool = False,
123
+ preserve_metadata: bool = True,
124
+ ) -> Path:
125
+ """Copy a single file."""
126
+ src = Path(src)
127
+ dest = Path(dest)
128
+
129
+ if dest.exists() and not overwrite:
130
+ raise FileExistsError(f"Destination exists: {dest}")
131
+
132
+ dest.parent.mkdir(parents=True, exist_ok=True)
133
+
134
+ if preserve_metadata:
135
+ shutil.copy2(src, dest)
136
+ else:
137
+ shutil.copy(src, dest)
138
+
139
+ return dest
140
+
141
+
142
+ def move_file(
143
+ src: str | Path,
144
+ dest: str | Path,
145
+ overwrite: bool = False,
146
+ ) -> Path:
147
+ """Move a single file."""
148
+ src = Path(src)
149
+ dest = Path(dest)
150
+
151
+ if dest.exists() and not overwrite:
152
+ raise FileExistsError(f"Destination exists: {dest}")
153
+
154
+ dest.parent.mkdir(parents=True, exist_ok=True)
155
+ shutil.move(str(src), str(dest))
156
+
157
+ return dest
158
+
159
+
160
+ def delete_file(
161
+ path: str | Path,
162
+ missing_ok: bool = True,
163
+ ) -> bool:
164
+ """Delete a file. Returns True if deleted, False if didn't exist."""
165
+ path = Path(path)
166
+ try:
167
+ path.unlink()
168
+ return True
169
+ except FileNotFoundError:
170
+ if not missing_ok:
171
+ raise
172
+ return False
173
+
174
+
175
+ def delete_dir(
176
+ path: str | Path,
177
+ missing_ok: bool = True,
178
+ ) -> bool:
179
+ """Delete a directory and all contents. Returns True if deleted."""
180
+ path = Path(path)
181
+ try:
182
+ shutil.rmtree(path)
183
+ return True
184
+ except FileNotFoundError:
185
+ if not missing_ok:
186
+ raise
187
+ return False
188
+
189
+
190
+ def touch(path: str | Path, mode: int = 0o644, exist_ok: bool = True) -> Path:
191
+ """Create file or update modification time."""
192
+ path = Path(path)
193
+ path.parent.mkdir(parents=True, exist_ok=True)
194
+ path.touch(mode=mode, exist_ok=exist_ok)
195
+ return path
196
+
197
+
198
+ def read_text(path: str | Path, encoding: str = "utf-8") -> str:
199
+ """Read file as text with encoding detection fallback."""
200
+ path = Path(path)
201
+ try:
202
+ return path.read_text(encoding=encoding)
203
+ except UnicodeDecodeError:
204
+ return path.read_text(encoding="latin-1")
205
+
206
+
207
+ def read_bytes(path: str | Path) -> bytes:
208
+ """Read file as bytes."""
209
+ return Path(path).read_bytes()
210
+
211
+
212
+ def write_text(
213
+ path: str | Path,
214
+ data: str,
215
+ encoding: str = "utf-8",
216
+ atomic: bool = True,
217
+ ) -> Path:
218
+ """Write text to file (atomically by default)."""
219
+ path = Path(path)
220
+ path.parent.mkdir(parents=True, exist_ok=True)
221
+
222
+ if atomic:
223
+ import tempfile
224
+
225
+ with tempfile.NamedTemporaryFile(
226
+ mode="w", encoding=encoding, delete=False, dir=path.parent
227
+ ) as f:
228
+ f.write(data)
229
+ temp_path = Path(f.name)
230
+ temp_path.replace(path)
231
+ else:
232
+ path.write_text(data, encoding=encoding)
233
+
234
+ return path
235
+
236
+
237
+ def write_bytes(
238
+ path: str | Path,
239
+ data: bytes,
240
+ atomic: bool = True,
241
+ ) -> Path:
242
+ """Write bytes to file (atomically by default)."""
243
+ path = Path(path)
244
+ path.parent.mkdir(parents=True, exist_ok=True)
245
+
246
+ if atomic:
247
+ import tempfile
248
+
249
+ with tempfile.NamedTemporaryFile(mode="wb", delete=False, dir=path.parent) as f:
250
+ f.write(data)
251
+ temp_path = Path(f.name)
252
+ temp_path.replace(path)
253
+ else:
254
+ path.write_bytes(data)
255
+
256
+ return path
257
+
258
+
259
+ # ──────────────────────────────────────────────────────────────────────────────
260
+ # SYMLINKS
261
+ # ──────────────────────────────────────────────────────────────────────────────
262
+
263
+
264
+ def symlink(
265
+ target: str | Path,
266
+ link_path: str | Path,
267
+ target_is_directory: bool = False,
268
+ ) -> Path:
269
+ """Create symbolic link."""
270
+ target = Path(target)
271
+ link_path = Path(link_path)
272
+ link_path.parent.mkdir(parents=True, exist_ok=True)
273
+ link_path.symlink_to(target, target_is_directory=target_is_directory)
274
+ return link_path
275
+
276
+
277
+ def readlink(path: str | Path) -> Path:
278
+ """Read symbolic link target."""
279
+ return Path(os.readlink(path))
280
+
281
+
282
+ def is_symlink(path: str | Path) -> bool:
283
+ """Check if path is a symbolic link."""
284
+ return Path(path).is_symlink()
285
+
286
+
287
+ def resolve_link(path: str | Path) -> Path:
288
+ """Resolve all symlinks in path."""
289
+ return Path(path).resolve()
290
+
291
+
292
+ # ──────────────────────────────────────────────────────────────────────────────
293
+ # PROCESS EXECUTION
294
+ # ──────────────────────────────────────────────────────────────────────────────
295
+
296
+
297
+ def run_command(
298
+ cmd: list[str],
299
+ cwd: str | Path | None = None,
300
+ capture: bool = True,
301
+ check: bool = True,
302
+ env: dict[str, str] | None = None,
303
+ timeout: float | None = None,
304
+ ) -> subprocess.CompletedProcess[str]:
305
+ """Run command with sensible defaults."""
306
+ # arg-list subprocess execution is the intended public API
307
+ return subprocess.run( # noqa: S603 # arg-list subprocess is the intended API
308
+ cmd,
309
+ cwd=cwd,
310
+ capture_output=capture,
311
+ text=True,
312
+ check=check,
313
+ env={**os.environ, **(env or {})},
314
+ timeout=timeout,
315
+ )
316
+
317
+
318
+ def run_shell(
319
+ cmd: str,
320
+ cwd: str | Path | None = None,
321
+ capture: bool = True,
322
+ check: bool = True,
323
+ timeout: float | None = None,
324
+ ) -> subprocess.CompletedProcess[str]:
325
+ """Run shell command."""
326
+ # shell command strings are the intended public API
327
+ return subprocess.run( # noqa: S602 # shell command string is the intended API
328
+ cmd,
329
+ shell=True,
330
+ cwd=cwd,
331
+ capture_output=capture,
332
+ text=True,
333
+ check=check,
334
+ timeout=timeout,
335
+ )
336
+
337
+
338
+ # ──────────────────────────────────────────────────────────────────────────────
339
+ # PATH INFO
340
+ # ──────────────────────────────────────────────────────────────────────────────
341
+
342
+
343
+ def get_size(path: str | Path) -> int:
344
+ """Get file or directory size in bytes."""
345
+ path = Path(path)
346
+ if path.is_file():
347
+ return path.stat().st_size
348
+ elif path.is_dir():
349
+ total = 0
350
+ for entry in path.rglob("*"):
351
+ if entry.is_file():
352
+ with contextlib.suppress(OSError, PermissionError):
353
+ total += entry.stat().st_size
354
+ return total
355
+ return 0
356
+
357
+
358
+ def get_size_human(path: str | Path) -> str:
359
+ """Get human-readable size of file or directory."""
360
+ return human_size(get_size(path))
361
+
362
+
363
+ def count_files(path: str | Path, pattern: str = "*") -> int:
364
+ """Count files matching pattern in directory."""
365
+ path = Path(path)
366
+ if path.is_file():
367
+ return 1 if path.match(pattern) else 0
368
+ return len(list(path.rglob(pattern)))
369
+
370
+
371
+ def find_largest(path: str | Path, n: int = 10) -> list[Path]:
372
+ """Find n largest files in directory."""
373
+ path = Path(path)
374
+ files = []
375
+ for entry in path.rglob("*"):
376
+ if entry.is_file():
377
+ with contextlib.suppress(OSError, PermissionError):
378
+ files.append((entry, entry.stat().st_size))
379
+ files.sort(key=lambda x: -x[1])
380
+ return [f[0] for f in files[:n]]
381
+
382
+
383
+ def find_oldest(path: str | Path, n: int = 10) -> list[Path]:
384
+ """Find n oldest files in directory."""
385
+ path = Path(path)
386
+ files = []
387
+ for entry in path.rglob("*"):
388
+ if entry.is_file():
389
+ with contextlib.suppress(OSError, PermissionError):
390
+ files.append((entry, entry.stat().st_mtime))
391
+ files.sort(key=lambda x: x[1])
392
+ return [f[0] for f in files[:n]]
393
+
394
+
395
+ def find_newest(path: str | Path, n: int = 10) -> list[Path]:
396
+ """Find n newest files in directory."""
397
+ path = Path(path)
398
+ files = []
399
+ for entry in path.rglob("*"):
400
+ if entry.is_file():
401
+ with contextlib.suppress(OSError, PermissionError):
402
+ files.append((entry, entry.stat().st_mtime))
403
+ files.sort(key=lambda x: -x[1])
404
+ return [f[0] for f in files[:n]]
405
+
406
+
407
+ # ──────────────────────────────────────────────────────────────────────────────
408
+ # ARCHIVE HELPERS
409
+ # ──────────────────────────────────────────────────────────────────────────────
410
+
411
+
412
+ def make_archive(
413
+ source: str | Path,
414
+ dest: str | Path,
415
+ format: str = "zip",
416
+ ) -> Path:
417
+ """Create archive from directory."""
418
+ import shutil
419
+
420
+ source = Path(source)
421
+ dest = Path(dest)
422
+ dest.parent.mkdir(parents=True, exist_ok=True)
423
+
424
+ base_name = str(dest.with_suffix(""))
425
+ shutil.make_archive(base_name, format, source)
426
+
427
+ return dest
428
+
429
+
430
+ def extract_archive(
431
+ archive: str | Path,
432
+ dest: str | Path,
433
+ ) -> Path:
434
+ """Extract archive to directory."""
435
+ import shutil
436
+
437
+ archive = Path(archive)
438
+ dest = Path(dest)
439
+ dest.mkdir(parents=True, exist_ok=True)
440
+ shutil.unpack_archive(archive, dest)
441
+ return dest
442
+
443
+
444
+ # ──────────────────────────────────────────────────────────────────────────────
445
+ # HASH HELPERS
446
+ # ──────────────────────────────────────────────────────────────────────────────
447
+
448
+
449
+ def hash_file(path: str | Path, algorithm: str = "sha256") -> str:
450
+ """Compute file hash."""
451
+ import hashlib
452
+
453
+ path = Path(path)
454
+ h = hashlib.new(algorithm)
455
+ with path.open("rb") as f:
456
+ for chunk in iter(lambda: f.read(65536), b""):
457
+ h.update(chunk)
458
+ return h.hexdigest()
459
+
460
+
461
+ def verify_hash(path: str | Path, expected: str, algorithm: str = "sha256") -> bool:
462
+ """Verify file hash matches expected."""
463
+ return hash_file(path, algorithm).lower() == expected.lower()
464
+
465
+
466
+ # ──────────────────────────────────────────────────────────────────────────────
467
+ # MISC
468
+ # ──────────────────────────────────────────────────────────────────────────────
469
+
470
+
471
+ def is_binary(path: str | Path) -> bool:
472
+ """Check if file appears to be binary."""
473
+ path = Path(path)
474
+ try:
475
+ with path.open("rb") as f:
476
+ chunk = f.read(8192)
477
+ if b"\x00" in chunk:
478
+ return True
479
+ text_chars = sum(1 for b in chunk if 32 <= b <= 126 or b in (9, 10, 13))
480
+ return len(chunk) > 0 and text_chars / len(chunk) < 0.7
481
+ except (OSError, PermissionError):
482
+ return False
483
+
484
+
485
+ def get_mime_type(path: str | Path) -> str:
486
+ """Get MIME type of file."""
487
+ import mimetypes
488
+
489
+ mimetypes.init()
490
+ mime, _ = mimetypes.guess_type(str(path))
491
+ return mime or "application/octet-stream"
492
+
493
+
494
+ def get_extension(path: str | Path) -> str:
495
+ """Get file extension (lowercase)."""
496
+ return Path(path).suffix.lower()
497
+
498
+
499
+ def strip_extension(path: str | Path) -> str:
500
+ """Get filename without extension."""
501
+ return Path(path).stem
502
+
503
+
504
+ def change_extension(path: str | Path, new_ext: str) -> Path:
505
+ """Change file extension."""
506
+ path = Path(path)
507
+ if not new_ext.startswith("."):
508
+ new_ext = "." + new_ext
509
+ return path.with_suffix(new_ext)