9"""Utilities for zipping and unzipping files."""
12from __future__
import print_function
21 """Filter the list of file or directory names."""
23 for pattern
in to_skip:
24 rv = [n
for n
in rv
if not fnmatch.fnmatch(n, pattern)]
28def zip(target_dir, zip_file, to_skip=None):
29 """Zip the given directory, write to the given zip file."""
30 if not os.path.isdir(target_dir):
31 raise IOError(
'%s does not exist!' % target_dir)
32 to_skip = to_skip
or []
33 with zipfile.ZipFile(zip_file,
'w', zipfile.ZIP_DEFLATED,
True)
as z:
34 for r, d, f
in os.walk(target_dir, topdown=
True):
36 for filename
in filtered(f, to_skip):
37 filepath = os.path.join(r, filename)
38 zi = zipfile.ZipInfo(filepath)
39 zi.filename = os.path.relpath(filepath, target_dir)
42 zi.filename = zi.filename.replace(ntpath.sep, posixpath.sep)
44 perms = os.stat(filepath).st_mode
46 if os.path.islink(filepath):
47 print(
'Skipping symlink %s' % filepath)
51 zi.external_attr = perms << 16
52 zi.compress_type = zipfile.ZIP_DEFLATED
53 with open(filepath,
'rb')
as f:
55 z.writestr(zi, content)
57 dirpath = os.path.join(r, dirname)
58 z.write(dirpath, os.path.relpath(dirpath, target_dir))
62 """Unzip the given zip file into the target dir."""
63 if not os.path.isdir(target_dir):
64 os.makedirs(target_dir)
65 with zipfile.ZipFile(zip_file,
'r', zipfile.ZIP_DEFLATED,
True)
as z:
66 for zi
in z.infolist():
67 dst_subpath = zi.filename
70 dst_subpath = dst_subpath.replace(posixpath.sep, ntpath.sep)
71 dst_path = os.path.join(target_dir, dst_subpath)
72 if dst_path.endswith(os.path.sep):
75 with open(dst_path,
'wb')
as f:
77 perms = zi.external_attr >> 16
78 os.chmod(dst_path, perms)
def print(*args, **kwargs)
def filtered(names, to_skip)
def zip(target_dir, zip_file, to_skip=None)
def unzip(zip_file, target_dir)