tar_sources.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import argparse
  2. import os
  3. import tarfile
  4. def parse_args():
  5. parser = argparse.ArgumentParser()
  6. parser.add_argument('--exts', nargs='*', default=None)
  7. parser.add_argument('--flat', action='store_true')
  8. parser.add_argument('--input', required=True)
  9. parser.add_argument('--output', required=True)
  10. parser.add_argument('--prefix', default=None)
  11. return parser.parse_args()
  12. def main():
  13. args = parse_args()
  14. srcs = []
  15. for root, _, files in os.walk(args.input):
  16. for f in files:
  17. if not args.exts or f.endswith(tuple(args.exts)):
  18. srcs.append(os.path.join(root, f))
  19. compression_mode = ''
  20. if args.output.endswith(('.tar.gz', '.tgz')):
  21. compression_mode = 'gz'
  22. elif args.output.endswith('.bzip2'):
  23. compression_mode = 'bz2'
  24. with tarfile.open(args.output, 'w:{}'.format(compression_mode)) as out:
  25. for f in srcs:
  26. arcname = os.path.basename(f) if args.flat else os.path.relpath(f, args.input)
  27. if args.prefix:
  28. arcname = os.path.join(args.prefix, arcname)
  29. out.add(f, arcname=arcname)
  30. if __name__ == '__main__':
  31. main()