tar_directory.py 1.5 KB

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