68 lines
3.1 KiB
Python
Executable File
68 lines
3.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# tarpeek — list tar/tar.gz/tar.bz2/tar.xz contents with a summary (by type, largest members), without extracting.
|
|
# Usage: tarpeek [--top N] [--by-ext] archive.tar.gz
|
|
"""tarpeek: peek inside any tarball. Unlike `tar -tvf` it adds a summary —
|
|
total sizes, breakdown by file extension, the largest members, and hardlink/
|
|
symlink counts — so you can judge an archive before unpacking it."""
|
|
import argparse, os, sys, tarfile
|
|
from collections import Counter, defaultdict
|
|
|
|
def human(n):
|
|
for u in ("B", "KiB", "MiB", "GiB"):
|
|
if abs(n) < 1024 or u == "GiB":
|
|
return f"{n:.1f}{u}" if u != "B" else f"{n}B"
|
|
n /= 1024.0
|
|
|
|
def peek(path, top=10, by_ext=False):
|
|
try:
|
|
tf = tarfile.open(path, "r:*")
|
|
except Exception as e:
|
|
print(f"tarpeek: {path}: {e}", file=sys.stderr); return 1
|
|
members = tf.getmembers()
|
|
files = [m for m in members if m.isfile()]
|
|
tot = sum(m.size for m in files)
|
|
print(f"{path}: {len(members)} members, {len(files)} files, {human(tot)} uncompressed")
|
|
print(f"{'size':>10} {'mode':>10} name")
|
|
for m in sorted(files, key=lambda m: -m.size)[:top]:
|
|
print(f"{human(m.size):>10} {oct(m.mode):>10} {m.name}")
|
|
if len(files) > top:
|
|
print(f" ... and {len(files)-top} smaller files")
|
|
kinds = Counter("dir" if m.isdir() else "symlink" if m.issym() else "hardlink" if m.islnk() else "file" if m.isfile() else "other" for m in members)
|
|
print("kinds:", dict(kinds))
|
|
if by_ext:
|
|
ext = defaultdict(lambda: [0, 0])
|
|
for m in files:
|
|
e = os.path.splitext(m.name)[1].lower() or "(none)"
|
|
ext[e][0] += 1; ext[e][1] += m.size
|
|
print("by extension:")
|
|
for e, (c, s) in sorted(ext.items(), key=lambda kv: -kv[1][1]):
|
|
print(f" {e:<12} {c:>4} files {human(s):>10}")
|
|
comp = os.path.getsize(path)
|
|
print(f"archive file: {human(comp)} on disk; compression: {tot/max(comp,1):.2f}x ({(1-comp/tot)*100:.1f}% saved)" if tot else "archive file: empty")
|
|
return 0
|
|
|
|
def selftest():
|
|
import tempfile, tarfile, io
|
|
with tempfile.TemporaryDirectory() as d:
|
|
p = os.path.join(d, "t.tar.gz")
|
|
with tarfile.open(p, "w:gz") as t:
|
|
for name, data in (("a.txt", b"x" * 5000), ("b.log", b"y" * 100), ("c.txt", b"z" * 50)):
|
|
ti = tarfile.TarInfo(name); ti.size = len(data)
|
|
t.addfile(ti, io.BytesIO(data))
|
|
assert peek(p, by_ext=True) == 0
|
|
print("tarpeek selftest: PASS"); return 0
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="List tarball contents with a size/type summary, without extracting.")
|
|
ap.add_argument("archive", nargs="?", help="tar archive (.tar, .tar.gz, .tar.bz2, .tar.xz)")
|
|
ap.add_argument("--top", type=int, default=10, help="largest members to show")
|
|
ap.add_argument("--by-ext", action="store_true", help="break down by file extension")
|
|
ap.add_argument("--selftest", action="store_true")
|
|
a = ap.parse_args()
|
|
if a.selftest: return selftest()
|
|
if not a.archive: ap.error("need an archive")
|
|
return peek(a.archive, a.top, a.by_ext)
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|