Christopher Dunn | dc0f736 | 2011-06-21 21:18:49 +0000 | [diff] [blame] | 1 | import os.path |
| 2 | import gzip |
| 3 | import tarfile |
| 4 | |
| 5 | TARGZ_DEFAULT_COMPRESSION_LEVEL = 9 |
| 6 | |
| 7 | def make_tarball(tarball_path, sources, base_dir, prefix_dir=''): |
| 8 | """Parameters: |
| 9 | tarball_path: output path of the .tar.gz file |
| 10 | sources: list of sources to include in the tarball, relative to the current directory |
| 11 | base_dir: if a source file is in a sub-directory of base_dir, then base_dir is stripped |
| 12 | from path in the tarball. |
| 13 | prefix_dir: all files stored in the tarball be sub-directory of prefix_dir. Set to '' |
| 14 | to make them child of root. |
| 15 | """ |
| 16 | base_dir = os.path.normpath( os.path.abspath( base_dir ) ) |
| 17 | def archive_name( path ): |
| 18 | """Makes path relative to base_dir.""" |
| 19 | path = os.path.normpath( os.path.abspath( path ) ) |
| 20 | 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 | def visit(tar, dirname, names): |
| 26 | for name in names: |
| 27 | path = os.path.join(dirname, name) |
| 28 | if os.path.isfile(path): |
| 29 | path_in_tar = archive_name(path) |
| 30 | tar.add(path, path_in_tar ) |
| 31 | compression = TARGZ_DEFAULT_COMPRESSION_LEVEL |
| 32 | tar = tarfile.TarFile.gzopen( tarball_path, 'w', compresslevel=compression ) |
| 33 | try: |
| 34 | for source in sources: |
| 35 | source_path = source |
| 36 | if os.path.isdir( source ): |
| 37 | os.path.walk(source_path, visit, tar) |
| 38 | else: |
| 39 | path_in_tar = archive_name(source_path) |
| 40 | tar.add(source_path, path_in_tar ) # filename, arcname |
| 41 | finally: |
| 42 | tar.close() |
| 43 | |
| 44 | def decompress( tarball_path, base_dir ): |
| 45 | """Decompress the gzipped tarball into directory base_dir. |
| 46 | """ |
| 47 | # !!! This class method is not documented in the online doc |
| 48 | # nor is bz2open! |
| 49 | tar = tarfile.TarFile.gzopen(tarball_path, mode='r') |
| 50 | try: |
| 51 | tar.extractall( base_dir ) |
| 52 | finally: |
| 53 | tar.close() |