tar_directory.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import os
  2. import sys
  3. import tarfile
  4. def is_exe(fpath):
  5. return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
  6. def main(args):
  7. if len(args) < 2 or len(args) > 3:
  8. raise Exception("Illegal usage: `tar_directory.py archive.tar directory [skip prefix]` or `tar_directory.py archive.tar output_directory --extract`")
  9. tar, directory, prefix, extract = args[0], args[1], None, False
  10. if len(args) == 3:
  11. if args[2] == '--extract':
  12. extract = True
  13. else:
  14. prefix = args[2]
  15. for tar_exe in ('/usr/bin/tar', '/bin/tar'):
  16. if not is_exe(tar_exe):
  17. continue
  18. if extract:
  19. dest = os.path.abspath(directory)
  20. if not os.path.exists(dest):
  21. os.makedirs(dest)
  22. os.execv(tar_exe, [tar_exe, '-xf', tar, '-C', dest])
  23. else:
  24. source = os.path.relpath(directory, prefix) if prefix else directory
  25. os.execv(tar_exe, [tar_exe, '-cf', tar] + (['-C', prefix] if prefix else []) + [source])
  26. break
  27. else:
  28. if extract:
  29. dest = os.path.abspath(directory)
  30. if not os.path.exists(dest):
  31. os.makedirs(dest)
  32. with tarfile.open(tar, 'r') as tar_file:
  33. tar_file.extractall(dest)
  34. else:
  35. source = directory
  36. with tarfile.open(tar, 'w') as out:
  37. out.add(os.path.abspath(source), arcname=os.path.relpath(source, prefix) if prefix else source)
  38. if __name__ == '__main__':
  39. main(sys.argv[1:])