Skip to content

Effort free video editing!

6.5 KB
Raw Blame
"""Wrap release binaries in wheels so `pip install auto-editor` gets one.

usage: python3 scripts/wheel.py [-o DIR] BINARY...

Each binary becomes one wheel. Its platform tag is read out of the binary
because that is the only place the real requirement lives: the glibc a Linux
build needs depends on the machine that linked it.
"""

import argparse
import base64
import hashlib
import re
import struct
import sys
import zipfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent


def elf_tag(data: bytes) -> str:
    wide = data[4] == 2
    end = "<" if data[5] == 1 else ">"
    arch = {62: "x86_64", 183: "aarch64", 40: "armv7l"}.get(
        struct.unpack_from(end + "H", data, 18)[0]
    )
    if arch is None:
        raise ValueError("unsupported ELF machine")

    if wide:
        phoff = struct.unpack_from(end + "Q", data, 32)[0]
        phentsize, phnum = struct.unpack_from(end + "HH", data, 54)
    else:
        phoff = struct.unpack_from(end + "I", data, 28)[0]
        phentsize, phnum = struct.unpack_from(end + "HH", data, 42)
    PT_INTERP = 3
    dynamic = any(
        struct.unpack_from(end + "I", data, phoff + i * phentsize)[0] == PT_INTERP
        for i in range(phnum)
    )

    if not dynamic:
        # No libc is loaded at run time, so either kind of system can run it.
        return f"manylinux_2_17_{arch}.manylinux2014_{arch}.musllinux_1_1_{arch}"
    if b"ld-musl" in data:
        raise ValueError("dynamic musl builds are not handled")

    # The symbol versions a dynamic binary asks for are the only place these
    # strings appear, and the newest one is the oldest glibc that satisfies it.
    need = max(
        ((int(a), int(b)) for a, b in re.findall(rb"GLIBC_(\d+)\.(\d+)", data)),
        default=(2, 17),
    )
    need = max(need, (2, 17))
    return f"manylinux_{need[0]}_{need[1]}_{arch}"


def macho_tag(data: bytes) -> str:
    cputype, _, _, ncmds = struct.unpack_from("<IIII", data, 4)
    arch = {0x0100000C: "arm64", 0x01000007: "x86_64"}.get(cputype)
    if arch is None:
        raise ValueError("unsupported Mach-O cpu")

    LC_VERSION_MIN_MACOSX, LC_BUILD_VERSION = 0x24, 0x32
    off = 32
    for _ in range(ncmds):
        cmd, size = struct.unpack_from("<II", data, off)
        minos = None
        if cmd == LC_BUILD_VERSION:
            minos = struct.unpack_from("<I", data, off + 12)[0]
        elif cmd == LC_VERSION_MIN_MACOSX:
            minos = struct.unpack_from("<I", data, off + 8)[0]
        if minos is not None:
            major, minor = minos >> 16, (minos >> 8) & 0xFF
            # Installers only match a zero minor from macOS 11 on.
            return f"macosx_{major}_{0 if major >= 11 else minor}_{arch}"
        off += size
    raise ValueError("Mach-O has no minimum OS version")


def pe_tag(data: bytes) -> str:
    pe = struct.unpack_from("<I", data, 0x3C)[0]
    if data[pe : pe + 4] != b"PE\0\0":
        raise ValueError("not a PE file")
    machine = struct.unpack_from("<H", data, pe + 4)[0]
    arch = {0x8664: "win_amd64", 0xAA64: "win_arm64"}.get(machine)
    if arch is None:
        raise ValueError("unsupported PE machine")
    return arch


def platform_tag(data: bytes) -> tuple[str, str]:
    """Return the wheel platform tag and the installed script's name."""
    if data[:4] == b"\x7fELF":
        return elf_tag(data), "auto-editor"
    if data[:4] == b"\xcf\xfa\xed\xfe":
        return macho_tag(data), "auto-editor"
    if data[:2] == b"MZ":
        return pe_tag(data), "auto-editor.exe"
    raise ValueError("not an ELF, Mach-O, or PE binary")


def build(binary: Path, version: str, out: Path) -> Path:
    data = binary.read_bytes()
    plat, script = platform_tag(data)
    tag = f"py3-none-{plat}"
    name = f"auto_editor-{version}"

    metadata = (
        "Metadata-Version: 2.1\n"
        "Name: auto-editor\n"
        f"Version: {version}\n"
        "Summary: Auto-Editor: Effort free video editing!\n"
        "Home-page: https://auto-editor.com\n"
        "Author: WyattBlue\n"
        "License: Unlicense\n"
        "Project-URL: Source Code, https://github.com/WyattBlue/auto-editor\n"
        "Project-URL: Bug Tracker, https://github.com/WyattBlue/auto-editor/issues\n"
        "Keywords: video,audio,media,editor,editing,silence-removal\n"
        "Requires-Python: >=3.8\n"
        "Description-Content-Type: text/markdown\n"
        "\n" + (ROOT / "README.md").read_text(encoding="utf-8")
    ).encode()
    wheel = (
        "Wheel-Version: 1.0\n"
        "Generator: auto-editor scripts/wheel.py\n"
        "Root-Is-Purelib: false\n"
        + "".join(f"Tag: py3-none-{p}\n" for p in plat.split("."))
    ).encode()

    files = [
        # Installers copy anything under data/scripts into the environment's
        # bin directory as is, which is all a prebuilt executable needs.
        (f"{name}.data/scripts/{script}", data, 0o755),
        (f"{name}.dist-info/METADATA", metadata, 0o644),
        (f"{name}.dist-info/WHEEL", wheel, 0o644),
        (f"{name}.dist-info/LICENSE", (ROOT / "LICENSE").read_bytes(), 0o644),
    ]
    record = ""
    for path, body, _ in files:
        digest = base64.urlsafe_b64encode(hashlib.sha256(body).digest())
        record += f"{path},sha256={digest.rstrip(b'=').decode()},{len(body)}\n"
    record += f"{name}.dist-info/RECORD,,\n"
    files.append((f"{name}.dist-info/RECORD", record.encode(), 0o644))

    dest = out / f"{name}-{tag}.whl"
    with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as zf:
        for path, body, mode in files:
            # A fixed date keeps the wheel a pure function of its inputs.
            info = zipfile.ZipInfo(path, (1980, 1, 1, 0, 0, 0))
            info.compress_type = zipfile.ZIP_DEFLATED
            info.external_attr = (0o100000 | mode) << 16
            zf.writestr(info, body)
    return dest


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("binaries", nargs="+", type=Path)
    parser.add_argument("-o", "--out", type=Path, default=Path("dist"))
    args = parser.parse_args()

    about = (ROOT / "src" / "about.nim").read_text()
    version = re.search(r'version\* = "([^"]+)"', about).group(1)

    args.out.mkdir(parents=True, exist_ok=True)
    seen = {}
    for binary in args.binaries:
        try:
            dest = build(binary, version, args.out)
        except ValueError as e:
            sys.exit(f"{binary}: {e}")
        if dest.name in seen:
            sys.exit(f"{binary} and {seen[dest.name]} both make {dest.name}")
        seen[dest.name] = binary
        print(dest)


if __name__ == "__main__":
    main()