~lazypower/charms/precise/python-moinmoin/fix_proof

« back to all changes in this revision

Viewing changes to lib/charm-helpers/charmhelpers/payload/archive.py

  • Committer: Marco Ceppi
  • Date: 2013-10-20 17:35:29 UTC
  • mfrom: (7.1.1 python-moinmoin)
  • Revision ID: marco@ceppi.net-20131020173529-w9qmyq0pjj1bc71f
Brad Marshall 2013-09-26 [merge] Rewritten in python using charm-helpers

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)