1
# Copyright 2014-2015 Canonical Limited.
3
# This file is part of charm-helpers.
5
# charm-helpers is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU Lesser General Public License version 3 as
7
# published by the Free Software Foundation.
9
# charm-helpers is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU Lesser General Public License for more details.
14
# You should have received a copy of the GNU Lesser General Public License
15
# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
20
from charmhelpers.core import (
26
class ArchiveError(Exception):
30
def get_archive_handler(archive_name):
31
if os.path.isfile(archive_name):
32
if tarfile.is_tarfile(archive_name):
33
return extract_tarfile
34
elif zipfile.is_zipfile(archive_name):
35
return extract_zipfile
37
# look at the file name
38
for ext in ('.tar', '.tar.gz', '.tgz', 'tar.bz2', '.tbz2', '.tbz'):
39
if archive_name.endswith(ext):
40
return extract_tarfile
41
for ext in ('.zip', '.jar'):
42
if archive_name.endswith(ext):
43
return extract_zipfile
46
def archive_dest_default(archive_name):
47
archive_file = os.path.basename(archive_name)
48
return os.path.join(hookenv.charm_dir(), "archives", archive_file)
51
def extract(archive_name, destpath=None):
52
handler = get_archive_handler(archive_name)
55
destpath = archive_dest_default(archive_name)
56
if not os.path.isdir(destpath):
58
handler(archive_name, destpath)
61
raise ArchiveError("No handler for archive")
64
def extract_tarfile(archive_name, destpath):
65
"Unpack a tar archive, optionally compressed"
66
archive = tarfile.open(archive_name)
67
archive.extractall(destpath)
70
def extract_zipfile(archive_name, destpath):
72
archive = zipfile.ZipFile(archive_name)
73
archive.extractall(destpath)