~james-page/charm-helpers/follow-symlinks

« back to all changes in this revision

Viewing changes to charmhelpers/fileutils/__init__.py

  • Committer: Matthew Wedgwood
  • Date: 2013-05-31 08:21:23 UTC
  • mto: This revision was merged to the branch mainline in revision 37.
  • Revision ID: matthew.wedgwood@canonical.com-20130531082123-32eeknxrf8075uj9
Framework for fetching file trees from arbitrary URLs

Show diffs side-by-side

added added

removed removed

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