File size: 1,269 Bytes
313dc05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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