1# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2# SPDX-License-Identifier: Apache-2.0
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import logging
17import os
18import posixpath
19import stat
20from fnmatch import fnmatchcase
21from glob import escape
22from pathlib import Path, PurePath, PurePosixPath
23from types import NotImplementedType
24
25from .client import StorageClient
26from .shortcuts import _reopen_reference_path, resolve_storage_client
27from .types import ObjectMetadata
28from .utils import _decode_buffer, _ensure_bytes
29
30logger = logging.getLogger(__name__)
31
32
[docs]
33class StatResult:
34 """
35 A stat-like result object that mimics os.stat_result for remote storage paths.
36
37 This class provides the same interface as os.stat_result but is populated
38 from ObjectMetadata obtained from storage providers.
39 """
40
41 def __init__(self, metadata: ObjectMetadata):
42 """Initialize StatResult from ObjectMetadata."""
43 # File type and mode bits
44 if metadata.type == "directory":
45 # Directory: 0o755 (rwxr-xr-x) + S_IFDIR
46 self.st_mode = stat.S_IFDIR | 0o755
47 else:
48 # Regular file: 0o644 (rw-r--r--) + S_IFREG
49 self.st_mode = stat.S_IFREG | 0o644
50
51 # File size
52 self.st_size = metadata.content_length
53
54 # Timestamps - convert datetime to epoch seconds
55 mtime = metadata.last_modified.timestamp()
56 self.st_mtime = mtime
57 self.st_atime = mtime
58 self.st_ctime = mtime
59
60 # Nanosecond precision timestamps
61 mtime_ns = int(mtime * 1_000_000_000)
62 self.st_mtime_ns = mtime_ns
63 self.st_atime_ns = mtime_ns
64 self.st_ctime_ns = mtime_ns
65
66 # Default values for fields we don't have from storage providers
67 self.st_ino = 0
68 self.st_dev = 0
69 self.st_nlink = 1
70 self.st_uid = os.getuid() if hasattr(os, "getuid") else 0 # User ID
71 self.st_gid = os.getgid() if hasattr(os, "getgid") else 0 # Group ID
72
73
[docs]
74class MultiStoragePath:
75 """
76 A path object similar to pathlib.Path that supports both local and remote file systems.
77
78 MultiStoragePath provides a unified interface for working with paths across different storage systems,
79 including local files, S3, GCS, Azure Blob Storage, and configured reference URIs.
80
81 This implementation is based on Python 3.9's pathlib.Path interface, providing compatible behavior
82 for local filesystem operations while extending support to remote storage systems.
83
84 Examples:
85 >>> import multistorageclient as msc
86 >>> msc.Path("/local/path/file.txt")
87 >>> msc.Path("msc://my-profile/data/file.txt")
88 >>> msc.Path(pathlib.Path("relative/path"))
89 """
90
91 _internal_path: PurePosixPath
92 _storage_client: StorageClient
93 _path: str
94 _key: str
95 _profile: str
96 _is_reference: bool
97
98 def __init__(self, path: str | os.PathLike):
99 """
100 Initialize path object supporting multiple storage backends.
101
102 :param path: String, Path, or MultiStoragePath. Relative paths are automatically converted to absolute.
103 """
104 if isinstance(path, MultiStoragePath) and path._is_reference:
105 self._set_reference(path._storage_client, path._key, path._profile)
106 return
107
108 self._path = str(path)
109 client, key = resolve_storage_client(self._path)
110 if client._config.canonical_root_url is not None:
111 self._set_reference(client, key, client.profile)
112 return
113
114 self._storage_client = client
115 self._profile = client.profile
116 self._is_reference = False
117 self._internal_path = PurePosixPath(key)
118 if client.is_default_profile():
119 self._internal_path = PurePosixPath("/") / self._internal_path
120 self._key = str(self._internal_path)
121
122 def _set_reference(self, client: StorageClient, key: str, profile: str) -> None:
123 self._storage_client = client
124 self._profile = profile
125 self._is_reference = True
126 self._key = key
127 self._internal_path = PurePosixPath(key)
128
129 def _with_key(self, key: str) -> "MultiStoragePath":
130 if self._is_reference:
131 child = type(self).__new__(type(self))
132 child._set_reference(self._storage_client, key, self._profile)
133 return child
134 if self._storage_client.is_default_profile():
135 return MultiStoragePath(key)
136 return MultiStoragePath(self._storage_client.url(key))
137
138 def __str__(self) -> str:
139 if self._storage_client.is_default_profile():
140 return self._key
141 return self._storage_client.url(self._key)
142
143 def __repr__(self) -> str:
144 return f"MultiStoragePath({str(self)!r})"
145
146 def __eq__(self, other) -> bool:
147 if not isinstance(other, MultiStoragePath):
148 return False
149 return self._ordering_key() == other._ordering_key()
150
151 def __lt__(self, other):
152 """
153 Return True if this path sorts before another path-like object.
154
155 Ordering is based on the normalized storage profile and internal path. ``pathlib`` paths are
156 compared as local filesystem paths; unsupported types return ``NotImplemented``.
157 """
158 other = self._coerce_path(other)
159 if other is NotImplemented:
160 return NotImplemented
161 return self._ordering_key() < other._ordering_key()
162
163 def __le__(self, other):
164 """Return whether this path sorts before or at another path-like object."""
165 other = self._coerce_path(other)
166 if other is NotImplemented:
167 return NotImplemented
168 return self._ordering_key() <= other._ordering_key()
169
170 def __gt__(self, other):
171 """Return whether this path sorts after another path-like object."""
172 other = self._coerce_path(other)
173 if other is NotImplemented:
174 return NotImplemented
175 return self._ordering_key() > other._ordering_key()
176
177 def __ge__(self, other):
178 """Return whether this path sorts after or at another path-like object."""
179 other = self._coerce_path(other)
180 if other is NotImplemented:
181 return NotImplemented
182 return self._ordering_key() >= other._ordering_key()
183
184 @staticmethod
185 def _coerce_path(other) -> "MultiStoragePath | NotImplementedType":
186 """
187 Convert supported path-like objects to ``MultiStoragePath`` for comparison.
188 """
189 if isinstance(other, MultiStoragePath):
190 return other
191 if isinstance(other, PurePath):
192 return MultiStoragePath(other)
193 return NotImplemented
194
195 def _ordering_key(self) -> tuple[str, bool, tuple[str, ...]]:
196 """
197 Return the resolved profile and internal path used for equality-compatible ordering.
198 """
199 return (self._profile, self._is_reference, self.parts)
200
201 def __hash__(self) -> int:
202 """Return hash of the path."""
203 return hash(self._ordering_key())
204
205 def __fspath__(self) -> str:
206 return str(self)
207
[docs]
208 def joinpath(self, *pathsegments):
209 return self.with_segments(*pathsegments)
210
211 def __truediv__(self, key):
212 try:
213 return self.joinpath(key)
214 except TypeError:
215 return NotImplemented
216
217 def __rtruediv__(self, key):
218 if self._is_reference:
219 return self if isinstance(key, (str, os.PathLike)) else NotImplemented
220 try:
221 return self.with_segments(key, self)
222 except TypeError:
223 return NotImplemented
224
225 def __getstate__(self):
226 if self._is_reference:
227 return {"reference_url": str(self), "root_url": self._storage_client.url()}
228 return {"_path": self._path, "_internal_path": self._internal_path}
229
230 def __setstate__(self, state):
231 if "reference_url" in state:
232 client, key = _reopen_reference_path(state["reference_url"], state["root_url"])
233 self._set_reference(client, key, client.profile)
234 return
235 self._is_reference = False
236 self._path = state["_path"]
237 self._internal_path = state["_internal_path"]
238 self._key = str(self._internal_path)
239 self._storage_client, _ = resolve_storage_client(self._path)
240 self._profile = self._storage_client.profile
241
242 @property
243 def anchor(self) -> str:
244 """
245 The concatenation of the drive and root, or ''.
246 """
247 return self._internal_path.anchor
248
249 @property
250 def name(self) -> str:
251 """
252 The final path component, if any.
253 """
254 if self._is_reference:
255 return self._key.rstrip("/").rpartition("/")[2]
256 return self._internal_path.name
257
258 @property
259 def suffix(self) -> str:
260 """
261 The final path component, if any.
262 """
263 if self._is_reference:
264 return PurePosixPath(self.name).suffix
265 return self._internal_path.suffix
266
267 @property
268 def suffixes(self) -> list[str]:
269 """
270 A list of the final component's suffixes, if any.
271
272 These include the leading periods. For example: ['.tar', '.gz']
273 """
274 if self._is_reference:
275 return PurePosixPath(self.name).suffixes
276 return self._internal_path.suffixes
277
278 @property
279 def stem(self) -> str:
280 """
281 The final path component, minus its last suffix.
282 """
283 if self._is_reference:
284 return self.name.removesuffix(self.suffix)
285 return self._internal_path.stem
286
287 @property
288 def parent(self) -> "MultiStoragePath":
289 """
290 The logical parent of the path.
291 """
292 if self._is_reference:
293 prefix, separator, _ = self._key.rstrip("/").rpartition("/")
294 if not prefix or prefix.endswith("/"):
295 prefix += separator
296 return self._with_key(prefix)
297 return self._with_key(str(self._internal_path.parent))
298
299 @property
300 def parents(self) -> list["MultiStoragePath"]:
301 """
302 A sequence of this path's logical parents.
303 """
304 if self._is_reference:
305 result = []
306 path = self
307 while path._key:
308 path = path.parent
309 result.append(path)
310 return result
311 return [self._with_key(str(p)) for p in self._internal_path.parents]
312
313 @property
314 def parts(self) -> tuple[str, ...]:
315 """
316 An object providing sequence-like access to the components in the filesystem path (does not
317 include the msc:// and the profile name).
318 """
319 if self._is_reference:
320 return tuple(self._key.split("/")) if self._key else ()
321 return self._internal_path.parts
322
[docs]
323 def as_posix(self) -> str:
324 """
325 Return the string representation of the path with forward (/) slashes.
326
327 If the path is a remote path, the file content is downloaded to local storage
328 (either cached or temporary file) and the local filesystem path is returned.
329 This enables access to remote file content through standard filesystem operations.
330 """
331 if self._storage_client.is_default_profile():
332 return self._internal_path.as_posix()
333
334 # Return the local path of the file
335 with self._storage_client.open(self._key, mode="rb") as fp:
336 return fp.resolve_filesystem_path()
337
[docs]
338 def is_absolute(self) -> bool:
339 """
340 Paths are always absolute.
341 """
342 return True
343
[docs]
344 def is_relative_to(self, other: "MultiStoragePath") -> bool:
345 """
346 Return True if the path is relative to another path in the same storage profile, or False otherwise.
347 """
348 if not isinstance(other, MultiStoragePath) or self._profile != other._profile:
349 return False
350 if self._is_reference != other._is_reference:
351 return False
352 if self._is_reference:
353 return self._key == other._key or self._key.startswith(other._directory_prefix())
354 return self._internal_path.is_relative_to(other._internal_path)
355
356 def _directory_prefix(self) -> str:
357 return self._key + "/" if self._key and not self._key.endswith("/") else self._key
358
[docs]
359 def is_reserved(self) -> bool:
360 if self._storage_client.is_default_profile():
361 return self._internal_path.is_reserved()
362 raise NotImplementedError("MultiStoragePath.is_reserved() is unsupported for remote storage paths")
363
[docs]
364 def match(self, pattern) -> bool:
365 """
366 Return True if this path matches the given pattern.
367 """
368 if self._is_reference:
369 pattern = os.fspath(pattern)
370 if not pattern:
371 raise ValueError("Empty pattern")
372 components = pattern.split("/")
373 parts = self.parts
374 if len(components) > len(parts) or (pattern.startswith("/") and len(components) != len(parts)):
375 return False
376 return all(fnmatchcase(part, rule) for part, rule in zip(reversed(parts), reversed(components)))
377 return Path(self._internal_path).match(pattern)
378
[docs]
379 def relative_to(self, other: "MultiStoragePath") -> PurePosixPath:
380 """
381 Return a version of this path relative to another path.
382
383 Both paths must use the same storage profile. The operation raises ValueError if:
384 - The paths have different storage profiles
385 - This path is not relative to the other path
386 - The other path is not a MultiStoragePath instance
387
388 Note: This method returns a PurePosixPath (not a MultiStoragePath) because
389 MultiStoragePath always represents absolute paths. The returned PurePosixPath applies
390 its normal component and separator normalization.
391
392 :param other: The base path to calculate relative path from
393 :return: A PurePosixPath representing the relative path
394 :raises ValueError: If the path cannot be made relative to other
395 :raises TypeError: If other is not a MultiStoragePath instance
396 """
397 if not isinstance(other, MultiStoragePath):
398 raise TypeError(f"'{type(other).__name__}' object cannot be used as relative base")
399
400 # Check if both paths use the same storage profile
401 if self._profile != other._profile:
402 raise ValueError(
403 f"Cannot compute relative path between different storage profiles: "
404 f"'{self._profile}' and '{other._profile}'"
405 )
406
407 if self._is_reference or other._is_reference:
408 if not self.is_relative_to(other):
409 raise ValueError(f"{str(self)!r} is not in the subpath of {str(other)!r}")
410 return PurePosixPath(self._key[len(other._directory_prefix()) :])
411
412 # Use the internal PurePosixPath.relative_to() method
413 try:
414 return self._internal_path.relative_to(other._internal_path)
415 except ValueError:
416 # Re-raise with paths that include the profile information for clarity
417 raise ValueError(f"{str(self)!r} is not in the subpath of {str(other)!r}")
418
[docs]
419 def with_name(self, name: str) -> "MultiStoragePath":
420 """
421 Return a new path with the file name changed.
422 """
423 if self._is_reference:
424 if not self.name or not name or "/" in name:
425 raise ValueError(f"Invalid name {name!r} for {self!r}")
426 path = self._key.rstrip("/")
427 prefix, separator, _ = path.rpartition("/")
428 return self._with_key(prefix + separator + name + self._key[len(path) :])
429 return self._with_key(str(self._internal_path.with_name(name)))
430
[docs]
431 def with_stem(self, stem: str) -> "MultiStoragePath":
432 """
433 Return a new path with the stem changed.
434 """
435 if self._is_reference:
436 return self.with_name(stem + self.suffix)
437 return self._with_key(str(self._internal_path.with_stem(stem)))
438
[docs]
439 def with_suffix(self, suffix: str) -> "MultiStoragePath":
440 """
441 Return a new path with the file suffix changed. If the path has no suffix, add given suffix.
442 If the given suffix is an empty string, remove the suffix from the path.
443 """
444 if self._is_reference:
445 PurePosixPath("name").with_suffix(suffix)
446 return self.with_name(self.stem + suffix)
447 return self._with_key(str(self._internal_path.with_suffix(suffix)))
448
[docs]
449 def with_segments(self, *pathsegments) -> "MultiStoragePath":
450 """
451 Construct a new path object from any number of path-like objects.
452 """
453 base = self
454 start = 0
455 for index, segment in enumerate(pathsegments, 1):
456 if isinstance(segment, MultiStoragePath) and segment._is_reference:
457 base = segment
458 start = index
459 if base._is_reference:
460 return base._with_key(posixpath.join(base._key, *pathsegments[start:]))
461 return self._with_key(str(self._internal_path.joinpath(*pathsegments)))
462
463 # Expanding and resolving paths
464
[docs]
465 @classmethod
466 def home(cls):
467 """
468 Return a new path pointing to the user's home directory.
469 """
470 return Path.home()
471
[docs]
472 def expanduser(self):
473 """
474 Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser).
475
476 Not supported for remote storage paths.
477 """
478 if self._storage_client.is_default_profile():
479 return Path(self._internal_path).expanduser()
480 raise NotImplementedError("MultiStoragePath.expanduser() is unsupported for remote storage paths")
481
[docs]
482 @classmethod
483 def cwd(cls):
484 """
485 Return a new path pointing to the current working directory.
486 """
487 return Path.cwd()
488
[docs]
489 def absolute(self):
490 """
491 Return the path itself since it is always absolute.
492 """
493 return self
494
[docs]
495 def resolve(self, strict=False):
496 """
497 Return the absolute path.
498 """
499 if self._storage_client.is_default_profile():
500 return MultiStoragePath(str(Path(self._internal_path).resolve(strict=strict)))
501 return self._with_key(self._key)
502
[docs]
503 def readlink(self):
504 """
505 Return the path to which the symbolic link points.
506
507 Not supported for remote storage paths.
508 """
509 if self._storage_client.is_default_profile():
510 return MultiStoragePath(str(Path(self._internal_path).readlink()))
511 raise NotImplementedError("MultiStoragePath.readlink() is unsupported for remote storage paths")
512
513 # Querying file type and status
514
[docs]
515 def stat(self):
516 """
517 Return the result of the stat() system call on this path, like os.stat() does.
518
519 If the path is a remote path, the result is a :py:class:`multistorageclient.pathlib.StatResult` object.
520 """
521 if self._storage_client.is_default_profile():
522 return Path(self._internal_path).stat()
523 info = self._storage_client.info(self._key)
524 return StatResult(info)
525
[docs]
526 def lstat(self):
527 """
528 Like stat(), except if the path points to a symlink, the symlink's status information
529 is returned, rather than its target's.
530
531 If the path is a remote path, the result is a :py:class:`multistorageclient.pathlib.StatResult` object.
532 """
533 if self._storage_client.is_default_profile():
534 return Path(self._internal_path).lstat()
535 info = self._storage_client.info(self._key)
536 return StatResult(info)
537
[docs]
538 def exists(self) -> bool:
539 """
540 Return True if the path exists.
541 """
542 if self._storage_client.is_default_profile():
543 return Path(self._internal_path).exists()
544 else:
545 try:
546 self._storage_client.info(self._key)
547 return True
548 except FileNotFoundError:
549 return False
550
[docs]
551 def is_file(self, strict: bool = True) -> bool:
552 """
553 Return True if the path exists and is a regular file.
554 """
555 if self._storage_client.is_default_profile():
556 return Path(self._internal_path).is_file()
557 if not self._is_reference and self._key.endswith("/"):
558 return False
559 return self._matches_type(self._key, "file", strict)
560
[docs]
561 def is_dir(self, strict: bool = True) -> bool:
562 """
563 Return True if the path exists and is a directory.
564 """
565 if self._storage_client.is_default_profile():
566 return Path(self._internal_path).is_dir()
567 path = self._key if self._is_reference else self._directory_prefix()
568 return self._matches_type(path, "directory", strict)
569
570 def _matches_type(self, path: str, object_type: str, strict: bool) -> bool:
571 try:
572 return self._storage_client.info(path, strict=strict).type == object_type
573 except FileNotFoundError:
574 return False
575 except Exception as e:
576 if self._is_reference:
577 raise
578 logger.warning("Error occurred while fetching file info at %s, caused by: %s", path, e)
579 return False
580
[docs]
581 def is_symlink(self):
582 """
583 Return True if the path exists and is a symbolic link.
584
585 Not supported for remote storage paths.
586 """
587 if self._storage_client.is_default_profile():
588 return Path(self._internal_path).is_symlink()
589 raise NotImplementedError("MultiStoragePath.is_symlink() is unsupported for remote storage paths")
590
[docs]
591 def is_mount(self):
592 """
593 Return True if the path exists and is a mount point.
594
595 Not supported for remote storage paths.
596 """
597 if self._storage_client.is_default_profile():
598 return Path(self._internal_path).is_mount()
599 raise NotImplementedError("MultiStoragePath.is_mount() is unsupported for remote storage paths")
600
[docs]
601 def is_socket(self):
602 """
603 Return True if the path exists and is a socket.
604
605 Not supported for remote storage paths.
606 """
607 if self._storage_client.is_default_profile():
608 return Path(self._internal_path).is_socket()
609 raise NotImplementedError("MultiStoragePath.is_socket() is unsupported for remote storage paths")
610
[docs]
611 def is_fifo(self):
612 """
613 Return True if the path exists and is a FIFO.
614
615 Not supported for remote storage paths.
616 """
617 if self._storage_client.is_default_profile():
618 return Path(self._internal_path).is_fifo()
619 raise NotImplementedError("MultiStoragePath.is_fifo() is unsupported for remote storage paths")
620
[docs]
621 def is_block_device(self):
622 """
623 Return True if the path exists and is a block device.
624
625 Not supported for remote storage paths.
626 """
627 if self._storage_client.is_default_profile():
628 return Path(self._internal_path).is_block_device()
629 raise NotImplementedError("MultiStoragePath.is_block_device() is unsupported for remote storage paths")
630
[docs]
631 def is_char_device(self):
632 """
633 Return True if the path exists and is a character device.
634
635 Not supported for remote storage paths.
636 """
637 if self._storage_client.is_default_profile():
638 return Path(self._internal_path).is_char_device()
639 raise NotImplementedError("MultiStoragePath.is_char_device() is unsupported for remote storage paths")
640
[docs]
641 def samefile(self, other_path):
642 """
643 Return True if both paths point to the same file or directory.
644
645 Not supported for remote storage paths.
646 """
647 if self._storage_client.is_default_profile():
648 return Path(self._internal_path).samefile(other_path)
649 return self == other_path
650
651 # Reading and writing files
652
[docs]
653 def open(self, mode="r", buffering=-1, encoding=None, errors=None, newline=None, **kwargs):
654 """
655 Open the file and return a file object.
656
657 :param mode: The file mode to open the file in.
658 :param buffering: The buffering mode.
659 :param encoding: The encoding to use for text files.
660 :param errors: How to handle encoding errors.
661 :param newline: Controls universal newlines mode.
662 :param kwargs: Additional arguments passed to client.open (e.g., check_source_version, prefetch_file, etc.)
663 """
664 return self._storage_client.open(self._key, mode=mode, buffering=buffering, encoding=encoding, **kwargs)
665
[docs]
666 def read_bytes(self) -> bytes:
667 """
668 Open the file in bytes mode, read it, and close the file.
669 """
670 return _ensure_bytes(self._storage_client.read(self._key))
671
[docs]
672 def read_text(self, encoding: str = "utf-8", errors: str = "strict") -> str:
673 """
674 Open the file in text mode, read it, and close the file.
675 """
676 result = self._storage_client.read(self._key)
677 return _decode_buffer(result, encoding, errors)
678
[docs]
679 def write_bytes(self, data: bytes) -> None:
680 """
681 Open the file in bytes mode, write to it, and close the file.
682 """
683 self._storage_client.write(self._key, data)
684
[docs]
685 def write_text(self, data: str, encoding: str = "utf-8", errors: str = "strict") -> None:
686 """
687 Open the file in text mode, write to it, and close the file.
688 """
689 self._storage_client.write(self._key, data.encode(encoding, errors))
690
691 # Reading directories
692
[docs]
693 def iterdir(self):
694 """
695 Yield path objects of the directory contents.
696 """
697 if self._storage_client.is_default_profile():
698 for item in Path(self._internal_path).iterdir():
699 yield MultiStoragePath(str(item))
700 else:
701 for item in self._storage_client.list(self._directory_prefix(), include_directories=True):
702 yield self._with_key(item.key)
703
[docs]
704 def glob(self, pattern):
705 """
706 Iterate over this subtree and yield all existing files (of any kind, including directories)
707 matching the given relative pattern.
708 """
709 if self._storage_client.is_default_profile():
710 return [MultiStoragePath(str(p)) for p in Path(self._internal_path).glob(pattern)]
711 if self._is_reference:
712 key_pattern = posixpath.join(escape(self._key), pattern)
713 else:
714 key_pattern = str(self._internal_path / pattern)
715 return [self._with_key(key) for key in self._storage_client.glob(key_pattern)]
716
[docs]
717 def rglob(self, pattern):
718 """
719 Recursively yield all existing files (of any kind, including directories) matching the
720 given relative pattern, anywhere in this subtree.
721 """
722 if self._storage_client.is_default_profile():
723 return [MultiStoragePath(str(p)) for p in Path(self._internal_path).rglob(pattern)]
724 return self.glob(f"**/{pattern}")
725
[docs]
726 def walk(self, top_down=True, on_error=None, follow_symlinks=False):
727 """
728 Walk the directory tree from this directory, similar to os.walk().
729
730 Not supported for remote storage paths.
731 """
732 if self._storage_client.is_default_profile():
733 return Path(self._internal_path).walk(top_down, on_error, follow_symlinks) # pyright: ignore[reportAttributeAccessIssue]
734 raise NotImplementedError("MultiStoragePath.walk() is unsupported for remote storage paths")
735
736 # Creating files and directories
737
[docs]
738 def touch(self, mode=0o666, exist_ok=False):
739 """
740 Create this file with the given access mode, if it doesn't exist.
741 """
742 self._storage_client._ensure_writable()
743 if self._storage_client.is_default_profile():
744 Path(self._internal_path).touch(mode, exist_ok)
745 else:
746 if self.exists():
747 # object storage does not support updating the last modified time of an object without writing the object
748 logger.warning("MultiStoragePath.touch() is not supported for remote storage paths")
749 else:
750 self._storage_client.write(self._key, b"")
751
[docs]
752 def mkdir(self, mode=0o777, parents=False, exist_ok=False) -> None:
753 """
754 Create a new directory at the given path.
755
756 For remote storage paths, this operation is a no-op.
757 """
758 self._storage_client._ensure_writable()
759 if self._storage_client.is_default_profile():
760 Path(self._internal_path).mkdir(mode, parents, exist_ok)
761
[docs]
762 def symlink_to(self, target, target_is_directory=False):
763 """
764 Make this path a symlink pointing to the target path.
765
766 Not supported for remote storage paths.
767 """
768 self._storage_client._ensure_writable()
769 if self._storage_client.is_default_profile():
770 Path(self._internal_path).symlink_to(target, target_is_directory)
771 else:
772 raise NotImplementedError("MultiStoragePath.symlink_to() is unsupported for remote storage paths")
773
774 # Renaming and deleting
775
[docs]
776 def rename(self, target) -> "MultiStoragePath":
777 """
778 Rename this path to the target path.
779 """
780 self._storage_client._ensure_writable()
781 if not isinstance(target, MultiStoragePath):
782 target = MultiStoragePath(target)
783
784 target._storage_client._ensure_writable()
785 if self._storage_client.is_default_profile():
786 Path(self._internal_path).rename(str(target._internal_path))
787 else:
788 # Note: This operation is not atomic, and the target path must be a single file.
789 self._storage_client.copy(self._key, str(target._internal_path))
790 self._storage_client.delete(self._key)
791
792 return target
793
[docs]
794 def replace(self, target):
795 """
796 Rename this path to the target path, overwriting if that path exists.
797
798 Not supported for remote storage paths.
799 """
800 self._storage_client._ensure_writable()
801 if isinstance(target, MultiStoragePath):
802 target._storage_client._ensure_writable()
803 if self._storage_client.is_default_profile():
804 Path(self._internal_path).replace(target)
805 else:
806 raise NotImplementedError("MultiStoragePath.replace() is unsupported for remote storage paths")
807
[docs]
808 def unlink(self, missing_ok: bool = False) -> None:
809 """
810 Remove this file or link. If the path is a directory, use rmdir() instead.
811 """
812 self._storage_client._ensure_writable()
813 if self._storage_client.is_default_profile():
814 Path(self._internal_path).unlink(missing_ok=missing_ok)
815 else:
816 try:
817 self._storage_client.delete(self._key)
818 except FileNotFoundError:
819 if not missing_ok:
820 raise
821
[docs]
822 def rmdir(self) -> None:
823 """
824 Remove this directory. The directory must be empty.
825
826 Not supported for remote storage paths.
827 """
828 self._storage_client._ensure_writable()
829 if self._storage_client.is_default_profile():
830 Path(self._internal_path).rmdir()
831 else:
832 raise NotImplementedError("MultiStoragePath.rmdir() is unsupported for remote storage paths")
833
834 # Permissions and ownership
835
[docs]
836 def owner(self):
837 """
838 Return the login name of the file owner.
839
840 Not supported for remote storage paths.
841 """
842 if self._storage_client.is_default_profile():
843 return Path(self._internal_path).owner()
844 raise NotImplementedError("MultiStoragePath.owner() is unsupported for remote storage paths")
845
[docs]
846 def group(self):
847 """
848 Return the group name of the file gid.
849
850 Not supported for remote storage paths.
851 """
852 if self._storage_client.is_default_profile():
853 return Path(self._internal_path).group()
854 raise NotImplementedError("MultiStoragePath.group() is unsupported for remote storage paths")
855
[docs]
856 def chmod(self, mode):
857 """
858 Change the permissions of the path, like os.chmod().
859
860 Not supported for remote storage paths.
861 """
862 self._storage_client._ensure_writable()
863 if self._storage_client.is_default_profile():
864 Path(self._internal_path).chmod(mode)
865 else:
866 raise NotImplementedError("MultiStoragePath.chmod() is unsupported for remote storage paths")
867
[docs]
868 def lchmod(self, mode):
869 """
870 Like chmod(), except if the path points to a symlink, the symlink's permissions are changed, rather
871 than its target's.
872
873 Not supported for remote storage paths.
874 """
875 self._storage_client._ensure_writable()
876 if self._storage_client.is_default_profile():
877 Path(self._internal_path).lchmod(mode)
878 else:
879 raise NotImplementedError("MultiStoragePath.lchmod() is unsupported for remote storage paths")