tarball.py 1.95 KB
Newer Older
Christopher Dunn's avatar
Christopher Dunn committed
1
from contextlib import closing
2
import os
3
4
5
6
7
8
9
10
11
12
13
14
15
import tarfile

TARGZ_DEFAULT_COMPRESSION_LEVEL = 9

def make_tarball(tarball_path, sources, base_dir, prefix_dir=''):
    """Parameters:
    tarball_path: output path of the .tar.gz file
    sources: list of sources to include in the tarball, relative to the current directory
    base_dir: if a source file is in a sub-directory of base_dir, then base_dir is stripped
        from path in the tarball.
    prefix_dir: all files stored in the tarball be sub-directory of prefix_dir. Set to ''
        to make them child of root.
    """
16
17
    base_dir = os.path.normpath(os.path.abspath(base_dir))
    def archive_name(path):
18
        """Makes path relative to base_dir."""
19
20
        path = os.path.normpath(os.path.abspath(path))
        common_path = os.path.commonprefix((base_dir, path))
21
        archive_name = path[len(common_path):]
22
        if os.path.isabs(archive_name):
23
            archive_name = archive_name[1:]
24
        return os.path.join(prefix_dir, archive_name)
25
26
27
28
29
    def visit(tar, dirname, names):
        for name in names:
            path = os.path.join(dirname, name)
            if os.path.isfile(path):
                path_in_tar = archive_name(path)
30
                tar.add(path, path_in_tar)
31
    compression = TARGZ_DEFAULT_COMPRESSION_LEVEL
Christopher Dunn's avatar
Christopher Dunn committed
32
33
    with closing(tarfile.TarFile.open(tarball_path, 'w:gz',
            compresslevel=compression)) as tar:
34
35
        for source in sources:
            source_path = source
36
            if os.path.isdir(source):
37
38
                for dirpath, dirnames, filenames in os.walk(source_path):
                    visit(tar, dirpath, filenames)
39
40
            else:
                path_in_tar = archive_name(source_path)
41
                tar.add(source_path, path_in_tar)      # filename, arcname
42

43
def decompress(tarball_path, base_dir):
44
45
    """Decompress the gzipped tarball into directory base_dir.
    """
Christopher Dunn's avatar
Christopher Dunn committed
46
    with closing(tarfile.TarFile.open(tarball_path)) as tar:
47
        tar.extractall(base_dir)