blob: 2ce261a5fc6379ca9e1aab429944103021ace656 [file] [log] [blame]
Baptiste Lepilleure94d2f42010-02-23 21:00:30 +00001import os.path
2import gzip
3import tarfile
4
5TARGZ_DEFAULT_COMPRESSION_LEVEL = 9
6
7def 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 fileobj = gzip.GzipFile( tarball_path, 'wb', compression )
33 tar = tarfile.TarFile(os.path.splitext(tarball_path)[0], 'w', fileobj)
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 tar.close()