libytdlp-sys 0.6.0

Raw FFI bindings to the libytdlp C ABI
#!/usr/bin/env python3
import os
import sys

WANTED = [
    ("libytdlp_bridge.options", "options.py"),
    ("libytdlp_bridge.serialize", "serialize.py"),
    ("libytdlp_bridge.extract", "extract.py"),
    ("libytdlp_bridge.download", "download.py"),
    ("libytdlp_bridge", "__init__.py"),
]


def main():
    out, *sources = sys.argv[1:]

    if len(sources) != len(WANTED):
        print("usage: embed_bridge.py OUT.h options.py serialize.py extract.py download.py __init__.py", file=sys.stderr)
        return 2

    entries = []

    for (name, base), path in zip(WANTED, sources):
        if os.path.basename(path) != base:
            print(f"expected {base}, got {path}", file=sys.stderr)
            return 2

        with open(path, encoding="utf-8") as handle:
            text = handle.read()

        if "\0" in text:
            print(f"bridge source holds NUL bytes: {path}", file=sys.stderr)
            return 1

        entries.append((name, path, text))

    with open(out, "w", encoding="utf-8") as handle:
        handle.write("// Generated by tools/embed_bridge.py. Do not edit.\n")
        handle.write("#ifndef LIBYTDLP_BRIDGE_SOURCES_H\n")
        handle.write("#define LIBYTDLP_BRIDGE_SOURCES_H\n\n")
        handle.write("namespace libytdlp {\n\n")
        handle.write("struct BridgeSource {\n")
        handle.write("    const char* module;\n")
        handle.write("    const char* file;\n")
        handle.write("    const char* text;\n")
        handle.write("};\n\n")

        for index, (name, path, text) in enumerate(entries):
            handle.write(f"static const char kBridgeSource{index}[] =\n")
            for line in text.splitlines(keepends=True):
                escaped = (
                    line.replace("\\", "\\\\")
                    .replace('"', '\\"')
                    .rstrip("\n")
                )
                handle.write(f'    "{escaped}\\n"\n')
            handle.write(";\n\n")

        handle.write("static const BridgeSource kBridgeSources[] = {\n")
        for index, (name, path, _) in enumerate(entries):
            handle.write(f'    {{"{name}", "{path}", kBridgeSource{index}}},\n')
        handle.write("};\n\n")
        handle.write("} // namespace libytdlp\n\n")
        handle.write("#endif\n")

    return 0


if __name__ == "__main__":
    raise SystemExit(main())