OLD | NEW |
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
4 | 4 |
5 import os | 5 import os |
6 from io import BytesIO | 6 from io import BytesIO |
7 import re | 7 import re |
8 from zipfile import ZipFile | 8 from zipfile import ZipFile |
9 | 9 |
10 class ExampleZipper(object): | 10 class ExampleZipper(object): |
11 """This class creates a zip file given a samples directory. | 11 """This class creates a zip file given a samples directory. |
12 """ | 12 """ |
13 def __init__(self, file_system, cache_builder, base_path, match_path): | 13 def __init__(self, file_system, cache_builder, base_path, match_path): |
14 self._base_path = base_path | 14 self._base_path = base_path |
15 self._zip_cache = cache_builder.build(self._MakeZipFile) | 15 self._zip_cache = cache_builder.build(self._MakeZipFile) |
16 self._file_system = file_system | 16 self._file_system = file_system |
17 self._match_path = match_path | 17 self._match_path = match_path |
18 | 18 |
19 def _MakeZipFile(self, files): | 19 def _MakeZipFile(self, files): |
20 zip_path = os.path.commonprefix(files).rsplit('/', 1)[-2] | 20 zip_path = os.path.commonprefix(files).rsplit('/', 1)[-2] |
21 prefix = zip_path.rsplit('/', 1)[-2] | 21 prefix = zip_path.rsplit('/', 1)[-2] |
22 if zip_path + '/manifest.json' not in files: | 22 if zip_path + '/manifest.json' not in files: |
23 return None | 23 return None |
24 zip_bytes = BytesIO() | 24 zip_bytes = BytesIO() |
25 zip_file = ZipFile(zip_bytes, mode='w') | 25 zip_file = ZipFile(zip_bytes, mode='w') |
26 try: | 26 try: |
27 for filename, contents in self._file_system.Read(files).Get().iteritems(): | 27 for name, file_contents in ( |
28 zip_file.writestr(filename[len(prefix):].strip('/'), contents) | 28 self._file_system.Read(files, binary=True).Get().iteritems()): |
| 29 zip_file.writestr(name[len(prefix):].strip('/'), file_contents) |
29 finally: | 30 finally: |
30 zip_file.close() | 31 zip_file.close() |
31 return zip_bytes.getvalue() | 32 return zip_bytes.getvalue() |
32 | 33 |
33 def Create(self, path): | 34 def Create(self, path): |
34 """ Creates a new zip file from the recursive contents of |path| | 35 """ Creates a new zip file from the recursive contents of |path| |
35 as returned by |_zip_cache|. | 36 as returned by |_zip_cache|. |
36 Paths within the zip file are given relative to and including |path|. | 37 Paths within the zip file are given relative to and including |path|. |
37 """ | 38 """ |
38 return self._zip_cache.GetFromFileListing( | 39 return self._zip_cache.GetFromFileListing( |
39 self._base_path + '/' + path) | 40 self._base_path + '/' + path) |
OLD | NEW |