~tvansteenburgh/charms/precise/nvp-transport-node/fix-proof

« back to all changes in this revision

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

  • Committer: Liam Young
  • Date: 2014-07-30 13:08:44 UTC
  • mfrom: (46.1.2 nvp-transport-node)
  • Revision ID: liam.young@canonical.com-20140730130844-ljfr29rwh62vsfid
[jamespage, r=gnuoy] Add support for using tarball from object storage

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', '.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
    archive_file = os.path.basename(archive_name)
 
32
    return os.path.join(hookenv.charm_dir(), "archives", archive_file)
 
33
 
 
34
 
 
35
def extract(archive_name, destpath=None):
 
36
    handler = get_archive_handler(archive_name)
 
37
    if handler:
 
38
        if not destpath:
 
39
            destpath = archive_dest_default(archive_name)
 
40
        if not os.path.isdir(destpath):
 
41
            host.mkdir(destpath)
 
42
        handler(archive_name, destpath)
 
43
        return destpath
 
44
    else:
 
45
        raise ArchiveError("No handler for archive")
 
46
 
 
47
 
 
48
def extract_tarfile(archive_name, destpath):
 
49
    "Unpack a tar archive, optionally compressed"
 
50
    archive = tarfile.open(archive_name)
 
51
    archive.extractall(destpath)
 
52
 
 
53
 
 
54
def extract_zipfile(archive_name, destpath):
 
55
    "Unpack a zip file"
 
56
    archive = zipfile.ZipFile(archive_name)
 
57
    archive.extractall(destpath)