TestAICodetoZip / zip_util.py
MegaTronX's picture
Upload 5 files
313dc05 verified
import os
import zipfile
import uuid
from typing import List, Tuple
def make_zip_from_files(
files: List[Tuple[str, str]],
zip_name: str = None,
out_dir: str = "/tmp"
) -> str:
"""
Take a list of (filename, content) tuples, write them into a temp folder,
zip them, and return the path to the zip file.
"""
if zip_name is None:
zip_name = f"code_bundle_{uuid.uuid4().hex}.zip"
zip_path = os.path.join(out_dir, zip_name)
# Make a temp working directory
temp_dir = os.path.join(out_dir, f"code_dir_{uuid.uuid4().hex}")
os.makedirs(temp_dir, exist_ok=True)
for fname, content in files:
# ensure subdirectories exist
full_path = os.path.join(temp_dir, fname)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
with open(full_path, "w", encoding="utf-8") as f:
f.write(content)
# create zip
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
for root, _, fnames in os.walk(temp_dir):
for f in fnames:
full = os.path.join(root, f)
# store relative path inside zip
rel = os.path.relpath(full, start=temp_dir)
zf.write(full, arcname=rel)
return zip_path