OLD | NEW |
---|---|
(Empty) | |
1 #!/usr/bin/env python | |
2 # | |
3 # Copyright 2016 Google Inc. | |
4 # | |
5 # Use of this source code is governed by a BSD-style license that can be | |
6 # found in the LICENSE file. | |
7 | |
8 | |
9 """Utilities for zipping and unzipping files.""" | |
10 | |
11 | |
12 import fnmatch | |
13 import os | |
14 import zipfile | |
15 | |
16 | |
17 def filtered(names, blacklist): | |
18 """Filter the list of file or directory names.""" | |
19 rv = names[:] | |
rmistry
2016/06/15 13:47:18
Just curious, why is this called rv?
borenet
2016/06/15 14:31:27
short for return value
rmistry
2016/06/15 14:49:40
You have been infected by the Go.
| |
20 for pattern in blacklist: | |
21 rv = [n for n in rv if not fnmatch.fnmatch(n, pattern)] | |
22 return rv | |
23 | |
24 | |
25 def zip(target_dir, zip_file, blacklist=None): # pylint: disable=W0622 | |
rmistry
2016/06/15 13:47:18
I think this will silently pass if target_dir does
borenet
2016/06/15 14:31:27
Done.
| |
26 """Zip the given directory, write to the given zip file.""" | |
27 blacklist = blacklist or [] | |
28 with zipfile.ZipFile(zip_file, 'w') as z: | |
29 for r, d, f in os.walk(target_dir, topdown=True): | |
30 d[:] = filtered(d, blacklist) | |
31 for filename in filtered(f, blacklist): | |
32 filepath = os.path.join(r, filename) | |
33 zi = zipfile.ZipInfo(filepath) | |
34 zi.filename = os.path.relpath(filepath, target_dir) | |
35 perms = os.stat(filepath).st_mode | |
36 zi.external_attr = perms << 16L | |
37 zi.compress_type = zipfile.ZIP_STORED | |
38 with open(filepath, 'rb') as f: | |
39 content = f.read() | |
40 z.writestr(zi, content) | |
41 for dirname in d: | |
42 dirpath = os.path.join(r, dirname) | |
43 z.write(dirpath, os.path.relpath(dirpath, target_dir)) | |
44 | |
45 | |
46 def unzip(zip_file, target_dir): | |
47 """Unzip the given zip file into the target dir.""" | |
48 if not os.path.isdir(target_dir): | |
49 os.makedirs(target_dir) | |
50 with zipfile.ZipFile(zip_file, 'r') as z: | |
51 for zi in z.infolist(): | |
52 dst_path = os.path.join(target_dir, zi.filename) | |
53 if zi.filename.endswith('/'): | |
54 os.mkdir(dst_path) | |
55 else: | |
56 with open(dst_path, 'w') as f: | |
57 f.write(z.read(zi)) | |
58 perms = zi.external_attr >> 16L | |
59 os.chmod(dst_path, perms) | |
OLD | NEW |