Skip to content

Instantly share code, notes, and snippets.

@filipeandre
Created July 2, 2024 18:53
Show Gist options
  • Save filipeandre/d586ceac7662f57982157d70fc5d6d6d to your computer and use it in GitHub Desktop.
Save filipeandre/d586ceac7662f57982157d70fc5d6d6d to your computer and use it in GitHub Desktop.
Create a zip to be used as python lambda
#!/usr/bin/env python
import os
import re
import zipfile
import site
import argparse
"""Package this lambda"""
ignore = ["__pycache__", "_pytest"]
exp = [re.compile(fr'.*/{p}(/.*)?$') for p in ignore]
def should_ignore(path: str):
for e in exp:
if e.match(path):
return True
return False
def package(dirs, dst):
"""create a zip file with custom directory targets"""
zf = zipfile.ZipFile("%s" % dst, "w", zipfile.ZIP_DEFLATED)
print('[*] packaging...')
count = 0
for src in dirs:
abs_src = os.path.expanduser(src["name"]) if src["name"].startswith('~') else os.path.abspath(src["name"])
if not os.path.isdir(abs_src):
arc_name = src["target"] + abs_src[len(abs_src) + 1:]
count = count+1
zf.write(abs_src, arc_name)
continue
for dirname, sub_dirs, files in os.walk(abs_src):
if should_ignore(dirname):
continue
for filename in files:
abs_name = os.path.abspath(os.path.join(dirname, filename))
arc_name = src["target"] + abs_name[len(abs_src) + 1:]
count = count+1
zf.write(abs_name, arc_name)
zf.close()
print('[✓] finished packaging %s files' % count)
argParser = argparse.ArgumentParser()
argParser.add_argument("-d", "--dest", help="destination zip")
args = argParser.parse_args()
package([
{"name": site.getsitepackages()[0], "target": "python/"},
], args.dest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment