#!/usr/bin/env python3 """ Baixa pacotes MinGW do repositorio do MSYS2 (com as dependencias) e extrai numa pasta: include/, lib/ e bin/ (as DLLs) para compilar o TinyBlocks para Windows a partir do Linux. msys2_deps.py pacote [pacote ...] Os pacotes sao nomes sem prefixo (SDL2, libpng...). O indice do repositorio (.db) diz o arquivo e as dependencias de cada pacote. Os arquivos baixados ficam em /../cache e nao sao baixados de novo. """ import io, os, re, subprocess, sys, tarfile, urllib.request MIRROR = os.environ.get("MSYS2_MIRROR", "https://repo.msys2.org/mingw") REPO = {"x86_64": ("mingw64", "mingw-w64-x86_64-"), "i686": ("mingw32", "mingw-w64-i686-")} # Pacotes que nao precisam ir junto (o compilador ja traz o runtime) SKIP = {"crt", "headers", "libgccjit"} def fetch(url, path): if os.path.exists(path): return path print("baixando", url, flush=True) tmp = path + ".parte" with urllib.request.urlopen(url, timeout=60) as r, open(tmp, "wb") as f: while True: b = r.read(1 << 16) if not b: break f.write(b) os.replace(tmp, path) return path def unzst(path): return subprocess.run(["zstd", "-dc", path], check=True, capture_output=True).stdout def read_db(arch, cache): repo, prefix = REPO[arch] db = fetch(f"{MIRROR}/{arch}/{repo}.db", os.path.join(cache, f"{repo}.db")) raw = open(db, "rb").read() if raw[:4] == b"\x28\xb5\x2f\xfd": # zstd raw = unzst(db) pk = {} with tarfile.open(fileobj=io.BytesIO(raw)) as t: for m in t: if not m.name.endswith("/desc"): continue fields, key = {}, None for line in t.extractfile(m).read().decode().splitlines(): if line.startswith("%") and line.endswith("%"): key = line.strip("%"); fields[key] = [] elif line and key: fields[key].append(line) name = fields["NAME"][0] info = {"file": fields["FILENAME"][0], "deps": fields.get("DEPENDS", [])} pk[name] = info for p in fields.get("PROVIDES", []): pk.setdefault(re.split(r"[<>=]", p)[0], info) return pk, prefix def main(): if len(sys.argv) < 4 or sys.argv[1] not in REPO: sys.exit(__doc__) arch, dest, wanted = sys.argv[1], os.path.abspath(sys.argv[2]), sys.argv[3:] cache = os.path.join(os.path.dirname(dest), "cache") os.makedirs(cache, exist_ok=True) pk, prefix = read_db(arch, cache) todo, seen = [prefix + w for w in wanted], set() while todo: n = re.split(r"[<>=]", todo.pop())[0] if n in seen or n[len(prefix):] in SKIP: continue seen.add(n) if n not in pk: sys.exit(f"pacote nao encontrado no MSYS2: {n}") todo += pk[n]["deps"] os.makedirs(dest, exist_ok=True) root = REPO[arch][0] + "/" for n in sorted(seen): f = pk[n]["file"] path = fetch(f"{MIRROR}/{arch}/{f}", os.path.join(cache, f)) data = unzst(path) if f.endswith(".zst") else open(path, "rb").read() with tarfile.open(fileobj=io.BytesIO(data)) as t: for m in t: if not m.name.startswith(root) or not (m.isfile() or m.isdir()): continue rel = m.name[len(root):] if not rel or rel.startswith(("share/doc", "share/man", "share/info", "share/locale")): continue out = os.path.join(dest, rel) if not os.path.abspath(out).startswith(dest + os.sep): continue # nada fora da pasta if m.isdir(): os.makedirs(out, exist_ok=True) else: os.makedirs(os.path.dirname(out), exist_ok=True) with open(out, "wb") as o: o.write(t.extractfile(m).read()) print(f"{len(seen)} pacotes em {dest}") if __name__ == "__main__": main()