copy_files_to_dir.py 1.7 KB

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