_tools.py 972 B

12345678910111213141516171819202122232425262728293031323334
  1. from __future__ import annotations
  2. import typing
  3. from pathlib import PurePosixPath
  4. from ._errors import DirectoryNotEmpty
  5. if typing.TYPE_CHECKING:
  6. from typing import IO
  7. from ._base import FS
  8. def remove_empty(fs: FS, path: str):
  9. """Remove all empty parents."""
  10. path = PurePosixPath(path)
  11. root = PurePosixPath("/")
  12. try:
  13. while path != root:
  14. fs.removedir(path.as_posix())
  15. path = path.parent
  16. except DirectoryNotEmpty:
  17. pass
  18. def copy_file_data(src_file: IO, dst_file: IO, chunk_size: int | None = None):
  19. """Copy data from one file object to another."""
  20. _chunk_size = 1024 * 1024 if chunk_size is None else chunk_size
  21. read = src_file.read
  22. write = dst_file.write
  23. # in iter(callable, sentilel), callable is called until it returns the sentinel;
  24. # this allows to copy `chunk_size` bytes at a time.
  25. for chunk in iter(lambda: read(_chunk_size) or None, None):
  26. write(chunk)