1
# Copyright (C) 2005, 2006, 2008, 2009, 2010 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Export a Tree to a zip file.
20
from __future__ import absolute_import
22
from contextlib import closing
33
from ..export import _export_iter_entries
34
from ..trace import mutter
37
# Windows expects this bit to be set in the 'external_attr' section,
38
# or it won't consider the entry a directory.
39
ZIP_DIRECTORY_BIT = (1 << 4)
40
FILE_PERMISSIONS = (0o644 << 16)
41
DIR_PERMISSIONS = (0o755 << 16)
43
_FILE_ATTR = stat.S_IFREG | FILE_PERMISSIONS
44
_DIR_ATTR = stat.S_IFDIR | ZIP_DIRECTORY_BIT | DIR_PERMISSIONS
47
def zip_archive_generator(tree, dest, root, subdir=None,
49
""" Export this tree to a new zip file.
51
`dest` will be created holding the contents of this tree; if it
52
already exists, it will be overwritten".
54
compression = zipfile.ZIP_DEFLATED
55
with tempfile.SpooledTemporaryFile() as buf:
56
with closing(zipfile.ZipFile(buf, "w", compression)) as zipf, \
58
for dp, tp, ie in _export_iter_entries(tree, subdir):
59
mutter(" export {%s} kind %s to %s", tp, ie.kind, dest)
61
# zipfile.ZipFile switches all paths to forward
62
# slashes anyway, so just stick with that.
63
if force_mtime is not None:
66
mtime = tree.get_file_mtime(tp)
67
date_time = time.localtime(mtime)[:6]
68
filename = osutils.pathjoin(root, dp)
70
zinfo = zipfile.ZipInfo(
73
zinfo.compress_type = compression
74
zinfo.external_attr = _FILE_ATTR
75
content = tree.get_file_text(tp)
76
zipf.writestr(zinfo, content)
77
elif ie.kind in ("directory", "tree-reference"):
78
# Directories must contain a trailing slash, to indicate
79
# to the zip routine that they are really directories and
80
# not just empty files.
81
zinfo = zipfile.ZipInfo(
82
filename=filename + '/',
84
zinfo.compress_type = compression
85
zinfo.external_attr = _DIR_ATTR
86
zipf.writestr(zinfo, '')
87
elif ie.kind == "symlink":
88
zinfo = zipfile.ZipInfo(
89
filename=(filename + '.lnk'),
91
zinfo.compress_type = compression
92
zinfo.external_attr = _FILE_ATTR
93
zipf.writestr(zinfo, tree.get_symlink_target(tp))
94
# Urgh, headers are written last since they include e.g. file size.
95
# So we have to buffer it all :(
97
for chunk in osutils.file_iterator(buf):