"""Packs a folder of assets into one zip, so a game opens one file instead of hundreds. python Scripts/packassets.py Every file is stored uncompressed. PNG and Ogg are compressed already, so deflating them again costs load time for nothing. The archive is the same bytes for the same folder, so a checked-in archive doesn't churn. - Paths inside the archive are relative to the folder, use forward slashes and keep their case. - Files are sorted by path, and each carries the zip format's earliest timestamp. - Folders get no entries of their own. """ import argparse import os import sys import zipfile EARLIEST_ZIP_TIME = (1980, 1, 1, 0, 0, 0) READ_CHUNK_BYTES = 1 << 20 class PackError(Exception): pass def list_files(folder): """Returns the path of every file under the folder, relative to it, sorted, with forward slashes.""" if not os.path.isdir(folder): raise PackError(f"{folder} isn't a folder.") returnMe = [] for directory, _, names in os.walk(folder): for name in names: relative = os.path.relpath(os.path.join(directory, name), folder) returnMe.append(relative.replace(os.sep, "/")) returnMe.sort() return returnMe def pack(folder, archive_path): """Writes the archive, and returns how many files it holds.""" paths = list_files(folder) if not paths: raise PackError(f"{folder} holds no files.") # Written beside the target and moved into place, so a failure never leaves half an archive. temporary = archive_path + ".tmp" try: with zipfile.ZipFile(temporary, "w", zipfile.ZIP_STORED) as archive: for path in paths: info = zipfile.ZipInfo(path, EARLIEST_ZIP_TIME) info.compress_type = zipfile.ZIP_STORED info.external_attr = 0o644 << 16 with open(os.path.join(folder, path.replace("/", os.sep)), "rb") as source: with archive.open(info, "w") as destination: while True: chunk = source.read(READ_CHUNK_BYTES) if not chunk: break destination.write(chunk) os.replace(temporary, archive_path) finally: if os.path.exists(temporary): os.remove(temporary) return len(paths) def main(arguments=None): parser = argparse.ArgumentParser(description="Packs a folder of assets into one uncompressed zip.") parser.add_argument("folder", help="the folder whose files go in the archive") parser.add_argument("archive", help="the zip file to write") parsed = parser.parse_args(arguments) try: count = pack(parsed.folder, parsed.archive) except (PackError, OSError) as error: print(f"error: {error}", file=sys.stderr) return 1 print(f"Packed {count} files into {parsed.archive}.") return 0 if __name__ == "__main__": sys.exit(main())