|
| 1 | +import zipfile |
| 2 | +import os |
| 3 | +import shutil |
| 4 | +import tempfile |
| 5 | +import logging |
| 6 | + |
| 7 | +ZIP_PATH = "dist/lambda.zip" |
| 8 | + |
| 9 | +# Configure logging |
| 10 | +logging.basicConfig( |
| 11 | + level=logging.INFO, |
| 12 | + format="%(asctime)s [%(levelname)s] %(message)s" |
| 13 | +) |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | +# Folders to prune (only safe unused folders) |
| 17 | +BOTOCORE_SAFE_PRUNE = [ |
| 18 | + "botocore/data/s3/tests", |
| 19 | + "botocore/data/glacier/tests", |
| 20 | +] |
| 21 | + |
| 22 | +BOTO3_SAFE_PRUNE = [ |
| 23 | + "boto3/examples" |
| 24 | +] |
| 25 | + |
| 26 | +def main(): |
| 27 | + if not os.path.exists(ZIP_PATH): |
| 28 | + logger.warning("ZIP file %s does not exist. Skipping cleanup.", ZIP_PATH) |
| 29 | + return |
| 30 | + |
| 31 | + tmp_dir = tempfile.mkdtemp(prefix="lambda_clean_") |
| 32 | + logger.info("Unzipping %s...", ZIP_PATH) |
| 33 | + with zipfile.ZipFile(ZIP_PATH, "r") as z: |
| 34 | + z.extractall(tmp_dir) |
| 35 | + |
| 36 | + # Remove only safe folders |
| 37 | + for folder_list in [BOTOCORE_SAFE_PRUNE, BOTO3_SAFE_PRUNE]: |
| 38 | + for rel in folder_list: |
| 39 | + target = os.path.join(tmp_dir, rel) |
| 40 | + if os.path.exists(target): |
| 41 | + logger.info("Removing %s", target) |
| 42 | + shutil.rmtree(target) |
| 43 | + |
| 44 | + # Re-create the cleaned zip |
| 45 | + logger.info("Re-zipping cleaned Lambda package...") |
| 46 | + with zipfile.ZipFile(ZIP_PATH, "w", zipfile.ZIP_DEFLATED) as z: |
| 47 | + for root, _, files in os.walk(tmp_dir): |
| 48 | + for f in files: |
| 49 | + abs_path = os.path.join(root, f) |
| 50 | + rel_path = os.path.relpath(abs_path, tmp_dir) |
| 51 | + z.write(abs_path, rel_path) |
| 52 | + |
| 53 | + shutil.rmtree(tmp_dir) |
| 54 | + logger.info("Cleaned Lambda saved at %s", ZIP_PATH) |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + logger.info("Running clean_lambda.py...") |
| 58 | + main() |
0 commit comments