You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
2.2KB

  1. # Copyright 2010 Baptiste Lepilleur and The JsonCpp Authors
  2. # Distributed under MIT license, or public domain if desired and
  3. # recognized in your jurisdiction.
  4. # See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  5. from contextlib import closing
  6. import os
  7. import tarfile
  8. TARGZ_DEFAULT_COMPRESSION_LEVEL = 9
  9. def make_tarball(tarball_path, sources, base_dir, prefix_dir=''):
  10. """Parameters:
  11. tarball_path: output path of the .tar.gz file
  12. sources: list of sources to include in the tarball, relative to the current directory
  13. base_dir: if a source file is in a sub-directory of base_dir, then base_dir is stripped
  14. from path in the tarball.
  15. prefix_dir: all files stored in the tarball be sub-directory of prefix_dir. Set to ''
  16. to make them child of root.
  17. """
  18. base_dir = os.path.normpath(os.path.abspath(base_dir))
  19. def archive_name(path):
  20. """Makes path relative to base_dir."""
  21. path = os.path.normpath(os.path.abspath(path))
  22. common_path = os.path.commonprefix((base_dir, path))
  23. archive_name = path[len(common_path):]
  24. if os.path.isabs(archive_name):
  25. archive_name = archive_name[1:]
  26. return os.path.join(prefix_dir, archive_name)
  27. def visit(tar, dirname, names):
  28. for name in names:
  29. path = os.path.join(dirname, name)
  30. if os.path.isfile(path):
  31. path_in_tar = archive_name(path)
  32. tar.add(path, path_in_tar)
  33. compression = TARGZ_DEFAULT_COMPRESSION_LEVEL
  34. with closing(tarfile.TarFile.open(tarball_path, 'w:gz',
  35. compresslevel=compression)) as tar:
  36. for source in sources:
  37. source_path = source
  38. if os.path.isdir(source):
  39. for dirpath, dirnames, filenames in os.walk(source_path):
  40. visit(tar, dirpath, filenames)
  41. else:
  42. path_in_tar = archive_name(source_path)
  43. tar.add(source_path, path_in_tar) # filename, arcname
  44. def decompress(tarball_path, base_dir):
  45. """Decompress the gzipped tarball into directory base_dir.
  46. """
  47. with closing(tarfile.TarFile.open(tarball_path)) as tar:
  48. tar.extractall(base_dir)