packlens 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.
packlens/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Packlens: inspect, verify and compare archives without extracting them."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ __all__ = ["__version__"]
packlens/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from packlens.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
File without changes
@@ -0,0 +1,174 @@
1
+ """Compare two archives without extracting either.
2
+
3
+ A matching size is never reported as "identical". Only a hash comparison (``--by hash``),
4
+ or two empty files, establishes that content is the same.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import enum
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ from packlens.analysis.paths import normalized_key
14
+ from packlens.core.errors import ArchiveReadError, UnsupportedFeatureError
15
+ from packlens.core.models import ArchiveEntry, EntryType
16
+ from packlens.formats.base import ArchiveHandler
17
+ from packlens.utils.formatting import json_safe
18
+ from packlens.utils.hashing import hash_stream
19
+
20
+ MTIME_TOLERANCE_SECONDS = 2 # ZIP timestamps have 2-second resolution
21
+
22
+
23
+ class CompareMode(str, enum.Enum):
24
+ PATH = "path" # which paths exist
25
+ SIZE = "size" # paths plus sizes (and CRC-32 where both archives have it)
26
+ HASH = "hash" # paths plus SHA-256 of content
27
+
28
+
29
+ @dataclass
30
+ class Change:
31
+ path: str
32
+ reasons: list[str]
33
+ old: ArchiveEntry
34
+ new: ArchiveEntry
35
+
36
+
37
+ @dataclass
38
+ class ComparisonReport:
39
+ mode: CompareMode
40
+ old_name: str
41
+ new_name: str
42
+ added: list[ArchiveEntry] = field(default_factory=list)
43
+ removed: list[ArchiveEntry] = field(default_factory=list)
44
+ changed: list[Change] = field(default_factory=list)
45
+ in_both: int = 0
46
+ identical: int = 0 # content proven equal (hash match, or both empty)
47
+ same_size_unverified: int = 0 # size matches; content was NOT compared
48
+ unverifiable: list[tuple[str, str]] = field(default_factory=list)
49
+ metadata_changes: list[tuple[str, dict[str, tuple[str, str]]]] = field(default_factory=list)
50
+ repeated_paths_old: int = 0
51
+ repeated_paths_new: int = 0
52
+
53
+ def to_dict(self) -> dict[str, Any]:
54
+ return {
55
+ "mode": self.mode.value,
56
+ "old": json_safe(self.old_name),
57
+ "new": json_safe(self.new_name),
58
+ "summary": {
59
+ "added": len(self.added),
60
+ "removed": len(self.removed),
61
+ "changed": len(self.changed),
62
+ "in_both": self.in_both,
63
+ "identical": self.identical,
64
+ "same_size_content_not_compared": self.same_size_unverified,
65
+ "unverifiable": len(self.unverifiable),
66
+ },
67
+ "added": [e.to_dict() for e in self.added],
68
+ "removed": [e.to_dict() for e in self.removed],
69
+ "changed": [
70
+ {"path": json_safe(c.path), "reasons": c.reasons, "old": c.old.to_dict(), "new": c.new.to_dict()}
71
+ for c in self.changed
72
+ ],
73
+ "unverifiable": [{"path": json_safe(p), "reason": json_safe(r)} for p, r in self.unverifiable],
74
+ "metadata_changes": [{"path": json_safe(p), "differences": d} for p, d in self.metadata_changes],
75
+ "repeated_paths": {"old": self.repeated_paths_old, "new": self.repeated_paths_new},
76
+ }
77
+
78
+
79
+ def _index(handler: ArchiveHandler) -> tuple[dict[str, ArchiveEntry], int]:
80
+ """Map normalised path to its winning entry (the last one, as on extraction)."""
81
+ table: dict[str, ArchiveEntry] = {}
82
+ repeats = 0
83
+ for entry in handler.entries():
84
+ key = normalized_key(entry.path)
85
+ if not key:
86
+ continue
87
+ if key in table and entry.type is not EntryType.DIRECTORY:
88
+ repeats += 1
89
+ table[key] = entry
90
+ return table, repeats
91
+
92
+
93
+ def _hash_entries(handler: ArchiveHandler, wanted: set[int]) -> tuple[dict[int, str], dict[int, str]]:
94
+ digests: dict[int, str] = {}
95
+ problems: dict[int, str] = {}
96
+ if not wanted:
97
+ return digests, problems
98
+ for entry, stream in handler.iter_data(select=lambda e: e.index in wanted):
99
+ if stream is None or entry.index not in wanted:
100
+ continue
101
+ try:
102
+ digests[entry.index], _ = hash_stream(stream)
103
+ except (ArchiveReadError, UnsupportedFeatureError) as exc:
104
+ problems[entry.index] = str(exc)
105
+ return digests, problems
106
+
107
+
108
+ def _metadata_diff(old: ArchiveEntry, new: ArchiveEntry) -> dict[str, tuple[str, str]]:
109
+ diff: dict[str, tuple[str, str]] = {}
110
+ if old.mode is not None and new.mode is not None and old.mode != new.mode:
111
+ diff["mode"] = (f"{old.mode:04o}", f"{new.mode:04o}")
112
+ a, b = old.mtime, new.mtime
113
+ # Naive (ZIP) and aware (TAR) timestamps are not comparable; skip rather than guess.
114
+ if a is not None and b is not None and (a.tzinfo is None) == (b.tzinfo is None):
115
+ if abs((a - b).total_seconds()) > MTIME_TOLERANCE_SECONDS:
116
+ diff["mtime"] = (a.isoformat(), b.isoformat())
117
+ return diff
118
+
119
+
120
+ def compare_archives(
121
+ old: ArchiveHandler,
122
+ new: ArchiveHandler,
123
+ mode: CompareMode = CompareMode.SIZE,
124
+ *,
125
+ include_metadata: bool = False,
126
+ ) -> ComparisonReport:
127
+ report = ComparisonReport(mode, old.name, new.name)
128
+ old_index, report.repeated_paths_old = _index(old)
129
+ new_index, report.repeated_paths_new = _index(new)
130
+ report.removed = [old_index[k] for k in sorted(old_index.keys() - new_index.keys())]
131
+ report.added = [new_index[k] for k in sorted(new_index.keys() - old_index.keys())]
132
+
133
+ to_hash: list[tuple[str, ArchiveEntry, ArchiveEntry]] = []
134
+ for key in sorted(old_index.keys() & new_index.keys()):
135
+ a, b = old_index[key], new_index[key]
136
+ report.in_both += 1
137
+ reasons: list[str] = []
138
+ if a.type is not b.type:
139
+ reasons.append(f"type: {a.type.value} -> {b.type.value}")
140
+ elif a.type in (EntryType.SYMLINK, EntryType.HARDLINK):
141
+ if a.link_target != b.link_target:
142
+ reasons.append(f"link target: {a.link_target!r} -> {b.link_target!r}")
143
+ elif a.type is EntryType.FILE and mode is not CompareMode.PATH:
144
+ if a.size is None or b.size is None:
145
+ report.unverifiable.append((a.path, "size unknown in one archive"))
146
+ elif a.size != b.size:
147
+ reasons.append(f"size: {a.size:,} -> {b.size:,} bytes")
148
+ elif a.size == 0:
149
+ report.identical += 1 # two empty files are provably the same
150
+ elif a.crc32 is not None and b.crc32 is not None and a.crc32 != b.crc32:
151
+ reasons.append("content differs (CRC-32 mismatch)")
152
+ elif mode is CompareMode.HASH:
153
+ to_hash.append((key, a, b))
154
+ else:
155
+ report.same_size_unverified += 1
156
+ if reasons:
157
+ report.changed.append(Change(a.path, reasons, a, b))
158
+ elif include_metadata:
159
+ diff = _metadata_diff(a, b)
160
+ if diff:
161
+ report.metadata_changes.append((a.path, diff))
162
+
163
+ if to_hash:
164
+ old_digests, old_problems = _hash_entries(old, {a.index for _, a, _ in to_hash})
165
+ new_digests, new_problems = _hash_entries(new, {b.index for _, _, b in to_hash})
166
+ for _key, a, b in to_hash:
167
+ if a.index in old_problems or b.index in new_problems:
168
+ report.unverifiable.append((a.path, old_problems.get(a.index) or new_problems.get(b.index, "")))
169
+ elif old_digests.get(a.index) == new_digests.get(b.index) and a.index in old_digests:
170
+ report.identical += 1
171
+ else:
172
+ report.changed.append(Change(a.path, ["content differs (SHA-256)"], a, b))
173
+ report.changed.sort(key=lambda c: c.path)
174
+ return report
@@ -0,0 +1,119 @@
1
+ """Duplicate detection in stages: group by size, then hash only same-size candidates, streaming."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from collections import Counter, defaultdict
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Callable
9
+
10
+ from packlens.core.errors import ArchiveReadError, UnsupportedFeatureError
11
+ from packlens.core.models import EntryType
12
+ from packlens.formats.base import ArchiveHandler
13
+ from packlens.utils.formatting import json_safe
14
+ from packlens.utils.hashing import hash_stream
15
+
16
+ EMPTY_SHA256 = hashlib.sha256(b"").hexdigest()
17
+
18
+
19
+ @dataclass
20
+ class DuplicateGroup:
21
+ size: int
22
+ sha256: str
23
+ paths: list[str]
24
+
25
+ @property
26
+ def wasted(self) -> int:
27
+ return self.size * (len(self.paths) - 1)
28
+
29
+
30
+ @dataclass
31
+ class DuplicateReport:
32
+ archive: str
33
+ files_examined: int = 0
34
+ candidates_hashed: int = 0
35
+ bytes_hashed: int = 0
36
+ groups: list[DuplicateGroup] = field(default_factory=list) # identical *content*
37
+ repeated_paths: dict[str, int] = field(default_factory=dict) # same *name* stored more than once
38
+ skipped: list[tuple[str, str]] = field(default_factory=list)
39
+ error: str | None = None
40
+
41
+ @property
42
+ def wasted_bytes(self) -> int:
43
+ return sum(g.wasted for g in self.groups)
44
+
45
+ def to_dict(self) -> dict[str, Any]:
46
+ return {
47
+ "archive": json_safe(self.archive),
48
+ "files_examined": self.files_examined,
49
+ "candidates_hashed": self.candidates_hashed,
50
+ "bytes_hashed": self.bytes_hashed,
51
+ "duplicate_content": [
52
+ {"size": g.size, "sha256": g.sha256, "count": len(g.paths), "wasted_bytes": g.wasted, "paths": [json_safe(p) for p in g.paths]}
53
+ for g in self.groups
54
+ ],
55
+ "wasted_bytes": self.wasted_bytes,
56
+ "repeated_paths": {json_safe(p): n for p, n in self.repeated_paths.items()},
57
+ "skipped": [{"path": json_safe(p), "reason": json_safe(r)} for p, r in self.skipped],
58
+ "error": json_safe(self.error),
59
+ }
60
+
61
+
62
+ def find_duplicates(
63
+ handler: ArchiveHandler,
64
+ *,
65
+ include_empty: bool = False,
66
+ on_progress: Callable[[int], None] | None = None,
67
+ ) -> DuplicateReport:
68
+ report = DuplicateReport(archive=handler.info().name)
69
+ by_size: dict[int, list[tuple[int, str]]] = defaultdict(list)
70
+ path_counts: Counter[str] = Counter()
71
+ try:
72
+ for entry in handler.entries():
73
+ if entry.type is not EntryType.FILE:
74
+ continue
75
+ report.files_examined += 1
76
+ path_counts[entry.path] += 1
77
+ if entry.size is None:
78
+ continue
79
+ by_size[entry.size].append((entry.index, entry.path))
80
+ except ArchiveReadError as exc:
81
+ report.error = str(exc)
82
+ return report
83
+ report.repeated_paths = {p: n for p, n in path_counts.items() if n > 1}
84
+
85
+ found: dict[tuple[int, str], list[str]] = defaultdict(list)
86
+ candidates: dict[int, str] = {}
87
+ for size, members in by_size.items():
88
+ if len(members) < 2:
89
+ continue
90
+ if size == 0:
91
+ if include_empty:
92
+ found[(0, EMPTY_SHA256)].extend(p for _, p in members) # all empty files are identical
93
+ continue
94
+ candidates.update(members)
95
+ report.candidates_hashed = len(candidates)
96
+
97
+ if candidates:
98
+ done = 0
99
+ try:
100
+ for entry, stream in handler.iter_data(select=lambda e: e.index in candidates):
101
+ if stream is None or entry.index not in candidates:
102
+ continue
103
+ try:
104
+ digest, actual = hash_stream(stream)
105
+ except (ArchiveReadError, UnsupportedFeatureError) as exc:
106
+ report.skipped.append((entry.path, str(exc)))
107
+ continue
108
+ report.bytes_hashed += actual
109
+ found[(actual, digest)].append(entry.path)
110
+ done += 1
111
+ if on_progress:
112
+ on_progress(done)
113
+ except ArchiveReadError as exc:
114
+ report.error = str(exc)
115
+ report.groups = sorted(
116
+ (DuplicateGroup(size, digest, paths) for (size, digest), paths in found.items() if len(paths) > 1),
117
+ key=lambda g: (-g.wasted, g.paths[0]),
118
+ )
119
+ return report
@@ -0,0 +1,109 @@
1
+ """The ``inspect`` pipeline: stream entries once, accumulate statistics and findings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Callable
7
+
8
+ from packlens.analysis.paths import ArchiveAnalyzer
9
+ from packlens.core.errors import ArchiveReadError
10
+ from packlens.core.limits import Limits
11
+ from packlens.core.models import (
12
+ ArchiveFormat,
13
+ ArchiveInfo,
14
+ ArchiveStats,
15
+ Finding,
16
+ Severity,
17
+ )
18
+ from packlens.formats.base import ArchiveHandler
19
+ from packlens.utils.formatting import json_safe
20
+
21
+
22
+ @dataclass
23
+ class InspectionReport:
24
+ info: ArchiveInfo
25
+ stats: ArchiveStats
26
+ findings: list[Finding]
27
+ finding_counts: dict[str, int]
28
+ findings_suppressed: int = 0
29
+ error: str | None = None # set when the archive could only be listed partially
30
+ nested: list[Any] = field(default_factory=list)
31
+
32
+ @property
33
+ def warning_count(self) -> int:
34
+ return sum(1 for f in self.findings if f.severity is Severity.WARNING)
35
+
36
+ @property
37
+ def compression_ratio(self) -> float | None:
38
+ """Uncompressed / archive size. ``None`` where it is not meaningful (plain TAR, unknown sizes)."""
39
+ if self.info.format is ArchiveFormat.TAR or self.stats.size_unknown:
40
+ return None
41
+ if not self.info.compressed_size or not self.stats.total_size:
42
+ return None
43
+ return self.stats.total_size / self.info.compressed_size
44
+
45
+ def to_dict(self) -> dict[str, Any]:
46
+ stats = self.stats
47
+ ratio = self.compression_ratio
48
+ return {
49
+ "archive": {
50
+ "name": json_safe(self.info.name),
51
+ "format": self.info.format.value,
52
+ "compressed_size": self.info.compressed_size,
53
+ "metadata": {k: json_safe(v) for k, v in self.info.metadata.items()},
54
+ },
55
+ "summary": {
56
+ "entries": stats.entry_count,
57
+ "files": stats.file_count,
58
+ "directories": stats.directory_count,
59
+ "symlinks": stats.symlink_count,
60
+ "hardlinks": stats.hardlink_count,
61
+ "other": stats.other_count,
62
+ "uncompressed_size": None if stats.size_unknown else stats.total_size,
63
+ "compression_ratio": round(ratio, 3) if ratio is not None else None,
64
+ },
65
+ "integrity": {"available": self.info.integrity.available, "scope": self.info.integrity.scope},
66
+ "findings": [f.to_dict() for f in self.findings],
67
+ "finding_counts": dict(self.finding_counts),
68
+ "findings_not_listed": self.findings_suppressed,
69
+ "nested": [n.to_dict() for n in self.nested],
70
+ "error": json_safe(self.error),
71
+ }
72
+
73
+
74
+ def inspect_archive(
75
+ handler: ArchiveHandler,
76
+ limits: Limits,
77
+ *,
78
+ on_entry: Callable[[int], None] | None = None,
79
+ ) -> InspectionReport:
80
+ """Collect statistics and findings without holding entries in memory."""
81
+ stats = ArchiveStats()
82
+ analyzer = ArchiveAnalyzer(limits)
83
+ error: str | None = None
84
+ try:
85
+ for entry in handler.entries():
86
+ stats.add(entry)
87
+ analyzer.feed(entry)
88
+ if on_entry is not None and stats.entry_count % 1000 == 0:
89
+ on_entry(stats.entry_count)
90
+ except ArchiveReadError as exc:
91
+ error = str(exc)
92
+ info = handler.info()
93
+ analyzer.finish(info, stats)
94
+ findings = handler.notes() + analyzer.findings
95
+ return InspectionReport(
96
+ info=info,
97
+ stats=stats,
98
+ findings=findings,
99
+ finding_counts=dict(analyzer.counts) | _count_codes(handler.notes()),
100
+ findings_suppressed=analyzer.suppressed,
101
+ error=error,
102
+ )
103
+
104
+
105
+ def _count_codes(findings: list[Finding]) -> dict[str, int]:
106
+ counts: dict[str, int] = {}
107
+ for finding in findings:
108
+ counts[finding.code] = counts.get(finding.code, 0) + 1
109
+ return counts
@@ -0,0 +1,156 @@
1
+ """Integrity verification: read every byte and let the format's own checks run.
2
+
3
+ Results are kept honest: a check is *passed*, *failed*, or *unavailable*, and the report says
4
+ what kind of verification actually took place (content checksums versus structure only).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import enum
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Callable
12
+
13
+ from packlens.core.errors import ArchiveReadError, UnsupportedFeatureError
14
+ from packlens.core.models import ArchiveEntry, ArchiveFormat
15
+ from packlens.formats.base import ArchiveHandler
16
+ from packlens.utils.formatting import json_safe
17
+ from packlens.utils.hashing import CHUNK_SIZE
18
+
19
+ MAX_STORED_RESULTS = 1000
20
+
21
+
22
+ class CheckStatus(str, enum.Enum):
23
+ PASSED = "passed"
24
+ FAILED = "failed"
25
+ UNAVAILABLE = "unavailable"
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class CheckResult:
30
+ name: str
31
+ status: CheckStatus
32
+ detail: str
33
+ path: str | None = None
34
+
35
+ def to_dict(self) -> dict[str, Any]:
36
+ return {"name": self.name, "status": self.status.value, "detail": json_safe(self.detail), "path": json_safe(self.path)}
37
+
38
+
39
+ @dataclass
40
+ class VerifyReport:
41
+ archive: str
42
+ format: ArchiveFormat
43
+ scope: str
44
+ checksums_per_entry: bool # does the format carry checksums that were compared?
45
+ integrity_available: bool
46
+ entries_total: int = 0
47
+ entries_without_data: int = 0 # directories, links and other entries with nothing to read
48
+ passed: int = 0
49
+ failed: int = 0
50
+ unavailable: int = 0
51
+ bytes_read: int = 0
52
+ structure: CheckResult | None = None
53
+ results: list[CheckResult] = field(default_factory=list) # failures and unavailable checks only
54
+ results_not_listed: int = 0
55
+
56
+ @property
57
+ def verdict(self) -> str:
58
+ structure_failed = self.structure is not None and self.structure.status is CheckStatus.FAILED
59
+ if self.failed or structure_failed:
60
+ return "failed"
61
+ if self.unavailable or not self.integrity_available:
62
+ return "incomplete"
63
+ return "passed"
64
+
65
+ @property
66
+ def level(self) -> str:
67
+ """What the passed checks actually establish."""
68
+ if self.checksums_per_entry and self.integrity_available:
69
+ return "content-checksums"
70
+ return "structure-and-readability"
71
+
72
+ def to_dict(self) -> dict[str, Any]:
73
+ return {
74
+ "archive": json_safe(self.archive),
75
+ "format": self.format.value,
76
+ "verdict": self.verdict,
77
+ "level": self.level,
78
+ "scope": self.scope,
79
+ "entries": {
80
+ "total": self.entries_total,
81
+ "without_data": self.entries_without_data,
82
+ "passed": self.passed,
83
+ "failed": self.failed,
84
+ "unavailable": self.unavailable,
85
+ },
86
+ "bytes_read": self.bytes_read,
87
+ "structure": self.structure.to_dict() if self.structure else None,
88
+ "problems": [r.to_dict() for r in self.results],
89
+ "problems_not_listed": self.results_not_listed,
90
+ }
91
+
92
+
93
+ def verify_archive(
94
+ handler: ArchiveHandler,
95
+ *,
96
+ on_result: Callable[[ArchiveEntry, CheckResult], None] | None = None,
97
+ on_entry: Callable[[int], None] | None = None,
98
+ ) -> VerifyReport:
99
+ """Read the whole archive, collecting per-entry results. Resource-limit errors propagate."""
100
+ info = handler.info()
101
+ fmt = handler.format
102
+ report = VerifyReport(
103
+ archive=info.name,
104
+ format=fmt,
105
+ scope=info.integrity.scope,
106
+ checksums_per_entry=fmt is ArchiveFormat.ZIP or fmt.is_stream,
107
+ integrity_available=info.integrity.available,
108
+ )
109
+
110
+ def record(entry: ArchiveEntry, result: CheckResult) -> None:
111
+ if result.status is CheckStatus.PASSED:
112
+ report.passed += 1
113
+ else:
114
+ if result.status is CheckStatus.FAILED:
115
+ report.failed += 1
116
+ else:
117
+ report.unavailable += 1
118
+ if len(report.results) < MAX_STORED_RESULTS:
119
+ report.results.append(result)
120
+ else:
121
+ report.results_not_listed += 1
122
+ if on_result:
123
+ on_result(entry, result)
124
+
125
+ pass_detail = {
126
+ True: "content checksum matched",
127
+ False: "readable and size matches header (format has no content checksum)",
128
+ }[report.checksums_per_entry and info.integrity.available]
129
+ try:
130
+ for entry, stream in handler.iter_data(select=lambda _e: True, complete=True):
131
+ report.entries_total += 1
132
+ if on_entry and report.entries_total % 100 == 0:
133
+ on_entry(report.entries_total)
134
+ if stream is None:
135
+ report.entries_without_data += 1
136
+ continue
137
+ try:
138
+ total = 0
139
+ while True:
140
+ chunk = stream.read(CHUNK_SIZE)
141
+ if not chunk:
142
+ break
143
+ total += len(chunk)
144
+ report.bytes_read += total
145
+ if entry.size is not None and total != entry.size:
146
+ record(entry, CheckResult("entry-data", CheckStatus.FAILED, f"declared size {entry.size:,} bytes but {total:,} were read", entry.path))
147
+ else:
148
+ record(entry, CheckResult("entry-data", CheckStatus.PASSED, pass_detail, entry.path))
149
+ except UnsupportedFeatureError as exc:
150
+ record(entry, CheckResult("entry-data", CheckStatus.UNAVAILABLE, str(exc), entry.path))
151
+ except ArchiveReadError as exc:
152
+ record(entry, CheckResult("entry-data", CheckStatus.FAILED, str(exc), entry.path))
153
+ report.structure = CheckResult("archive-structure", CheckStatus.PASSED, "all headers and the end of the archive are well-formed")
154
+ except ArchiveReadError as exc:
155
+ report.structure = CheckResult("archive-structure", CheckStatus.FAILED, str(exc))
156
+ return report
@@ -0,0 +1,59 @@
1
+ """Detection of archives stored inside archives, and bounded in-memory inspection of them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from packlens.core.models import ArchiveFormat
6
+
7
+ # Longest suffixes first so ``.tar.gz`` wins over ``.gz``.
8
+ _SUFFIX_LABELS: tuple[tuple[str, str], ...] = (
9
+ (".tar.gz", "tar.gz"),
10
+ (".tar.bz2", "tar.bz2"),
11
+ (".tar.xz", "tar.xz"),
12
+ (".tar.zst", "tar.zst"),
13
+ (".tgz", "tar.gz"),
14
+ (".tbz2", "tar.bz2"),
15
+ (".tbz", "tar.bz2"),
16
+ (".txz", "tar.xz"),
17
+ (".tar", "tar"),
18
+ (".zip", "zip"),
19
+ (".jar", "zip"),
20
+ (".war", "zip"),
21
+ (".ear", "zip"),
22
+ (".whl", "zip"),
23
+ (".gz", "gzip"),
24
+ (".bz2", "bzip2"),
25
+ (".xz", "xz"),
26
+ (".7z", "7z"),
27
+ (".rar", "rar"),
28
+ (".zst", "zstd"),
29
+ )
30
+
31
+ _SUPPORTED_LABELS = {"tar.gz", "tar.bz2", "tar.xz", "tar", "zip", "gzip", "bzip2", "xz"}
32
+
33
+
34
+ def archive_label_from_name(path: str) -> str | None:
35
+ """Guess the archive type from a file name alone. Cheap; the content is not examined."""
36
+ lowered = path.rsplit("/", 1)[-1].lower()
37
+ for suffix, label in _SUFFIX_LABELS:
38
+ if lowered.endswith(suffix) and len(lowered) > len(suffix):
39
+ return label
40
+ return None
41
+
42
+
43
+ def is_supported_label(label: str) -> bool:
44
+ return label in _SUPPORTED_LABELS
45
+
46
+
47
+ def magic_format(head: bytes) -> ArchiveFormat | None:
48
+ """Cheap container sniffing on the first 512 bytes (compressed tars show as their codec)."""
49
+ if head.startswith((b"PK\x03\x04", b"PK\x05\x06")):
50
+ return ArchiveFormat.ZIP
51
+ if head[:2] == b"\x1f\x8b":
52
+ return ArchiveFormat.GZIP
53
+ if head[:3] == b"BZh" and head[3:4].isdigit():
54
+ return ArchiveFormat.BZIP2
55
+ if head[:6] == b"\xfd7zXZ\x00":
56
+ return ArchiveFormat.XZ
57
+ if head[257:262] == b"ustar":
58
+ return ArchiveFormat.TAR
59
+ return None