panpath 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- panpath/__init__.py +86 -0
- panpath/azure_async.py +20 -0
- panpath/azure_async_client.py +551 -0
- panpath/azure_client.py +542 -0
- panpath/azure_sync.py +20 -0
- panpath/base.py +946 -0
- panpath/clients.py +273 -0
- panpath/exceptions.py +38 -0
- panpath/gs_async.py +20 -0
- panpath/gs_async_client.py +552 -0
- panpath/gs_client.py +527 -0
- panpath/gs_sync.py +20 -0
- panpath/local_async.py +160 -0
- panpath/local_sync.py +29 -0
- panpath/py.typed +0 -0
- panpath/registry.py +71 -0
- panpath/router.py +174 -0
- panpath/s3_async.py +20 -0
- panpath/s3_async_client.py +590 -0
- panpath/s3_client.py +572 -0
- panpath/s3_sync.py +23 -0
- panpath-0.1.0.dist-info/METADATA +256 -0
- panpath-0.1.0.dist-info/RECORD +25 -0
- panpath-0.1.0.dist-info/WHEEL +4 -0
- panpath-0.1.0.dist-info/licenses/LICENSE +21 -0
panpath/base.py
ADDED
|
@@ -0,0 +1,946 @@
|
|
|
1
|
+
"""Base classes for cloud path implementations."""
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from pathlib import PurePosixPath
|
|
4
|
+
from typing import TYPE_CHECKING, Any, BinaryIO, Iterator, List, Optional, TextIO, Tuple, Union
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from panpath.clients import AsyncClient, Client
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CloudPath(PurePosixPath, ABC):
|
|
11
|
+
"""Base class for synchronous cloud path implementations.
|
|
12
|
+
|
|
13
|
+
Following cloudpathlib pattern: inherits from PurePosixPath for path operations,
|
|
14
|
+
with additional cloud storage methods.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
_client: Optional["Client"] = None
|
|
18
|
+
_default_client: Optional["Client"] = None
|
|
19
|
+
|
|
20
|
+
def __new__(cls, *args: Any, **kwargs: Any) -> "CloudPath":
|
|
21
|
+
"""Create new cloud path instance."""
|
|
22
|
+
# Extract client before passing to PurePosixPath
|
|
23
|
+
client = kwargs.pop('client', None)
|
|
24
|
+
obj = super().__new__(cls, *args, **kwargs) # type: ignore
|
|
25
|
+
obj._client = client
|
|
26
|
+
return obj # type: ignore
|
|
27
|
+
|
|
28
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
29
|
+
"""Initialize cloud path (client already handled in __new__())."""
|
|
30
|
+
# Remove client from kwargs if present (already handled in __new__())
|
|
31
|
+
kwargs.pop('client', None)
|
|
32
|
+
# Python version compatibility for PurePosixPath.__init__():
|
|
33
|
+
# - Python 3.9: Fully initialized in __new__(), __init__() does nothing useful but passes args to object.__init__() which rejects them
|
|
34
|
+
# - Python 3.10-3.11: Similar to 3.9
|
|
35
|
+
# - Python 3.12+: Needs __init__(*args) to set _raw_paths, _drv, etc.
|
|
36
|
+
import sys
|
|
37
|
+
if sys.version_info >= (3, 12):
|
|
38
|
+
# Python 3.12+ requires calling __init__ with args to set internal properties
|
|
39
|
+
super().__init__(*args) # type: ignore
|
|
40
|
+
# else: Python 3.9-3.11 don't need __init__ called (already done in __new__)
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def client(self) -> "Client":
|
|
44
|
+
"""Get or create the client for this path."""
|
|
45
|
+
if self._client is None:
|
|
46
|
+
if self.__class__._default_client is None:
|
|
47
|
+
self.__class__._default_client = self._create_default_client()
|
|
48
|
+
self._client = self.__class__._default_client
|
|
49
|
+
return self._client
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
@abstractmethod
|
|
53
|
+
def _create_default_client(cls) -> "Client":
|
|
54
|
+
"""Create the default client for this path class."""
|
|
55
|
+
...
|
|
56
|
+
|
|
57
|
+
def _new_cloudpath(self, path: str) -> "CloudPath":
|
|
58
|
+
"""Create a new cloud path preserving client and type.
|
|
59
|
+
|
|
60
|
+
This is called by parent, joinpath, etc. to maintain the path type
|
|
61
|
+
and associated client.
|
|
62
|
+
"""
|
|
63
|
+
return self.__class__(path, client=self._client)
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def parent(self) -> "CloudPath":
|
|
67
|
+
"""Return parent directory as same path type."""
|
|
68
|
+
parent_path = super().parent
|
|
69
|
+
return self._new_cloudpath(str(parent_path))
|
|
70
|
+
|
|
71
|
+
def __truediv__(self, other: Any) -> "CloudPath":
|
|
72
|
+
"""Join paths while preserving type and client."""
|
|
73
|
+
result = super().__truediv__(other)
|
|
74
|
+
return self._new_cloudpath(str(result))
|
|
75
|
+
|
|
76
|
+
def __rtruediv__(self, other: Any) -> "CloudPath":
|
|
77
|
+
"""Right join paths while preserving type and client."""
|
|
78
|
+
result = super().__rtruediv__(other)
|
|
79
|
+
return self._new_cloudpath(str(result))
|
|
80
|
+
|
|
81
|
+
def joinpath(self, *args: Any) -> "CloudPath":
|
|
82
|
+
"""Join paths while preserving type and client."""
|
|
83
|
+
result = super().joinpath(*args)
|
|
84
|
+
return self._new_cloudpath(str(result))
|
|
85
|
+
|
|
86
|
+
def __str__(self) -> str:
|
|
87
|
+
"""Return properly formatted cloud URI with double slash."""
|
|
88
|
+
parts = self.parts
|
|
89
|
+
if len(parts) >= 2:
|
|
90
|
+
scheme = parts[0].rstrip(':')
|
|
91
|
+
bucket = parts[1]
|
|
92
|
+
if len(parts) > 2:
|
|
93
|
+
key = "/".join(parts[2:])
|
|
94
|
+
return f"{scheme}://{bucket}/{key}"
|
|
95
|
+
else:
|
|
96
|
+
return f"{scheme}://{bucket}"
|
|
97
|
+
return super().__str__()
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def cloud_prefix(self) -> str:
|
|
101
|
+
"""Return the cloud prefix (e.g., 's3://bucket')."""
|
|
102
|
+
parts = self.parts
|
|
103
|
+
if len(parts) >= 2:
|
|
104
|
+
# parts[0] is 's3:', parts[1] is 'bucket'
|
|
105
|
+
scheme = parts[0].rstrip(':')
|
|
106
|
+
bucket = parts[1]
|
|
107
|
+
return f"{scheme}://{bucket}"
|
|
108
|
+
return ""
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def key(self) -> str:
|
|
112
|
+
"""Return the key/blob name without the cloud prefix."""
|
|
113
|
+
parts = self.parts
|
|
114
|
+
if len(parts) >= 3:
|
|
115
|
+
# Join all parts after scheme and bucket
|
|
116
|
+
return "/".join(parts[2:])
|
|
117
|
+
return ""
|
|
118
|
+
|
|
119
|
+
# Cloud storage operations delegated to client
|
|
120
|
+
def exists(self) -> bool:
|
|
121
|
+
"""Check if path exists."""
|
|
122
|
+
return self.client.exists(str(self))
|
|
123
|
+
|
|
124
|
+
def read_bytes(self) -> bytes:
|
|
125
|
+
"""Read file as bytes."""
|
|
126
|
+
return self.client.read_bytes(str(self))
|
|
127
|
+
|
|
128
|
+
def read_text(self, encoding: str = "utf-8") -> str:
|
|
129
|
+
"""Read file as text."""
|
|
130
|
+
return self.client.read_text(str(self), encoding=encoding)
|
|
131
|
+
|
|
132
|
+
def write_bytes(self, data: bytes) -> None:
|
|
133
|
+
"""Write bytes to file."""
|
|
134
|
+
self.client.write_bytes(str(self), data)
|
|
135
|
+
|
|
136
|
+
def write_text(self, data: str, encoding: str = "utf-8") -> None:
|
|
137
|
+
"""Write text to file."""
|
|
138
|
+
self.client.write_text(str(self), data, encoding=encoding)
|
|
139
|
+
|
|
140
|
+
def unlink(self, missing_ok: bool = False) -> None:
|
|
141
|
+
"""Delete file."""
|
|
142
|
+
try:
|
|
143
|
+
self.client.delete(str(self))
|
|
144
|
+
except FileNotFoundError:
|
|
145
|
+
if not missing_ok:
|
|
146
|
+
raise
|
|
147
|
+
|
|
148
|
+
def iterdir(self) -> Iterator["CloudPath"]:
|
|
149
|
+
"""Iterate over directory contents."""
|
|
150
|
+
for item in self.client.list_dir(str(self)):
|
|
151
|
+
yield self._new_cloudpath(item)
|
|
152
|
+
|
|
153
|
+
def is_dir(self) -> bool:
|
|
154
|
+
"""Check if path is a directory."""
|
|
155
|
+
return self.client.is_dir(str(self))
|
|
156
|
+
|
|
157
|
+
def is_file(self) -> bool:
|
|
158
|
+
"""Check if path is a file."""
|
|
159
|
+
return self.client.is_file(str(self))
|
|
160
|
+
|
|
161
|
+
def stat(self) -> Any:
|
|
162
|
+
"""Get file stats."""
|
|
163
|
+
return self.client.stat(str(self))
|
|
164
|
+
|
|
165
|
+
def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
|
|
166
|
+
"""Create a directory marker in cloud storage.
|
|
167
|
+
|
|
168
|
+
In cloud storage (S3, GCS, Azure), directories are implicit. This method
|
|
169
|
+
creates an empty object with a trailing slash to serve as a directory marker.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
mode: Ignored (for compatibility with pathlib)
|
|
173
|
+
parents: If True, create parent directories as needed
|
|
174
|
+
exist_ok: If True, don't raise error if directory already exists
|
|
175
|
+
"""
|
|
176
|
+
self.client.mkdir(str(self), parents=parents, exist_ok=exist_ok)
|
|
177
|
+
|
|
178
|
+
def open(
|
|
179
|
+
self,
|
|
180
|
+
mode: str = "r",
|
|
181
|
+
encoding: Optional[str] = None,
|
|
182
|
+
**kwargs: Any,
|
|
183
|
+
) -> Union[BinaryIO, TextIO]:
|
|
184
|
+
"""Open file for reading/writing."""
|
|
185
|
+
return self.client.open(str(self), mode=mode, encoding=encoding, **kwargs)
|
|
186
|
+
|
|
187
|
+
def __eq__(self, other: Any) -> bool:
|
|
188
|
+
"""Check equality - sync paths never equal async paths."""
|
|
189
|
+
if isinstance(other, AsyncCloudPath):
|
|
190
|
+
raise ValueError(
|
|
191
|
+
"Cannot compare sync and async paths. "
|
|
192
|
+
f"Use to_async() to convert {type(self).__name__} to async, "
|
|
193
|
+
f"or to_sync() to convert {type(other).__name__} to sync."
|
|
194
|
+
)
|
|
195
|
+
return super().__eq__(other)
|
|
196
|
+
|
|
197
|
+
def __hash__(self) -> int:
|
|
198
|
+
"""Return hash of path."""
|
|
199
|
+
return super().__hash__()
|
|
200
|
+
|
|
201
|
+
def absolute(self) -> "CloudPath":
|
|
202
|
+
"""Return absolute path - cloud paths are already absolute."""
|
|
203
|
+
return self
|
|
204
|
+
|
|
205
|
+
def is_absolute(self) -> bool:
|
|
206
|
+
"""Cloud paths are always absolute."""
|
|
207
|
+
return True
|
|
208
|
+
|
|
209
|
+
def as_uri(self) -> str:
|
|
210
|
+
"""Return the path as a URI (same as string representation)."""
|
|
211
|
+
return str(self)
|
|
212
|
+
|
|
213
|
+
def match(self, pattern: str) -> bool:
|
|
214
|
+
"""Match path against glob pattern.
|
|
215
|
+
|
|
216
|
+
Override to work correctly with cloud URIs by matching against
|
|
217
|
+
the key portion of the path (excluding scheme and bucket).
|
|
218
|
+
"""
|
|
219
|
+
from pathlib import PurePosixPath
|
|
220
|
+
|
|
221
|
+
# For cloud paths, we want to match against the key part only (path after bucket)
|
|
222
|
+
# Get the key portion (all parts after scheme and bucket)
|
|
223
|
+
our_parts = self.parts[2:] if len(self.parts) > 2 else ()
|
|
224
|
+
|
|
225
|
+
# If no key parts, can only match empty patterns
|
|
226
|
+
if not our_parts:
|
|
227
|
+
return pattern in ('', '*', '**')
|
|
228
|
+
|
|
229
|
+
# Create a PurePosixPath from the key parts to do matching
|
|
230
|
+
key_path = PurePosixPath(*our_parts)
|
|
231
|
+
|
|
232
|
+
# Use PurePosixPath's match which handles ** correctly
|
|
233
|
+
return key_path.match(pattern)
|
|
234
|
+
|
|
235
|
+
def to_async(self) -> "AsyncCloudPath":
|
|
236
|
+
"""Convert this sync path to an async path.
|
|
237
|
+
|
|
238
|
+
Returns:
|
|
239
|
+
AsyncCloudPath instance with the same path and client type.
|
|
240
|
+
|
|
241
|
+
Example:
|
|
242
|
+
>>> sync_path = PanPath("s3://bucket/key.txt")
|
|
243
|
+
>>> async_path = sync_path.to_async()
|
|
244
|
+
>>> isinstance(async_path, AsyncS3Path)
|
|
245
|
+
True
|
|
246
|
+
"""
|
|
247
|
+
# Import here to avoid circular imports
|
|
248
|
+
from panpath.router import PanPath
|
|
249
|
+
return PanPath(str(self), mode="async") # type: ignore
|
|
250
|
+
|
|
251
|
+
def glob(self, pattern: str) -> List["CloudPath"]:
|
|
252
|
+
"""Glob for files matching pattern.
|
|
253
|
+
|
|
254
|
+
Args:
|
|
255
|
+
pattern: Pattern to match (e.g., "*.txt", "**/*.py")
|
|
256
|
+
|
|
257
|
+
Returns:
|
|
258
|
+
List of matching paths
|
|
259
|
+
"""
|
|
260
|
+
return self.client.glob(str(self), pattern)
|
|
261
|
+
|
|
262
|
+
def rglob(self, pattern: str) -> List["CloudPath"]:
|
|
263
|
+
"""Recursively glob for files matching pattern.
|
|
264
|
+
|
|
265
|
+
Args:
|
|
266
|
+
pattern: Pattern to match (e.g., "*.txt", "*.py")
|
|
267
|
+
|
|
268
|
+
Returns:
|
|
269
|
+
List of matching paths (recursive)
|
|
270
|
+
"""
|
|
271
|
+
return self.glob(f"**/{pattern}")
|
|
272
|
+
|
|
273
|
+
def walk(self) -> List[Tuple[str, List[str], List[str]]]:
|
|
274
|
+
"""Walk directory tree (like os.walk).
|
|
275
|
+
|
|
276
|
+
Returns:
|
|
277
|
+
List of (dirpath, dirnames, filenames) tuples
|
|
278
|
+
"""
|
|
279
|
+
return self.client.walk(str(self))
|
|
280
|
+
|
|
281
|
+
def touch(self, exist_ok: bool = True) -> None:
|
|
282
|
+
"""Create empty file.
|
|
283
|
+
|
|
284
|
+
Args:
|
|
285
|
+
exist_ok: If False, raise error if file exists
|
|
286
|
+
"""
|
|
287
|
+
self.client.touch(str(self), exist_ok=exist_ok)
|
|
288
|
+
|
|
289
|
+
def rename(self, target: Union[str, "CloudPath"]) -> "CloudPath":
|
|
290
|
+
"""Rename/move file to target.
|
|
291
|
+
|
|
292
|
+
Can move between cloud and local paths.
|
|
293
|
+
|
|
294
|
+
Args:
|
|
295
|
+
target: New path (can be cloud or local)
|
|
296
|
+
|
|
297
|
+
Returns:
|
|
298
|
+
New path instance
|
|
299
|
+
"""
|
|
300
|
+
target_str = str(target)
|
|
301
|
+
# Check if cross-storage operation (cloud <-> local or cloud <-> cloud)
|
|
302
|
+
if self._is_cross_storage_op(str(self), target_str):
|
|
303
|
+
# Copy then delete for cross-storage
|
|
304
|
+
self._copy_cross_storage(str(self), target_str)
|
|
305
|
+
self.unlink()
|
|
306
|
+
else:
|
|
307
|
+
# Same storage, use native rename
|
|
308
|
+
self.client.rename(str(self), target_str)
|
|
309
|
+
from panpath.router import PanPath
|
|
310
|
+
return PanPath(target_str) # type: ignore def replace(self, target: Union[str, "CloudPath"]) -> "CloudPath":
|
|
311
|
+
"""Replace file at target (overwriting if exists).
|
|
312
|
+
|
|
313
|
+
Args:
|
|
314
|
+
target: Target path
|
|
315
|
+
|
|
316
|
+
Returns:
|
|
317
|
+
New path instance
|
|
318
|
+
"""
|
|
319
|
+
# For cloud storage, replace is same as rename (always overwrites)
|
|
320
|
+
return self.rename(target)
|
|
321
|
+
|
|
322
|
+
def rmdir(self) -> None:
|
|
323
|
+
"""Remove empty directory marker."""
|
|
324
|
+
self.client.rmdir(str(self))
|
|
325
|
+
|
|
326
|
+
def resolve(self) -> "CloudPath":
|
|
327
|
+
"""Resolve to absolute path (no-op for cloud paths).
|
|
328
|
+
|
|
329
|
+
Returns:
|
|
330
|
+
Self (cloud paths are already absolute)
|
|
331
|
+
"""
|
|
332
|
+
return self
|
|
333
|
+
|
|
334
|
+
def samefile(self, other: Union[str, "CloudPath"]) -> bool:
|
|
335
|
+
"""Check if this path refers to same file as other.
|
|
336
|
+
|
|
337
|
+
Args:
|
|
338
|
+
other: Path to compare
|
|
339
|
+
|
|
340
|
+
Returns:
|
|
341
|
+
True if paths are the same
|
|
342
|
+
"""
|
|
343
|
+
return str(self) == str(other)
|
|
344
|
+
|
|
345
|
+
def is_symlink(self) -> bool:
|
|
346
|
+
"""Check if this is a symbolic link (via metadata).
|
|
347
|
+
|
|
348
|
+
Returns:
|
|
349
|
+
True if symlink metadata exists
|
|
350
|
+
"""
|
|
351
|
+
return self.client.is_symlink(str(self))
|
|
352
|
+
|
|
353
|
+
def readlink(self) -> "CloudPath":
|
|
354
|
+
"""Read symlink target from metadata.
|
|
355
|
+
|
|
356
|
+
Returns:
|
|
357
|
+
Path that this symlink points to
|
|
358
|
+
"""
|
|
359
|
+
target = self.client.readlink(str(self))
|
|
360
|
+
from panpath.router import PanPath
|
|
361
|
+
return PanPath(target) # type: ignore
|
|
362
|
+
|
|
363
|
+
def symlink_to(self, target: Union[str, "CloudPath"]) -> None:
|
|
364
|
+
"""Create symlink pointing to target (via metadata).
|
|
365
|
+
|
|
366
|
+
Args:
|
|
367
|
+
target: Path this symlink should point to (absolute with scheme or relative)
|
|
368
|
+
"""
|
|
369
|
+
target_str = str(target)
|
|
370
|
+
# If target doesn't have a scheme prefix, treat as relative path
|
|
371
|
+
if "://" not in target_str:
|
|
372
|
+
# Resolve relative to symlink's parent directory
|
|
373
|
+
target_str = str(self.parent / target_str)
|
|
374
|
+
self.client.symlink_to(str(self), target_str)
|
|
375
|
+
|
|
376
|
+
def rmtree(self, ignore_errors: bool = False, onerror: Optional[Any] = None) -> None:
|
|
377
|
+
"""Remove directory and all its contents recursively.
|
|
378
|
+
|
|
379
|
+
Args:
|
|
380
|
+
ignore_errors: If True, errors are ignored
|
|
381
|
+
onerror: Callable that accepts (function, path, excinfo)
|
|
382
|
+
"""
|
|
383
|
+
self.client.rmtree(str(self), ignore_errors=ignore_errors, onerror=onerror)
|
|
384
|
+
|
|
385
|
+
def copy(self, target: Union[str, "CloudPath"], follow_symlinks: bool = True) -> "CloudPath":
|
|
386
|
+
"""Copy file to target.
|
|
387
|
+
|
|
388
|
+
Can copy between cloud and local paths.
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
target: Destination path (can be cloud or local)
|
|
392
|
+
|
|
393
|
+
Returns:
|
|
394
|
+
Target path instance
|
|
395
|
+
"""
|
|
396
|
+
target_str = str(target)
|
|
397
|
+
# Check if cross-storage operation
|
|
398
|
+
if self._is_cross_storage_op(str(self), target_str):
|
|
399
|
+
self._copy_cross_storage(str(self), target_str)
|
|
400
|
+
else:
|
|
401
|
+
# Same storage, use native copy
|
|
402
|
+
self.client.copy(str(self), target_str)
|
|
403
|
+
from panpath.router import PanPath
|
|
404
|
+
return PanPath(target_str) # type: ignore
|
|
405
|
+
|
|
406
|
+
def copytree(self, target: Union[str, "CloudPath"], follow_symlinks: bool = True) -> "CloudPath":
|
|
407
|
+
"""Copy directory tree to target recursively.
|
|
408
|
+
|
|
409
|
+
Can copy between cloud and local paths.
|
|
410
|
+
|
|
411
|
+
Args:
|
|
412
|
+
target: Destination path (can be cloud or local)
|
|
413
|
+
follow_symlinks: If False, symlinks are copied as symlinks (not dereferenced)
|
|
414
|
+
|
|
415
|
+
Returns:
|
|
416
|
+
Target path instance
|
|
417
|
+
"""
|
|
418
|
+
target_str = str(target)
|
|
419
|
+
# Check if cross-storage operation
|
|
420
|
+
if self._is_cross_storage_op(str(self), target_str):
|
|
421
|
+
self._copytree_cross_storage(str(self), target_str, follow_symlinks=follow_symlinks)
|
|
422
|
+
else:
|
|
423
|
+
# Same storage, use native copytree
|
|
424
|
+
self.client.copytree(str(self), target_str, follow_symlinks=follow_symlinks)
|
|
425
|
+
from panpath.router import PanPath
|
|
426
|
+
return PanPath(target_str) # type: ignore
|
|
427
|
+
|
|
428
|
+
@staticmethod
|
|
429
|
+
def _is_cross_storage_op(src: str, dst: str) -> bool:
|
|
430
|
+
"""Check if operation crosses storage boundaries."""
|
|
431
|
+
src_scheme = src.split("://")[0] if "://" in src else "file"
|
|
432
|
+
dst_scheme = dst.split("://")[0] if "://" in dst else "file"
|
|
433
|
+
return src_scheme != dst_scheme
|
|
434
|
+
|
|
435
|
+
@staticmethod
|
|
436
|
+
def _copy_cross_storage(src: str, dst: str, follow_symlinks: bool = True) -> None:
|
|
437
|
+
"""Copy file across storage boundaries."""
|
|
438
|
+
from panpath.router import PanPath
|
|
439
|
+
src_path = PanPath(src)
|
|
440
|
+
dst_path = PanPath(dst)
|
|
441
|
+
|
|
442
|
+
# Handle symlinks
|
|
443
|
+
if not follow_symlinks and src_path.is_symlink():
|
|
444
|
+
# Copy as symlink
|
|
445
|
+
target = src_path.readlink()
|
|
446
|
+
dst_path.symlink_to(str(target))
|
|
447
|
+
else:
|
|
448
|
+
# Read from source and write to destination
|
|
449
|
+
data = src_path.read_bytes()
|
|
450
|
+
dst_path.write_bytes(data)
|
|
451
|
+
|
|
452
|
+
@staticmethod
|
|
453
|
+
def _copytree_cross_storage(src: str, dst: str, follow_symlinks: bool = True) -> None:
|
|
454
|
+
"""Copy directory tree across storage boundaries."""
|
|
455
|
+
from panpath.router import PanPath
|
|
456
|
+
src_path = PanPath(src)
|
|
457
|
+
dst_path = PanPath(dst)
|
|
458
|
+
|
|
459
|
+
# Create destination directory
|
|
460
|
+
dst_path.mkdir(parents=True, exist_ok=True)
|
|
461
|
+
|
|
462
|
+
# Walk source tree and copy all files
|
|
463
|
+
for dirpath, dirnames, filenames in src_path.walk():
|
|
464
|
+
# Calculate relative path from src
|
|
465
|
+
rel_dir = dirpath[len(str(src)):].lstrip("/")
|
|
466
|
+
|
|
467
|
+
# Create subdirectories in destination
|
|
468
|
+
for dirname in dirnames:
|
|
469
|
+
dst_subdir = dst_path / rel_dir / dirname if rel_dir else dst_path / dirname
|
|
470
|
+
dst_subdir.mkdir(parents=True, exist_ok=True)
|
|
471
|
+
|
|
472
|
+
# Copy files
|
|
473
|
+
for filename in filenames:
|
|
474
|
+
src_file = PanPath(dirpath) / filename
|
|
475
|
+
dst_file = dst_path / rel_dir / filename if rel_dir else dst_path / filename
|
|
476
|
+
# Handle symlinks
|
|
477
|
+
if not follow_symlinks and src_file.is_symlink():
|
|
478
|
+
# Copy as symlink
|
|
479
|
+
target = src_file.readlink()
|
|
480
|
+
dst_file.symlink_to(str(target))
|
|
481
|
+
else:
|
|
482
|
+
data = src_file.read_bytes()
|
|
483
|
+
dst_file.write_bytes(data)
|
|
484
|
+
|
|
485
|
+
class AsyncCloudPath(PurePosixPath, ABC):
|
|
486
|
+
"""Base class for asynchronous cloud path implementations."""
|
|
487
|
+
|
|
488
|
+
_client: Optional["AsyncClient"] = None
|
|
489
|
+
_default_client: Optional["AsyncClient"] = None
|
|
490
|
+
|
|
491
|
+
def __new__(cls, *args: Any, **kwargs: Any) -> "AsyncCloudPath":
|
|
492
|
+
"""Create new async cloud path instance."""
|
|
493
|
+
# Extract client before passing to PurePosixPath
|
|
494
|
+
client = kwargs.pop('client', None)
|
|
495
|
+
obj = super().__new__(cls, *args, **kwargs) # type: ignore
|
|
496
|
+
obj._client = client
|
|
497
|
+
return obj # type: ignore
|
|
498
|
+
|
|
499
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
500
|
+
"""Initialize async cloud path (client already handled in __new__())."""
|
|
501
|
+
# Remove client from kwargs if present (already handled in __new__())
|
|
502
|
+
kwargs.pop('client', None)
|
|
503
|
+
# Python version compatibility for PurePosixPath.__init__():
|
|
504
|
+
# - Python 3.9: Fully initialized in __new__(), __init__() does nothing useful but passes args to object.__init__() which rejects them
|
|
505
|
+
# - Python 3.10-3.11: Similar to 3.9
|
|
506
|
+
# - Python 3.12+: Needs __init__(*args) to set _raw_paths, _drv, etc.
|
|
507
|
+
import sys
|
|
508
|
+
if sys.version_info >= (3, 12):
|
|
509
|
+
# Python 3.12+ requires calling __init__ with args to set internal properties
|
|
510
|
+
super().__init__(*args) # type: ignore
|
|
511
|
+
# else: Python 3.9-3.11 don't need __init__ called (already done in __new__)
|
|
512
|
+
|
|
513
|
+
@property
|
|
514
|
+
def client(self) -> "AsyncClient":
|
|
515
|
+
"""Get or create the async client for this path."""
|
|
516
|
+
if self._client is None:
|
|
517
|
+
if self.__class__._default_client is None:
|
|
518
|
+
self.__class__._default_client = self._create_default_client()
|
|
519
|
+
self._client = self.__class__._default_client
|
|
520
|
+
return self._client
|
|
521
|
+
|
|
522
|
+
@classmethod
|
|
523
|
+
@abstractmethod
|
|
524
|
+
def _create_default_client(cls) -> "AsyncClient":
|
|
525
|
+
"""Create the default async client for this path class."""
|
|
526
|
+
...
|
|
527
|
+
|
|
528
|
+
def _new_cloudpath(self, path: str) -> "AsyncCloudPath":
|
|
529
|
+
"""Create a new async cloud path preserving client and type."""
|
|
530
|
+
return self.__class__(path, client=self._client)
|
|
531
|
+
|
|
532
|
+
@property
|
|
533
|
+
def parent(self) -> "AsyncCloudPath":
|
|
534
|
+
"""Return parent directory as same path type."""
|
|
535
|
+
parent_path = super().parent
|
|
536
|
+
return self._new_cloudpath(str(parent_path))
|
|
537
|
+
|
|
538
|
+
def __truediv__(self, other: Any) -> "AsyncCloudPath":
|
|
539
|
+
"""Join paths while preserving type and client."""
|
|
540
|
+
result = super().__truediv__(other)
|
|
541
|
+
return self._new_cloudpath(str(result))
|
|
542
|
+
|
|
543
|
+
def __rtruediv__(self, other: Any) -> "AsyncCloudPath":
|
|
544
|
+
"""Right join paths while preserving type and client."""
|
|
545
|
+
result = super().__rtruediv__(other)
|
|
546
|
+
return self._new_cloudpath(str(result))
|
|
547
|
+
|
|
548
|
+
def joinpath(self, *args: Any) -> "AsyncCloudPath":
|
|
549
|
+
"""Join paths while preserving type and client."""
|
|
550
|
+
result = super().joinpath(*args)
|
|
551
|
+
return self._new_cloudpath(str(result))
|
|
552
|
+
|
|
553
|
+
def __str__(self) -> str:
|
|
554
|
+
"""Return properly formatted cloud URI with double slash."""
|
|
555
|
+
parts = self.parts
|
|
556
|
+
if len(parts) >= 2:
|
|
557
|
+
scheme = parts[0].rstrip(':')
|
|
558
|
+
bucket = parts[1]
|
|
559
|
+
if len(parts) > 2:
|
|
560
|
+
key = "/".join(parts[2:])
|
|
561
|
+
return f"{scheme}://{bucket}/{key}"
|
|
562
|
+
else:
|
|
563
|
+
return f"{scheme}://{bucket}"
|
|
564
|
+
return super().__str__()
|
|
565
|
+
|
|
566
|
+
@property
|
|
567
|
+
def cloud_prefix(self) -> str:
|
|
568
|
+
"""Return the cloud prefix (e.g., 's3://bucket')."""
|
|
569
|
+
parts = self.parts
|
|
570
|
+
if len(parts) >= 2:
|
|
571
|
+
# parts[0] is 's3:', parts[1] is 'bucket'
|
|
572
|
+
scheme = parts[0].rstrip(':')
|
|
573
|
+
bucket = parts[1]
|
|
574
|
+
return f"{scheme}://{bucket}"
|
|
575
|
+
return ""
|
|
576
|
+
|
|
577
|
+
@property
|
|
578
|
+
def key(self) -> str:
|
|
579
|
+
"""Return the key/blob name without the cloud prefix."""
|
|
580
|
+
parts = self.parts
|
|
581
|
+
if len(parts) >= 3:
|
|
582
|
+
# Join all parts after scheme and bucket
|
|
583
|
+
return "/".join(parts[2:])
|
|
584
|
+
return ""
|
|
585
|
+
|
|
586
|
+
# Async cloud storage operations delegated to client
|
|
587
|
+
async def exists(self) -> bool:
|
|
588
|
+
"""Check if path exists."""
|
|
589
|
+
return await self.client.exists(str(self))
|
|
590
|
+
|
|
591
|
+
async def read_bytes(self) -> bytes:
|
|
592
|
+
"""Read file as bytes."""
|
|
593
|
+
return await self.client.read_bytes(str(self))
|
|
594
|
+
|
|
595
|
+
async def read_text(self, encoding: str = "utf-8") -> str:
|
|
596
|
+
"""Read file as text."""
|
|
597
|
+
return await self.client.read_text(str(self), encoding=encoding)
|
|
598
|
+
|
|
599
|
+
async def write_bytes(self, data: bytes) -> None:
|
|
600
|
+
"""Write bytes to file."""
|
|
601
|
+
await self.client.write_bytes(str(self), data)
|
|
602
|
+
|
|
603
|
+
async def write_text(self, data: str, encoding: str = "utf-8") -> None:
|
|
604
|
+
"""Write text to file."""
|
|
605
|
+
await self.client.write_text(str(self), data, encoding=encoding)
|
|
606
|
+
|
|
607
|
+
async def unlink(self, missing_ok: bool = False) -> None:
|
|
608
|
+
"""Delete file."""
|
|
609
|
+
try:
|
|
610
|
+
await self.client.delete(str(self))
|
|
611
|
+
except FileNotFoundError:
|
|
612
|
+
if not missing_ok:
|
|
613
|
+
raise
|
|
614
|
+
|
|
615
|
+
async def iterdir(self) -> list["AsyncCloudPath"]:
|
|
616
|
+
"""List directory contents (async version returns list)."""
|
|
617
|
+
items = await self.client.list_dir(str(self))
|
|
618
|
+
return [self._new_cloudpath(item) for item in items]
|
|
619
|
+
|
|
620
|
+
async def is_dir(self) -> bool:
|
|
621
|
+
"""Check if path is a directory."""
|
|
622
|
+
return await self.client.is_dir(str(self))
|
|
623
|
+
|
|
624
|
+
async def is_file(self) -> bool:
|
|
625
|
+
"""Check if path is a file."""
|
|
626
|
+
return await self.client.is_file(str(self))
|
|
627
|
+
|
|
628
|
+
async def stat(self) -> Any:
|
|
629
|
+
"""Get file stats."""
|
|
630
|
+
return await self.client.stat(str(self))
|
|
631
|
+
|
|
632
|
+
async def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
|
|
633
|
+
"""Create a directory marker in cloud storage.
|
|
634
|
+
|
|
635
|
+
In cloud storage (S3, GCS, Azure), directories are implicit. This method
|
|
636
|
+
creates an empty object with a trailing slash to serve as a directory marker.
|
|
637
|
+
|
|
638
|
+
Args:
|
|
639
|
+
mode: Ignored (for compatibility with pathlib)
|
|
640
|
+
parents: If True, create parent directories as needed
|
|
641
|
+
exist_ok: If True, don't raise error if directory already exists
|
|
642
|
+
"""
|
|
643
|
+
await self.client.mkdir(str(self), parents=parents, exist_ok=exist_ok)
|
|
644
|
+
|
|
645
|
+
async def open(
|
|
646
|
+
self,
|
|
647
|
+
mode: str = "r",
|
|
648
|
+
encoding: Optional[str] = None,
|
|
649
|
+
**kwargs: Any,
|
|
650
|
+
) -> Any:
|
|
651
|
+
"""Open file for reading/writing (returns async file handle)."""
|
|
652
|
+
return await self.client.open(str(self), mode=mode, encoding=encoding, **kwargs)
|
|
653
|
+
|
|
654
|
+
def __eq__(self, other: Any) -> bool:
|
|
655
|
+
"""Check equality - async paths never equal sync paths."""
|
|
656
|
+
if isinstance(other, CloudPath):
|
|
657
|
+
raise ValueError(
|
|
658
|
+
"Cannot compare sync and async paths. "
|
|
659
|
+
f"Use to_async() to convert {type(other).__name__} to async, "
|
|
660
|
+
f"or to_sync() to convert {type(self).__name__} to sync."
|
|
661
|
+
)
|
|
662
|
+
return super().__eq__(other)
|
|
663
|
+
|
|
664
|
+
def __hash__(self) -> int:
|
|
665
|
+
"""Return hash of path."""
|
|
666
|
+
return super().__hash__()
|
|
667
|
+
|
|
668
|
+
def absolute(self) -> "AsyncCloudPath":
|
|
669
|
+
"""Return absolute path - cloud paths are already absolute."""
|
|
670
|
+
return self
|
|
671
|
+
|
|
672
|
+
def is_absolute(self) -> bool:
|
|
673
|
+
"""Cloud paths are always absolute."""
|
|
674
|
+
return True
|
|
675
|
+
|
|
676
|
+
def as_uri(self) -> str:
|
|
677
|
+
"""Return the path as a URI (same as string representation)."""
|
|
678
|
+
return str(self)
|
|
679
|
+
|
|
680
|
+
def match(self, pattern: str) -> bool:
|
|
681
|
+
"""Match path against glob pattern.
|
|
682
|
+
|
|
683
|
+
Override to work correctly with cloud URIs by matching against
|
|
684
|
+
the key portion of the path (excluding scheme and bucket).
|
|
685
|
+
"""
|
|
686
|
+
from pathlib import PurePosixPath
|
|
687
|
+
|
|
688
|
+
# For cloud paths, we want to match against the key part only (path after bucket)
|
|
689
|
+
# Get the key portion (all parts after scheme and bucket)
|
|
690
|
+
our_parts = self.parts[2:] if len(self.parts) > 2 else ()
|
|
691
|
+
|
|
692
|
+
# If no key parts, can only match empty patterns
|
|
693
|
+
if not our_parts:
|
|
694
|
+
return pattern in ('', '*', '**')
|
|
695
|
+
|
|
696
|
+
# Create a PurePosixPath from the key parts to do matching
|
|
697
|
+
key_path = PurePosixPath(*our_parts)
|
|
698
|
+
|
|
699
|
+
# Use PurePosixPath's match which handles ** correctly
|
|
700
|
+
return key_path.match(pattern)
|
|
701
|
+
|
|
702
|
+
def to_sync(self) -> "CloudPath":
|
|
703
|
+
"""Convert async path to sync path.
|
|
704
|
+
|
|
705
|
+
Returns:
|
|
706
|
+
CloudPath instance with the same path and client type.
|
|
707
|
+
|
|
708
|
+
Example:
|
|
709
|
+
>>> async_path = AsyncPanPath("s3://bucket/key.txt")
|
|
710
|
+
>>> sync_path = async_path.to_sync()
|
|
711
|
+
>>> isinstance(sync_path, S3Path)
|
|
712
|
+
True
|
|
713
|
+
"""
|
|
714
|
+
# Import here to avoid circular imports
|
|
715
|
+
from panpath.router import PanPath
|
|
716
|
+
return PanPath(str(self), mode="sync") # type: ignore
|
|
717
|
+
|
|
718
|
+
async def glob(self, pattern: str) -> List["AsyncCloudPath"]:
|
|
719
|
+
"""Glob for files matching pattern.
|
|
720
|
+
|
|
721
|
+
Args:
|
|
722
|
+
pattern: Pattern to match (e.g., "*.txt", "**/*.py")
|
|
723
|
+
|
|
724
|
+
Returns:
|
|
725
|
+
List of matching paths
|
|
726
|
+
"""
|
|
727
|
+
return await self.client.glob(str(self), pattern)
|
|
728
|
+
|
|
729
|
+
async def rglob(self, pattern: str) -> List["AsyncCloudPath"]:
|
|
730
|
+
"""Recursively glob for files matching pattern.
|
|
731
|
+
|
|
732
|
+
Args:
|
|
733
|
+
pattern: Pattern to match (e.g., "*.txt", "*.py")
|
|
734
|
+
|
|
735
|
+
Returns:
|
|
736
|
+
List of matching paths (recursive)
|
|
737
|
+
"""
|
|
738
|
+
return await self.glob(f"**/{pattern}")
|
|
739
|
+
|
|
740
|
+
async def walk(self) -> List[Tuple[str, List[str], List[str]]]:
|
|
741
|
+
"""Walk directory tree (like os.walk).
|
|
742
|
+
|
|
743
|
+
Returns:
|
|
744
|
+
List of (dirpath, dirnames, filenames) tuples
|
|
745
|
+
"""
|
|
746
|
+
return await self.client.walk(str(self))
|
|
747
|
+
|
|
748
|
+
async def touch(self, exist_ok: bool = True) -> None:
|
|
749
|
+
"""Create empty file.
|
|
750
|
+
|
|
751
|
+
Args:
|
|
752
|
+
exist_ok: If False, raise error if file exists
|
|
753
|
+
"""
|
|
754
|
+
await self.client.touch(str(self), exist_ok=exist_ok)
|
|
755
|
+
|
|
756
|
+
async def rename(self, target: Union[str, "AsyncCloudPath"]) -> "AsyncCloudPath":
|
|
757
|
+
"""Rename/move file to target.
|
|
758
|
+
|
|
759
|
+
Can move between cloud and local paths.
|
|
760
|
+
|
|
761
|
+
Args:
|
|
762
|
+
target: New path (can be cloud or local)
|
|
763
|
+
|
|
764
|
+
Returns:
|
|
765
|
+
New path instance
|
|
766
|
+
"""
|
|
767
|
+
target_str = str(target)
|
|
768
|
+
# Check if cross-storage operation
|
|
769
|
+
if CloudPath._is_cross_storage_op(str(self), target_str):
|
|
770
|
+
# Copy then delete for cross-storage
|
|
771
|
+
await self._copy_cross_storage_async(str(self), target_str)
|
|
772
|
+
await self.unlink()
|
|
773
|
+
else:
|
|
774
|
+
# Same storage, use native rename
|
|
775
|
+
await self.client.rename(str(self), target_str)
|
|
776
|
+
from panpath.router import PanPath
|
|
777
|
+
return PanPath(target_str, mode="async") # type: ignore
|
|
778
|
+
|
|
779
|
+
async def replace(self, target: Union[str, "AsyncCloudPath"]) -> "AsyncCloudPath":
|
|
780
|
+
"""Replace file at target (overwriting if exists).
|
|
781
|
+
|
|
782
|
+
Args:
|
|
783
|
+
target: Target path
|
|
784
|
+
|
|
785
|
+
Returns:
|
|
786
|
+
New path instance
|
|
787
|
+
"""
|
|
788
|
+
# For cloud storage, replace is same as rename (always overwrites)
|
|
789
|
+
return await self.rename(target)
|
|
790
|
+
|
|
791
|
+
async def rmdir(self) -> None:
|
|
792
|
+
"""Remove empty directory marker."""
|
|
793
|
+
await self.client.rmdir(str(self))
|
|
794
|
+
|
|
795
|
+
def resolve(self) -> "AsyncCloudPath":
|
|
796
|
+
"""Resolve to absolute path (no-op for cloud paths).
|
|
797
|
+
|
|
798
|
+
Returns:
|
|
799
|
+
Self (cloud paths are already absolute)
|
|
800
|
+
"""
|
|
801
|
+
return self
|
|
802
|
+
|
|
803
|
+
def samefile(self, other: Union[str, "AsyncCloudPath"]) -> bool:
|
|
804
|
+
"""Check if this path refers to same file as other.
|
|
805
|
+
|
|
806
|
+
Args:
|
|
807
|
+
other: Path to compare
|
|
808
|
+
|
|
809
|
+
Returns:
|
|
810
|
+
True if paths are the same
|
|
811
|
+
"""
|
|
812
|
+
return str(self) == str(other)
|
|
813
|
+
|
|
814
|
+
async def is_symlink(self) -> bool:
|
|
815
|
+
"""Check if this is a symbolic link (via metadata).
|
|
816
|
+
|
|
817
|
+
Returns:
|
|
818
|
+
True if symlink metadata exists
|
|
819
|
+
"""
|
|
820
|
+
return await self.client.is_symlink(str(self))
|
|
821
|
+
|
|
822
|
+
async def readlink(self) -> "AsyncCloudPath":
|
|
823
|
+
"""Read symlink target from metadata.
|
|
824
|
+
|
|
825
|
+
Returns:
|
|
826
|
+
Path that this symlink points to
|
|
827
|
+
"""
|
|
828
|
+
target = await self.client.readlink(str(self))
|
|
829
|
+
from panpath.router import PanPath
|
|
830
|
+
return PanPath(target, mode="async") # type: ignore
|
|
831
|
+
|
|
832
|
+
async def symlink_to(self, target: Union[str, "AsyncCloudPath"]) -> None:
|
|
833
|
+
"""Create symlink pointing to target (via metadata).
|
|
834
|
+
|
|
835
|
+
Args:
|
|
836
|
+
target: Path this symlink should point to (absolute with scheme or relative)
|
|
837
|
+
"""
|
|
838
|
+
target_str = str(target)
|
|
839
|
+
# If target doesn't have a scheme prefix, treat as relative path
|
|
840
|
+
if "://" not in target_str:
|
|
841
|
+
# Resolve relative to symlink's parent directory
|
|
842
|
+
target_str = str(self.parent / target_str)
|
|
843
|
+
await self.client.symlink_to(str(self), target_str)
|
|
844
|
+
|
|
845
|
+
async def rmtree(self, ignore_errors: bool = False, onerror: Optional[Any] = None) -> None:
|
|
846
|
+
"""Remove directory and all its contents recursively.
|
|
847
|
+
|
|
848
|
+
Args:
|
|
849
|
+
ignore_errors: If True, errors are ignored
|
|
850
|
+
onerror: Callable that accepts (function, path, excinfo)
|
|
851
|
+
"""
|
|
852
|
+
await self.client.rmtree(str(self), ignore_errors=ignore_errors, onerror=onerror)
|
|
853
|
+
|
|
854
|
+
async def copy(self, target: Union[str, "AsyncCloudPath"], follow_symlinks: bool = True) -> "AsyncCloudPath":
|
|
855
|
+
"""Copy file to target.
|
|
856
|
+
|
|
857
|
+
Can copy between cloud and local paths.
|
|
858
|
+
|
|
859
|
+
Args:
|
|
860
|
+
target: Destination path (can be cloud or local)
|
|
861
|
+
|
|
862
|
+
Returns:
|
|
863
|
+
Target path instance
|
|
864
|
+
"""
|
|
865
|
+
target_str = str(target)
|
|
866
|
+
# Check if cross-storage operation
|
|
867
|
+
if CloudPath._is_cross_storage_op(str(self), target_str):
|
|
868
|
+
await self._copy_cross_storage_async(str(self), target_str, follow_symlinks=follow_symlinks)
|
|
869
|
+
else:
|
|
870
|
+
# Same storage, use native copy
|
|
871
|
+
await self.client.copy(str(self), target_str, follow_symlinks=follow_symlinks)
|
|
872
|
+
from panpath.router import PanPath
|
|
873
|
+
return PanPath(target_str, mode="async") # type: ignore
|
|
874
|
+
|
|
875
|
+
async def copytree(self, target: Union[str, "AsyncCloudPath"], follow_symlinks: bool = True) -> "AsyncCloudPath":
|
|
876
|
+
"""Copy directory tree to target recursively.
|
|
877
|
+
|
|
878
|
+
Can copy between cloud and local paths.
|
|
879
|
+
|
|
880
|
+
Args:
|
|
881
|
+
target: Destination path (can be cloud or local)
|
|
882
|
+
follow_symlinks: If False, symlinks are copied as symlinks (not dereferenced)
|
|
883
|
+
|
|
884
|
+
Returns:
|
|
885
|
+
Target path instance
|
|
886
|
+
"""
|
|
887
|
+
target_str = str(target)
|
|
888
|
+
# Check if cross-storage operation
|
|
889
|
+
if CloudPath._is_cross_storage_op(str(self), target_str):
|
|
890
|
+
await self._copytree_cross_storage_async(str(self), target_str, follow_symlinks=follow_symlinks)
|
|
891
|
+
else:
|
|
892
|
+
# Same storage, use native copytree
|
|
893
|
+
await self.client.copytree(str(self), target_str, follow_symlinks=follow_symlinks)
|
|
894
|
+
from panpath.router import PanPath
|
|
895
|
+
return PanPath(target_str, mode="async") # type: ignore
|
|
896
|
+
|
|
897
|
+
@staticmethod
|
|
898
|
+
async def _copy_cross_storage_async(src: str, dst: str, follow_symlinks: bool = True) -> None:
|
|
899
|
+
"""Copy file across storage boundaries (async)."""
|
|
900
|
+
from panpath.router import PanPath
|
|
901
|
+
src_path = PanPath(src, mode="async")
|
|
902
|
+
dst_path = PanPath(dst, mode="async")
|
|
903
|
+
|
|
904
|
+
# Handle symlinks
|
|
905
|
+
if not follow_symlinks and await src_path.is_symlink():
|
|
906
|
+
# Copy as symlink
|
|
907
|
+
target = await src_path.readlink()
|
|
908
|
+
await dst_path.symlink_to(str(target))
|
|
909
|
+
else:
|
|
910
|
+
# Read from source and write to destination
|
|
911
|
+
data = await src_path.read_bytes()
|
|
912
|
+
await dst_path.write_bytes(data)
|
|
913
|
+
|
|
914
|
+
@staticmethod
|
|
915
|
+
async def _copytree_cross_storage_async(src: str, dst: str, follow_symlinks: bool = True) -> None:
|
|
916
|
+
"""Copy directory tree across storage boundaries (async)."""
|
|
917
|
+
from panpath.router import PanPath
|
|
918
|
+
src_path = PanPath(src, mode="async")
|
|
919
|
+
dst_path = PanPath(dst, mode="async")
|
|
920
|
+
|
|
921
|
+
# Create destination directory
|
|
922
|
+
await dst_path.mkdir(parents=True, exist_ok=True)
|
|
923
|
+
|
|
924
|
+
# Walk source tree and copy all files
|
|
925
|
+
for dirpath, dirnames, filenames in await src_path.walk():
|
|
926
|
+
# Calculate relative path from src
|
|
927
|
+
rel_dir = dirpath[len(str(src)):].lstrip("/")
|
|
928
|
+
|
|
929
|
+
# Create subdirectories in destination
|
|
930
|
+
for dirname in dirnames:
|
|
931
|
+
dst_subdir = dst_path / rel_dir / dirname if rel_dir else dst_path / dirname
|
|
932
|
+
await dst_subdir.mkdir(parents=True, exist_ok=True)
|
|
933
|
+
|
|
934
|
+
# Copy files
|
|
935
|
+
for filename in filenames:
|
|
936
|
+
src_file = PanPath(dirpath, mode="async") / filename
|
|
937
|
+
dst_file = dst_path / rel_dir / filename if rel_dir else dst_path / filename
|
|
938
|
+
# Handle symlinks
|
|
939
|
+
if not follow_symlinks and await src_file.is_symlink():
|
|
940
|
+
# Copy as symlink
|
|
941
|
+
target = await src_file.readlink()
|
|
942
|
+
await dst_file.symlink_to(str(target))
|
|
943
|
+
else:
|
|
944
|
+
data = await src_file.read_bytes()
|
|
945
|
+
await dst_file.write_bytes(data)
|
|
946
|
+
|