mkzip.py (2212B)
1 #!/usr/bin/env python3 2 """Build a zip from files and folders (pure python). 3 4 usage: mkzip.py OUT.zip [--prefix DIR/] [--exclude NAME]... ENTRY... 5 --prefix DIR/ put everything under that folder inside the zip (so unzipping doesn't spill files) 6 and store normal permissions: 0755 for scripts (*.sh, *.py, AppRun), 0644 otherwise 7 (shared folders report every file as rwxrwx---) 8 --exclude NAME skips files (or whole folders) with that name inside added folders (e.g. regions that are now 9 reserved in the binary and no longer read from disk) 10 ENTRY is path or path:name_in_zip (folders are added recursively). 11 Missing entries are skipped with a note, so optional files (res/, fnt.bin) don't break the build. 12 """ 13 import os, sys, zipfile 14 15 out, args = sys.argv[1], sys.argv[2:] 16 exclude, entries, prefix = set(), [], "" 17 while args: 18 a = args.pop(0) 19 if a == "--exclude": exclude.add(args.pop(0)) 20 elif a == "--prefix": prefix = args.pop(0) 21 else: entries.append(a) 22 23 def add(z, path, arcname): 24 arcname = prefix + arcname 25 if prefix: 26 zi = zipfile.ZipInfo.from_file(path, arcname) 27 script = arcname.endswith((".sh", ".py")) or os.path.basename(arcname) == "AppRun" 28 zi.external_attr = (0o755 if script else 0o644) << 16 29 zi.compress_type = zipfile.ZIP_DEFLATED 30 with open(path, "rb") as f: 31 z.writestr(zi, f.read(), compresslevel=9) 32 else: 33 z.write(path, arcname) 34 n = 0 35 with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as z: 36 for e in entries: 37 src, _, name = e.partition(":") 38 name = name or src 39 if os.path.isdir(src): 40 for d, dirs, fs in os.walk(src): 41 dirs[:] = sorted(x for x in dirs if x not in exclude) 42 for f in sorted(f for f in fs if f not in exclude): 43 p = os.path.join(d, f) 44 add(z, p, os.path.join(name, os.path.relpath(p, src))) 45 n += 1 46 elif os.path.isfile(src): 47 add(z, src, name); n += 1 48 else: 49 print(" skipping missing:", src) 50 print("%s: %d files, %d KB" % (out, n, os.path.getsize(out) >> 10))