Files

125 lines
4.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""extfix - detect a file's real type by magic bytes and fix a wrong extension.
Usage: extfix [dir] [--dry-run] [--apply] [--selftest] [--help]
Reads each file's magic bytes (JPEG, PNG, GIF, PDF, ZIP, gzip, tar, ELF,
SQLite, MP3, WAV, WebP, TIFF, BMP, 7z, xz, bzip2, zstd, MP4, ...), compares
against its current extension, and reports mismatches. With --apply it
renames the file to the correct extension (never overwriting: clashes get a
`_2` suffix). Files whose type is unknown are left alone and listed as such
only with --verbose.
"""
import argparse, os, sys, tempfile
from pathlib import Path
MAGIC = [
(b"\xff\xd8\xff", ".jpg"),
(b"\x89PNG\r\n\x1a\n", ".png"),
(b"GIF87a", ".gif"), (b"GIF89a", ".gif"),
(b"%PDF-", ".pdf"),
(b"PK\x03\x04", ".zip"), (b"PK\x05\x06", ".zip"), (b"PK\x07\x08", ".zip"),
(b"\x1f\x8b", ".gz"),
(b"BZh", ".bz2"),
(b"\xfd7zXZ\x00", ".xz"),
(b"\x28\xb5\x2f\xfd", ".zst"),
(b"7z\xbc\xaf'\x1c", ".7z"),
(b"\x7fELF", ""), # ELF: no extension
(b"SQLite format 3\x00", ".db"),
(b"RIFF", ".wav"), # refined below for WEBP
(b"\xff\xfb", ".mp3"), (b"ID3", ".mp3"),
(b"\x00\x00\x01\x00", ".ico"),
(b"BM", ".bmp"),
(b"II*\x00", ".tif"), (b"MM\x00*", ".tif"),
]
# aliases: extensions that are acceptable for a detected type
ALIASES = {
".jpg": {".jpg", ".jpeg"},
".tif": {".tif", ".tiff"},
".gz": {".gz", ".tgz"},
".zip": {".zip", ".jar", ".docx", ".xlsx", ".pptx", ".apk", ".epub"},
".db": {".db", ".sqlite", ".sqlite3"},
".mp3": {".mp3"},
".wav": {".wav"},
}
def detect(data):
if data[:12].endswith(b"WEBP") and data[:4] == b"RIFF":
return ".webp"
if len(data) >= 12 and data[4:8] == b"ftyp":
return ".mp4"
if len(data) >= 262 and data[257:262] == b"ustar":
return ".tar"
for magic, ext in MAGIC:
if data.startswith(magic):
return ext
return None
def selftest():
with tempfile.TemporaryDirectory() as td:
base = Path(td)
(base / "photo.txt").write_bytes(b"\xff\xd8\xff\xe0" + b"\x00" * 20)
(base / "doc.jpg").write_bytes(b"%PDF-1.7\n" + b"\x00" * 20)
(base / "real.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 20)
(base / "mystery.xyz").write_bytes(b"hello world, plain text here")
import subprocess
r = subprocess.run([sys.executable, __file__, str(base), "--apply"],
capture_output=True, text=True)
assert r.returncode == 0, r.stderr
assert (base / "photo.jpg").exists(), r.stdout
assert (base / "doc.pdf").exists(), r.stdout
assert (base / "real.png").exists()
assert (base / "mystery.xyz").exists()
print("selftest OK: photo.txt->photo.jpg, doc.jpg->doc.pdf, correct + unknown left alone")
return 0
def main():
ap = argparse.ArgumentParser(description="extfix - fix wrong file extensions by magic bytes")
ap.add_argument("dir", nargs="?", default=".")
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--apply", action="store_true", help="actually rename mismatched files")
ap.add_argument("--verbose", action="store_true")
ap.add_argument("--selftest", action="store_true")
a = ap.parse_args()
if a.selftest:
return selftest()
root = Path(a.dir)
if not root.is_dir():
print(f"extfix: {a.dir}: not a directory", file=sys.stderr); return 2
mismatches = []
unknown = 0
for p in sorted(root.rglob("*")):
if not p.is_file():
continue
try:
data = p.read_bytes()[:300]
except OSError:
continue
real = detect(data)
if real is None:
unknown += 1
if a.verbose:
print(f"unknown: {p}")
continue
if real == "":
continue # ELF etc: no extension to fix
cur = p.suffix.lower()
ok_exts = ALIASES.get(real, {real})
if cur not in ok_exts:
mismatches.append((p, real))
if not mismatches:
print(f"no mismatched extensions ({unknown} unknown type(s) skipped)"); return 0
for p, real in mismatches:
print(f"{p} : {p.suffix or '(none)'} -> {real}")
if not a.apply:
print(f"report only: {len(mismatches)} mismatch(es); use --apply to fix"); return 0
for p, real in mismatches:
target = p.with_suffix(real)
i = 2
while target.exists():
target = p.with_name(f"{p.stem}_{i}{real}"); i += 1
p.rename(target)
print(f"fixed {len(mismatches)} extension(s)")
return 0
if __name__ == "__main__":
sys.exit(main())