~charmers/charms/precise/solr-jetty/trunk

« back to all changes in this revision

Viewing changes to lib/charmhelpers/payload/archive.py

  • Committer: Matthew Wedgwood
  • Date: 2013-07-19 16:34:13 UTC
  • mfrom: (17.1.8 solr-jetty)
  • Revision ID: matthew.wedgwood@canonical.com-20130719163413-2vk3szo8xj7vwfr4
[thedac] Use current charm-helpers (revno 38) inline

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import os
 
2
import tarfile
 
3
import zipfile
 
4
from charmhelpers.core import (
 
5
    host,
 
6
    hookenv,
 
7
)
 
8
 
 
9
 
 
10
class ArchiveError(Exception):
 
11
    pass
 
12
 
 
13
 
 
14
def get_archive_handler(archive_name):
 
15
    if os.path.isfile(archive_name):
 
16
        if tarfile.is_tarfile(archive_name):
 
17
            return extract_tarfile
 
18
        elif zipfile.is_zipfile(archive_name):
 
19
            return extract_zipfile
 
20
    else:
 
21
        # look at the file name
 
22
        for ext in ('.tar.gz', '.tgz', 'tar.bz2', '.tbz2', '.tbz'):
 
23
            if archive_name.endswith(ext):
 
24
                return extract_tarfile
 
25
        for ext in ('.zip', '.jar'):
 
26
            if archive_name.endswith(ext):
 
27
                return extract_zipfile
 
28
 
 
29
 
 
30
def archive_dest_default(archive_name):
 
31
    return os.path.join(hookenv.charm_dir(), "archives", archive_name)
 
32
 
 
33
 
 
34
def extract(archive_name, destpath=None):
 
35
    handler = get_archive_handler(archive_name)
 
36
    if handler:
 
37
        if not destpath:
 
38
            destpath = archive_dest_default(archive_name)
 
39
        if not os.path.isdir(destpath):
 
40
            host.mkdir(destpath)
 
41
        get_archive_handler(archive_name)(archive_name, destpath)
 
42
        return destpath
 
43
    else:
 
44
        raise ArchiveError("No handler for archive")
 
45
 
 
46
 
 
47
def extract_tarfile(archive_name, destpath):
 
48
    "Unpack a tar archive, optionally compressed"
 
49
    archive = tarfile.open(archive_name)
 
50
    archive.extractall(destpath)
 
51
 
 
52
 
 
53
def extract_zipfile(archive_name, destpath):
 
54
    "Unpack a zip file"
 
55
    archive = zipfile.ZipFile(archive_name)
 
56
    archive.extractall(destpath)