autotar_gendirs.py 2.5 KB

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