File: tarball.py

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (53 lines) | stat: -rw-r--r-- 2,071 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import os.path
import gzip
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.
    """
    base_dir = os.path.normpath( os.path.abspath( base_dir ) )
    def archive_name( path ):
        """Makes path relative to base_dir."""
        path = os.path.normpath( os.path.abspath( path ) )
        common_path = os.path.commonprefix( (base_dir, path) )
        archive_name = path[len(common_path):]
        if os.path.isabs( archive_name ):
            archive_name = archive_name[1:]
        return os.path.join( prefix_dir, archive_name )
    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)
                tar.add(path, path_in_tar )
    compression = TARGZ_DEFAULT_COMPRESSION_LEVEL
    tar = tarfile.TarFile.gzopen( tarball_path, 'w', compresslevel=compression )
    try:
        for source in sources:
            source_path = source
            if os.path.isdir( source ):
                os.path.walk(source_path, visit, tar)
            else:
                path_in_tar = archive_name(source_path)
                tar.add(source_path, path_in_tar )      # filename, arcname
    finally:
        tar.close()

def decompress( tarball_path, base_dir ):
    """Decompress the gzipped tarball into directory base_dir.
    """
    # !!! This class method is not documented in the online doc
    # nor is bz2open!
    tar = tarfile.TarFile.gzopen(tarball_path, mode='r')
    try:
        tar.extractall( base_dir )
    finally:
        tar.close()