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/archive.py ADDED
@@ -0,0 +1,447 @@
1
+ """Archive operations: create, extract, list, compress, decompress."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import bz2
6
+ import gzip
7
+ import lzma
8
+ import shutil
9
+ import tarfile
10
+ import zipfile
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ from path_file._internal._log import get_logger
15
+ from path_file._internal._safety import is_subpath
16
+ from path_file.entries import Entry
17
+ from path_file.exceptions import ArchiveError
18
+
19
+ logger = get_logger(__name__)
20
+
21
+
22
+ # ──────────────────────────────────────────────────────────────────────────────
23
+ # ARCHIVE ENTRY
24
+ # ──────────────────────────────────────────────────────────────────────────────
25
+
26
+
27
+ @dataclass
28
+ class ArchiveEntry:
29
+ """Represents an entry in an archive."""
30
+
31
+ name: str
32
+ size: int
33
+ is_dir: bool
34
+ modified: float | None = None # Unix timestamp
35
+ mode: int | None = None
36
+
37
+
38
+ # ──────────────────────────────────────────────────────────────────────────────
39
+ # ARCHIVE TYPE DETECTION
40
+ # ──────────────────────────────────────────────────────────────────────────────
41
+
42
+
43
+ def detect_archive_type(path: Path) -> str:
44
+ """
45
+ Detect archive type from file extension and magic bytes.
46
+
47
+ Returns:
48
+ One of: 'zip', 'tar', 'tar.gz', 'tar.bz2', 'tar.xz', 'gz', 'bz2', 'xz', 'unknown'
49
+ """
50
+ suffixes = [s.lower() for s in path.suffixes]
51
+ name = "".join(suffixes)
52
+
53
+ # Check by extension first
54
+ if name.endswith(".tar.gz") or name.endswith(".tgz"):
55
+ return "tar.gz"
56
+ if name.endswith(".tar.bz2") or name.endswith(".tbz2"):
57
+ return "tar.bz2"
58
+ if name.endswith(".tar.xz") or name.endswith(".txz"):
59
+ return "tar.xz"
60
+ if name.endswith(".tar"):
61
+ return "tar"
62
+ if name.endswith(".zip"):
63
+ return "zip"
64
+ if name.endswith(".gz"):
65
+ return "gz"
66
+ if name.endswith(".bz2"):
67
+ return "bz2"
68
+ if name.endswith(".xz"):
69
+ return "xz"
70
+
71
+ # Check magic bytes
72
+ try:
73
+ with path.open("rb") as f:
74
+ magic = f.read(8)
75
+ except (OSError, PermissionError):
76
+ return "unknown"
77
+
78
+ if (
79
+ magic.startswith(b"PK\x03\x04")
80
+ or magic.startswith(b"PK\x05\x06")
81
+ or magic.startswith(b"PK\x07\x08")
82
+ ):
83
+ return "zip"
84
+ if magic.startswith(b"\x1f\x8b"):
85
+ return "gz"
86
+ if magic.startswith(b"BZh"):
87
+ return "bz2"
88
+ if magic.startswith(b"\xfd7zXZ\x00"):
89
+ return "xz"
90
+ # tar has no magic, but we can check for ustar indicator
91
+ if len(magic) >= 512 and magic[257:262] == b"ustar":
92
+ return "tar"
93
+
94
+ return "unknown"
95
+
96
+
97
+ # ──────────────────────────────────────────────────────────────────────────────
98
+ # CREATE ARCHIVE
99
+ # ──────────────────────────────────────────────────────────────────────────────
100
+
101
+
102
+ def create_archive(
103
+ entries: list[Entry],
104
+ dest: Path,
105
+ format: str = "zip",
106
+ compression: str = "deflated",
107
+ compression_level: int = 6,
108
+ ) -> None:
109
+ """
110
+ Create archive from entries.
111
+
112
+ Args:
113
+ entries: List of Entry objects to archive
114
+ dest: Destination archive path
115
+ format: 'zip', 'tar', 'tar.gz', 'tar.bz2', 'tar.xz'
116
+ compression: For zip: 'stored' or 'deflated'
117
+ compression_level: 0-9 for gzip/bz2/xz
118
+ """
119
+ dest = Path(dest)
120
+ dest.parent.mkdir(parents=True, exist_ok=True)
121
+
122
+ format = format.lower()
123
+
124
+ if format == "zip":
125
+ _create_zip(entries, dest, compression, compression_level)
126
+ elif format in ("tar", "tar.gz", "tar.bz2", "tar.xz"):
127
+ _create_tar(entries, dest, format, compression_level)
128
+ else:
129
+ raise ArchiveError(f"Unsupported archive format: {format}", str(dest))
130
+
131
+
132
+ def _create_zip(
133
+ entries: list[Entry],
134
+ dest: Path,
135
+ compression: str,
136
+ level: int,
137
+ ) -> None:
138
+ """Create ZIP archive."""
139
+ comp = zipfile.ZIP_DEFLATED if compression == "deflated" else zipfile.ZIP_STORED
140
+
141
+ with zipfile.ZipFile(dest, "w", compression=comp, compresslevel=level) as zf:
142
+ for entry in entries:
143
+ if entry.is_dir:
144
+ # Add directory entry
145
+ arcname = str(entry.path.relative_to(entry.path.parent)) + "/"
146
+ zf.writestr(zipfile.ZipInfo(arcname), b"")
147
+ else:
148
+ arcname = str(entry.path.relative_to(entry.path.parent))
149
+ zf.write(entry.path, arcname)
150
+
151
+
152
+ def _tar_add(tf: tarfile.TarFile, entries: list[Entry]) -> None:
153
+ """Add entries to an open tar file (arcname = entry basename)."""
154
+ for entry in entries:
155
+ arcname = str(entry.path.relative_to(entry.path.parent))
156
+ tf.add(entry.path, arcname=arcname)
157
+
158
+
159
+ def _create_tar(
160
+ entries: list[Entry],
161
+ dest: Path,
162
+ format: str,
163
+ level: int,
164
+ ) -> None:
165
+ """Create TAR archive (optionally compressed)."""
166
+ if format == "tar.gz":
167
+ with tarfile.open(dest, "w:gz", compresslevel=level) as tf:
168
+ _tar_add(tf, entries)
169
+ elif format == "tar.bz2":
170
+ with tarfile.open(dest, "w:bz2", compresslevel=level) as tf:
171
+ _tar_add(tf, entries)
172
+ elif format == "tar.xz":
173
+ # lzma doesn't accept compresslevel in tarfile
174
+ with tarfile.open(dest, "w:xz") as tf:
175
+ _tar_add(tf, entries)
176
+ elif format == "tar":
177
+ with tarfile.open(dest, "w") as tf:
178
+ _tar_add(tf, entries)
179
+ else:
180
+ raise ArchiveError(f"Unknown tar format: {format}", str(dest))
181
+
182
+
183
+ # ──────────────────────────────────────────────────────────────────────────────
184
+ # EXTRACT ARCHIVE
185
+ # ──────────────────────────────────────────────────────────────────────────────
186
+
187
+
188
+ def extract_archive(
189
+ archive: Path,
190
+ dest: Path,
191
+ overwrite: bool = False,
192
+ members: list[str] | None = None,
193
+ ) -> list[Path]:
194
+ """
195
+ Extract archive to destination.
196
+
197
+ Args:
198
+ archive: Archive path
199
+ dest: Destination directory
200
+ overwrite: Overwrite existing files
201
+ members: Specific members to extract (None = all)
202
+
203
+ Returns:
204
+ List of extracted paths
205
+ """
206
+ archive = Path(archive)
207
+ dest = Path(dest).resolve()
208
+ dest.mkdir(parents=True, exist_ok=True)
209
+
210
+ archive_type = detect_archive_type(archive)
211
+ extracted = []
212
+
213
+ if archive_type == "zip":
214
+ extracted = _extract_zip(archive, dest, overwrite, members)
215
+ elif archive_type in ("tar", "tar.gz", "tar.bz2", "tar.xz"):
216
+ extracted = _extract_tar(archive, dest, overwrite, members)
217
+ elif archive_type in ("gz", "bz2", "xz"):
218
+ extracted = _extract_compressed(archive, dest, overwrite)
219
+ else:
220
+ raise ArchiveError(f"Cannot extract unknown format: {archive_type}", str(archive))
221
+
222
+ return extracted
223
+
224
+
225
+ def _extract_zip(
226
+ archive: Path,
227
+ dest: Path,
228
+ overwrite: bool,
229
+ members: list[str] | None,
230
+ ) -> list[Path]:
231
+ """Extract ZIP archive with path traversal protection."""
232
+ extracted = []
233
+
234
+ with zipfile.ZipFile(archive, "r") as zf:
235
+ for member in zf.namelist():
236
+ if members and member not in members:
237
+ continue
238
+
239
+ # Path traversal protection
240
+ member_path = (dest / member).resolve()
241
+ if not is_subpath(dest, member_path):
242
+ logger.warning(f"Skipping potentially dangerous path: {member}")
243
+ continue
244
+
245
+ if member_path.exists() and not overwrite:
246
+ continue
247
+
248
+ if member.endswith("/"):
249
+ member_path.mkdir(parents=True, exist_ok=True)
250
+ else:
251
+ member_path.parent.mkdir(parents=True, exist_ok=True)
252
+ zf.extract(member, dest)
253
+
254
+ extracted.append(member_path)
255
+
256
+ return extracted
257
+
258
+
259
+ def _extract_tar(
260
+ archive: Path,
261
+ dest: Path,
262
+ overwrite: bool,
263
+ members: list[str] | None,
264
+ ) -> list[Path]:
265
+ """Extract TAR archive with path traversal protection."""
266
+ extracted = []
267
+
268
+ with tarfile.open(archive, "r:*") as tf:
269
+ for member in tf.getmembers():
270
+ if members and member.name not in members:
271
+ continue
272
+
273
+ # Path traversal protection
274
+ member_path = (dest / member.name).resolve()
275
+ if not is_subpath(dest, member_path):
276
+ logger.warning(f"Skipping potentially dangerous path: {member.name}")
277
+ continue
278
+
279
+ if member_path.exists() and not overwrite:
280
+ continue
281
+
282
+ tf.extract(member, dest)
283
+ extracted.append(member_path)
284
+
285
+ return extracted
286
+
287
+
288
+ def _extract_compressed(
289
+ archive: Path,
290
+ dest: Path,
291
+ overwrite: bool,
292
+ ) -> list[Path]:
293
+ """Extract single-file compressed archive (gz, bz2, xz)."""
294
+ archive_type = detect_archive_type(archive)
295
+ output_name = archive.stem # Remove .gz, .bz2, .xz
296
+ output_path = dest / output_name
297
+
298
+ if output_path.exists() and not overwrite:
299
+ return []
300
+
301
+ if archive_type == "gz":
302
+ with gzip.open(archive, "rb") as f_in, output_path.open("wb") as f_out:
303
+ shutil.copyfileobj(f_in, f_out)
304
+ elif archive_type == "bz2":
305
+ with bz2.open(archive, "rb") as f_in, output_path.open("wb") as f_out:
306
+ shutil.copyfileobj(f_in, f_out)
307
+ elif archive_type == "xz":
308
+ with lzma.open(archive, "rb") as f_in, output_path.open("wb") as f_out:
309
+ shutil.copyfileobj(f_in, f_out)
310
+ else:
311
+ raise ArchiveError(f"Unknown compressed format: {archive_type}", str(archive))
312
+
313
+ return [output_path]
314
+
315
+
316
+ # ──────────────────────────────────────────────────────────────────────────────
317
+ # LIST ARCHIVE CONTENTS
318
+ # ──────────────────────────────────────────────────────────────────────────────
319
+
320
+
321
+ def list_archive(archive: Path) -> list[ArchiveEntry]:
322
+ """List contents of archive without extracting."""
323
+ archive_type = detect_archive_type(archive)
324
+ entries = []
325
+
326
+ if archive_type == "zip":
327
+ with zipfile.ZipFile(archive, "r") as zf:
328
+ for info in zf.infolist():
329
+ entries.append(
330
+ ArchiveEntry(
331
+ name=info.filename,
332
+ size=info.file_size,
333
+ is_dir=info.is_dir(),
334
+ modified=info.date_time and info.date_time[0] > 1980,
335
+ )
336
+ )
337
+ elif archive_type in ("tar", "tar.gz", "tar.bz2", "tar.xz"):
338
+ with tarfile.open(archive, "r:*") as tf:
339
+ for member in tf.getmembers():
340
+ entries.append(
341
+ ArchiveEntry(
342
+ name=member.name,
343
+ size=member.size,
344
+ is_dir=member.isdir(),
345
+ modified=member.mtime,
346
+ mode=member.mode,
347
+ )
348
+ )
349
+ else:
350
+ raise ArchiveError(f"Cannot list unknown format: {archive_type}", str(archive))
351
+
352
+ return entries
353
+
354
+
355
+ # ──────────────────────────────────────────────────────────────────────────────
356
+ # COMPRESS / DECOMPRESS SINGLE FILE
357
+ # ──────────────────────────────────────────────────────────────────────────────
358
+
359
+
360
+ def compress_file(
361
+ path: Path,
362
+ format: str = "gz",
363
+ level: int = 6,
364
+ keep_original: bool = True,
365
+ ) -> Path:
366
+ """
367
+ Compress a single file.
368
+
369
+ Args:
370
+ path: File to compress
371
+ format: 'gz', 'bz2', 'xz'
372
+ level: Compression level (0-9)
373
+ keep_original: Don't delete original
374
+
375
+ Returns:
376
+ Path to compressed file
377
+ """
378
+ path = Path(path)
379
+ if not path.is_file():
380
+ raise ArchiveError("Not a file", str(path))
381
+
382
+ format = format.lower()
383
+ if format == "gz":
384
+ out_path = path.with_suffix(path.suffix + ".gz")
385
+ with path.open("rb") as f_in, gzip.open(out_path, "wb", compresslevel=level) as f_out:
386
+ shutil.copyfileobj(f_in, f_out)
387
+ elif format == "bz2":
388
+ out_path = path.with_suffix(path.suffix + ".bz2")
389
+ with path.open("rb") as f_in, bz2.open(out_path, "wb", compresslevel=level) as f_out:
390
+ shutil.copyfileobj(f_in, f_out)
391
+ elif format == "xz":
392
+ out_path = path.with_suffix(path.suffix + ".xz")
393
+ with path.open("rb") as f_in, lzma.open(out_path, "wb", preset=level) as f_out:
394
+ shutil.copyfileobj(f_in, f_out)
395
+ else:
396
+ raise ArchiveError(f"Unsupported compression format: {format}", str(path))
397
+
398
+ if not keep_original:
399
+ path.unlink()
400
+
401
+ return out_path
402
+
403
+
404
+ def decompress_file(
405
+ path: Path,
406
+ keep_original: bool = False,
407
+ ) -> Path:
408
+ """
409
+ Decompress a single file.
410
+
411
+ Args:
412
+ path: Compressed file
413
+ keep_original: Don't delete compressed file
414
+
415
+ Returns:
416
+ Path to decompressed file
417
+ """
418
+ path = Path(path)
419
+ if not path.is_file():
420
+ raise ArchiveError("Not a file", str(path))
421
+
422
+ archive_type = detect_archive_type(path)
423
+ out_path = path.with_suffix("") # Remove compression suffix
424
+
425
+ if out_path.exists():
426
+ # Find unique name
427
+ i = 1
428
+ while out_path.exists():
429
+ out_path = path.with_stem(f"{path.stem}_{i}")
430
+ i += 1
431
+
432
+ if archive_type == "gz":
433
+ with gzip.open(path, "rb") as f_in, out_path.open("wb") as f_out:
434
+ shutil.copyfileobj(f_in, f_out)
435
+ elif archive_type == "bz2":
436
+ with bz2.open(path, "rb") as f_in, out_path.open("wb") as f_out:
437
+ shutil.copyfileobj(f_in, f_out)
438
+ elif archive_type == "xz":
439
+ with lzma.open(path, "rb") as f_in, out_path.open("wb") as f_out:
440
+ shutil.copyfileobj(f_in, f_out)
441
+ else:
442
+ raise ArchiveError(f"Cannot decompress: {archive_type}", str(path))
443
+
444
+ if not keep_original:
445
+ path.unlink()
446
+
447
+ return out_path