copy_files_to_dir.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import argparse
  2. import errno
  3. import os
  4. import process_command_files as pcf
  5. import shutil
  6. import sys
  7. def parse_args():
  8. parser = argparse.ArgumentParser()
  9. parser.add_argument('--dest-dir', required=True)
  10. parser.add_argument('--existing', choices=('skip', 'overwrite'), default='overwrite')
  11. parser.add_argument('--flat', action='store_true')
  12. parser.add_argument('--skip-prefix', dest='skip_prefixes', action='append', default=[])
  13. parser.add_argument('files', nargs='*')
  14. return parser.parse_args(pcf.get_args(sys.argv[1:]))
  15. def makedirs(dirname):
  16. try:
  17. os.makedirs(dirname)
  18. except OSError as e:
  19. if e.errno == errno.EEXIST and os.path.isdir(dirname):
  20. pass
  21. else:
  22. raise
  23. def main():
  24. args = parse_args()
  25. dest_dir = os.path.normpath(args.dest_dir) + os.pathsep
  26. makedirs(dest_dir)
  27. prefixes = ['{}{}'.format(os.path.normpath(p), os.path.sep) for p in args.skip_prefixes]
  28. for src in args.files:
  29. src = os.path.normpath(src)
  30. assert os.path.isfile(src)
  31. if args.flat:
  32. rel_dst = os.path.basename(src)
  33. else:
  34. rel_dst = src
  35. for prefix in prefixes:
  36. if src.startswith(prefix):
  37. rel_dst = src[len(prefix) :]
  38. break
  39. assert not os.path.isabs(rel_dst)
  40. dst = os.path.join(args.dest_dir, rel_dst)
  41. if os.path.isfile(dst) and args.existing == 'skip':
  42. break
  43. makedirs(os.path.dirname(dst))
  44. shutil.copyfile(src, dst)
  45. if __name__ == '__main__':
  46. main()