_copy.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from __future__ import annotations
  2. import typing
  3. from ._errors import IllegalDestination
  4. from ._path import combine, frombase, isbase
  5. from ._tools import copy_file_data
  6. if typing.TYPE_CHECKING:
  7. from ._base import FS
  8. def copy_file(src_fs: FS, src_path: str, dst_fs: FS, dst_path: str):
  9. if src_fs is dst_fs and src_path == dst_path:
  10. raise IllegalDestination(f"cannot copy {src_path!r} to itself")
  11. with src_fs.open(src_path, "rb") as src_file:
  12. with dst_fs.open(dst_path, "wb") as dst_file:
  13. copy_file_data(src_file, dst_file)
  14. def copy_structure(
  15. src_fs: FS,
  16. dst_fs: FS,
  17. src_root: str = "/",
  18. dst_root: str = "/",
  19. ):
  20. if src_fs is dst_fs and isbase(src_root, dst_root):
  21. raise IllegalDestination(f"cannot copy {src_fs!r} to itself")
  22. dst_fs.makedirs(dst_root, recreate=True)
  23. for dir_path in src_fs.walk.dirs(src_root):
  24. dst_fs.makedir(combine(dst_root, frombase(src_root, dir_path)), recreate=True)
  25. def copy_dir(src_fs: FS, src_path: str, dst_fs: FS, dst_path: str):
  26. copy_structure(src_fs, dst_fs, src_path, dst_path)
  27. for file_path in src_fs.walk.files(src_path):
  28. copy_path = combine(dst_path, frombase(src_path, file_path))
  29. copy_file(src_fs, file_path, dst_fs, copy_path)
  30. def copy_fs(src_fs: FS, dst_fs: FS):
  31. copy_dir(src_fs, "/", dst_fs, "/")