tar_sources.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import argparse
  2. import os
  3. import stat
  4. import tarfile
  5. def parse_args():
  6. parser = argparse.ArgumentParser()
  7. parser.add_argument('--exts', nargs='*', default=None)
  8. parser.add_argument('--flat', action='store_true')
  9. parser.add_argument('--input', required=True)
  10. parser.add_argument('--output', required=True)
  11. parser.add_argument('--prefix', default=None)
  12. return parser.parse_args()
  13. def main():
  14. args = parse_args()
  15. compression_mode = ''
  16. if args.output.endswith(('.tar.gz', '.tgz')):
  17. compression_mode = 'gz'
  18. elif args.output.endswith('.bzip2'):
  19. compression_mode = 'bz2'
  20. with tarfile.open(args.output, 'w:{}'.format(compression_mode)) as out:
  21. for root, dirs, files in os.walk(args.input, topdown=True):
  22. dirs.sort()
  23. for name in sorted(files):
  24. fname = os.path.join(root, name)
  25. if args.exts and not fname.endswith(tuple(args.exts)):
  26. continue
  27. arcname = os.path.basename(fname) if args.flat else os.path.relpath(fname, args.input)
  28. if args.prefix:
  29. arcname = os.path.join(args.prefix, arcname)
  30. with open(fname, 'rb') as fin:
  31. tarinfo = out.gettarinfo(fname, arcname)
  32. tarinfo.mode = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH if tarinfo.mode | stat.S_IXUSR else 0
  33. tarinfo.mode = (
  34. tarinfo.mode | stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH
  35. )
  36. tarinfo.mtime = 0
  37. tarinfo.uid = 0
  38. tarinfo.gid = 0
  39. tarinfo.uname = 'dummy'
  40. tarinfo.gname = 'dummy'
  41. out.addfile(tarinfo, fin)
  42. if __name__ == '__main__':
  43. main()