smb.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from __future__ import annotations
  2. import os
  3. import sys
  4. import warnings
  5. from typing import TYPE_CHECKING
  6. from typing import Any
  7. if TYPE_CHECKING:
  8. if sys.version_info >= (3, 11):
  9. from typing import Self
  10. else:
  11. from typing_extensions import Self
  12. import smbprotocol.exceptions
  13. from upath import UPath
  14. _unset: Any = object()
  15. class SMBPath(UPath):
  16. __slots__ = ()
  17. def mkdir(self, mode=0o777, parents=False, exist_ok=False):
  18. # smbclient does not support setting mode externally
  19. if parents and not exist_ok and self.exists():
  20. raise FileExistsError(str(self))
  21. try:
  22. self.fs.mkdir(
  23. self.path,
  24. create_parents=parents,
  25. )
  26. except smbprotocol.exceptions.SMBOSError:
  27. if not exist_ok:
  28. raise FileExistsError(str(self))
  29. if not self.is_dir():
  30. raise FileExistsError(str(self))
  31. def iterdir(self):
  32. if not self.is_dir():
  33. raise NotADirectoryError(str(self))
  34. else:
  35. return super().iterdir()
  36. def rename(
  37. self,
  38. target: str | os.PathLike[str] | UPath,
  39. *,
  40. recursive: bool = _unset,
  41. maxdepth: int | None = _unset,
  42. **kwargs: Any,
  43. ) -> Self:
  44. if recursive is not _unset:
  45. warnings.warn(
  46. "SMBPath.rename(): recursive is currently ignored.",
  47. UserWarning,
  48. stacklevel=2,
  49. )
  50. if maxdepth is not _unset:
  51. warnings.warn(
  52. "SMBPath.rename(): maxdepth is currently ignored.",
  53. UserWarning,
  54. stacklevel=2,
  55. )
  56. return super().rename(target, **kwargs)