autotar_gendirs.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from __future__ import print_function
  2. import os
  3. import sys
  4. import argparse
  5. import tarfile
  6. import subprocess
  7. def is_exe(fpath):
  8. return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
  9. def pack_dir(dir_path, dest_path):
  10. dir_path = os.path.abspath(dir_path)
  11. for tar_exe in ('/usr/bin/tar', '/bin/tar'):
  12. if is_exe(tar_exe):
  13. subprocess.check_call([tar_exe, '-cf', dest_path, '-C', os.path.dirname(dir_path), os.path.basename(dir_path)])
  14. break
  15. else:
  16. with tarfile.open(dest_path, 'w') as out:
  17. out.add(dir_path, arcname=os.path.basename(dir_path))
  18. def unpack_dir(tared_dir, dest_path):
  19. tared_dir = os.path.abspath(tared_dir)
  20. if not os.path.exists(dest_path):
  21. os.makedirs(dest_path)
  22. for tar_exe in ('/usr/bin/tar', '/bin/tar'):
  23. if is_exe(tar_exe):
  24. subprocess.check_call([tar_exe, '-xf', tared_dir, '-C', dest_path])
  25. break
  26. else:
  27. with tarfile.open(tared_dir, 'r') as tar_file:
  28. tar_file.extractall(dest_path)
  29. # Must only be used to pack directories in build root
  30. # Must silently accept empty list of dirs and do nothing in such case (workaround for ymake.core.conf limitations)
  31. def main(args):
  32. parser = argparse.ArgumentParser()
  33. parser.add_argument('--pack', action='store_true', default=False)
  34. parser.add_argument('--unpack', action='store_true', default=False)
  35. parser.add_argument('--ext')
  36. parser.add_argument('--outs', nargs='*', default=[])
  37. parser.add_argument('dirs', nargs='*')
  38. args = parser.parse_args(args)
  39. if args.pack:
  40. if len(args.dirs) != len(args.outs):
  41. print("Number and oder of dirs to pack must match to the number and order of outs", file=sys.stderr)
  42. return 1
  43. for dir, dest in zip(args.dirs, args.outs):
  44. pack_dir(dir, dest)
  45. elif args.unpack:
  46. for tared_dir in args.dirs:
  47. if not tared_dir.endswith(args.ext):
  48. print("Requested to unpack '{}' which do not have required extension '{}'".format(tared_dir, args.ext), file=sys.stderr)
  49. return 1
  50. dest = os.path.dirname(tared_dir)
  51. unpack_dir(tared_dir, dest)
  52. else:
  53. print("Neither --pack nor --unpack specified. Don't know what to do.", file=sys.stderr)
  54. return 1
  55. return 0
  56. if __name__ == '__main__':
  57. sys.exit(main(sys.argv[1:]))