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
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
"""Async S3 client implementation."""
|
|
2
|
+
from typing import Any, Optional
|
|
3
|
+
|
|
4
|
+
from panpath.clients import AsyncClient
|
|
5
|
+
from panpath.exceptions import MissingDependencyError, NoSuchFileError
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
import aioboto3
|
|
9
|
+
from botocore.exceptions import ClientError
|
|
10
|
+
|
|
11
|
+
HAS_AIOBOTO3 = True
|
|
12
|
+
except ImportError:
|
|
13
|
+
HAS_AIOBOTO3 = False
|
|
14
|
+
aioboto3 = None # type: ignore
|
|
15
|
+
ClientError = Exception # type: ignore
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AsyncS3Client(AsyncClient):
|
|
19
|
+
"""Asynchronous S3 client implementation using aioboto3."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, **kwargs: Any):
|
|
22
|
+
"""Initialize async S3 client.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
**kwargs: Additional arguments passed to aioboto3.Session
|
|
26
|
+
"""
|
|
27
|
+
if not HAS_AIOBOTO3:
|
|
28
|
+
raise MissingDependencyError(
|
|
29
|
+
backend="async S3",
|
|
30
|
+
package="aioboto3",
|
|
31
|
+
extra="async-s3",
|
|
32
|
+
)
|
|
33
|
+
self._session = aioboto3.Session(**kwargs)
|
|
34
|
+
|
|
35
|
+
def _parse_s3_path(self, path: str) -> tuple[str, str]:
|
|
36
|
+
"""Parse S3 path into bucket and key."""
|
|
37
|
+
if path.startswith("s3://"):
|
|
38
|
+
path = path[5:]
|
|
39
|
+
parts = path.split("/", 1)
|
|
40
|
+
bucket = parts[0]
|
|
41
|
+
key = parts[1] if len(parts) > 1 else ""
|
|
42
|
+
return bucket, key
|
|
43
|
+
|
|
44
|
+
async def exists(self, path: str) -> bool:
|
|
45
|
+
"""Check if S3 object exists."""
|
|
46
|
+
bucket, key = self._parse_s3_path(path)
|
|
47
|
+
async with self._session.client("s3") as client:
|
|
48
|
+
if not key:
|
|
49
|
+
try:
|
|
50
|
+
await client.head_bucket(Bucket=bucket)
|
|
51
|
+
return True
|
|
52
|
+
except ClientError:
|
|
53
|
+
return False
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
await client.head_object(Bucket=bucket, Key=key)
|
|
57
|
+
return True
|
|
58
|
+
except ClientError as e:
|
|
59
|
+
if e.response["Error"]["Code"] == "404":
|
|
60
|
+
return False
|
|
61
|
+
raise
|
|
62
|
+
|
|
63
|
+
async def read_bytes(self, path: str) -> bytes:
|
|
64
|
+
"""Read S3 object as bytes."""
|
|
65
|
+
bucket, key = self._parse_s3_path(path)
|
|
66
|
+
async with self._session.client("s3") as client:
|
|
67
|
+
try:
|
|
68
|
+
response = await client.get_object(Bucket=bucket, Key=key)
|
|
69
|
+
async with response["Body"] as stream:
|
|
70
|
+
return await stream.read()
|
|
71
|
+
except ClientError as e:
|
|
72
|
+
if e.response["Error"]["Code"] == "NoSuchKey":
|
|
73
|
+
raise NoSuchFileError(f"S3 object not found: {path}")
|
|
74
|
+
raise
|
|
75
|
+
|
|
76
|
+
async def read_text(self, path: str, encoding: str = "utf-8") -> str:
|
|
77
|
+
"""Read S3 object as text."""
|
|
78
|
+
data = await self.read_bytes(path)
|
|
79
|
+
return data.decode(encoding)
|
|
80
|
+
|
|
81
|
+
async def write_bytes(self, path: str, data: bytes) -> None:
|
|
82
|
+
"""Write bytes to S3 object."""
|
|
83
|
+
bucket, key = self._parse_s3_path(path)
|
|
84
|
+
async with self._session.client("s3") as client:
|
|
85
|
+
await client.put_object(Bucket=bucket, Key=key, Body=data)
|
|
86
|
+
|
|
87
|
+
async def write_text(self, path: str, data: str, encoding: str = "utf-8") -> None:
|
|
88
|
+
"""Write text to S3 object."""
|
|
89
|
+
await self.write_bytes(path, data.encode(encoding))
|
|
90
|
+
|
|
91
|
+
async def delete(self, path: str) -> None:
|
|
92
|
+
"""Delete S3 object."""
|
|
93
|
+
bucket, key = self._parse_s3_path(path)
|
|
94
|
+
async with self._session.client("s3") as client:
|
|
95
|
+
try:
|
|
96
|
+
await client.delete_object(Bucket=bucket, Key=key)
|
|
97
|
+
except ClientError as e:
|
|
98
|
+
if e.response["Error"]["Code"] == "NoSuchKey":
|
|
99
|
+
raise NoSuchFileError(f"S3 object not found: {path}")
|
|
100
|
+
raise
|
|
101
|
+
|
|
102
|
+
async def list_dir(self, path: str) -> list[str]:
|
|
103
|
+
"""List S3 objects with prefix."""
|
|
104
|
+
bucket, prefix = self._parse_s3_path(path)
|
|
105
|
+
if prefix and not prefix.endswith("/"):
|
|
106
|
+
prefix += "/"
|
|
107
|
+
|
|
108
|
+
results = []
|
|
109
|
+
async with self._session.client("s3") as client:
|
|
110
|
+
paginator = client.get_paginator("list_objects_v2")
|
|
111
|
+
async for page in paginator.paginate(Bucket=bucket, Prefix=prefix, Delimiter="/"):
|
|
112
|
+
# List "subdirectories"
|
|
113
|
+
for common_prefix in page.get("CommonPrefixes", []):
|
|
114
|
+
results.append(f"s3://{bucket}/{common_prefix['Prefix'].rstrip('/')}")
|
|
115
|
+
# List files
|
|
116
|
+
for obj in page.get("Contents", []):
|
|
117
|
+
key = obj["Key"]
|
|
118
|
+
if key != prefix:
|
|
119
|
+
results.append(f"s3://{bucket}/{key}")
|
|
120
|
+
return results
|
|
121
|
+
|
|
122
|
+
async def is_dir(self, path: str) -> bool:
|
|
123
|
+
"""Check if S3 path is a directory."""
|
|
124
|
+
bucket, key = self._parse_s3_path(path)
|
|
125
|
+
if not key:
|
|
126
|
+
return True
|
|
127
|
+
|
|
128
|
+
prefix = key if key.endswith("/") else key + "/"
|
|
129
|
+
async with self._session.client("s3") as client:
|
|
130
|
+
response = await client.list_objects_v2(Bucket=bucket, Prefix=prefix, MaxKeys=1)
|
|
131
|
+
return "Contents" in response or "CommonPrefixes" in response
|
|
132
|
+
|
|
133
|
+
async def is_file(self, path: str) -> bool:
|
|
134
|
+
"""Check if S3 path is a file."""
|
|
135
|
+
bucket, key = self._parse_s3_path(path)
|
|
136
|
+
if not key:
|
|
137
|
+
return False
|
|
138
|
+
|
|
139
|
+
async with self._session.client("s3") as client:
|
|
140
|
+
try:
|
|
141
|
+
await client.head_object(Bucket=bucket, Key=key)
|
|
142
|
+
return True
|
|
143
|
+
except ClientError:
|
|
144
|
+
return False
|
|
145
|
+
|
|
146
|
+
async def stat(self, path: str) -> Any:
|
|
147
|
+
"""Get S3 object metadata."""
|
|
148
|
+
bucket, key = self._parse_s3_path(path)
|
|
149
|
+
async with self._session.client("s3") as client:
|
|
150
|
+
try:
|
|
151
|
+
return await client.head_object(Bucket=bucket, Key=key)
|
|
152
|
+
except ClientError as e:
|
|
153
|
+
if e.response["Error"]["Code"] == "404":
|
|
154
|
+
raise NoSuchFileError(f"S3 object not found: {path}")
|
|
155
|
+
raise
|
|
156
|
+
|
|
157
|
+
async def open(
|
|
158
|
+
self,
|
|
159
|
+
path: str,
|
|
160
|
+
mode: str = "r",
|
|
161
|
+
encoding: Optional[str] = None,
|
|
162
|
+
**kwargs: Any,
|
|
163
|
+
) -> Any:
|
|
164
|
+
"""Open S3 object (returns async context manager for streaming)."""
|
|
165
|
+
# For async, we use aiofiles-like interface
|
|
166
|
+
# This is a simplified implementation - in practice, might want to use
|
|
167
|
+
# aioboto3's streaming capabilities more directly
|
|
168
|
+
if "r" in mode:
|
|
169
|
+
data = await self.read_bytes(path)
|
|
170
|
+
if "b" in mode:
|
|
171
|
+
from io import BytesIO
|
|
172
|
+
|
|
173
|
+
return BytesIO(data)
|
|
174
|
+
else:
|
|
175
|
+
from io import StringIO
|
|
176
|
+
|
|
177
|
+
text = data.decode(encoding or "utf-8")
|
|
178
|
+
return StringIO(text)
|
|
179
|
+
elif "w" in mode:
|
|
180
|
+
bucket, key = self._parse_s3_path(path)
|
|
181
|
+
|
|
182
|
+
class AsyncS3WriteBuffer:
|
|
183
|
+
def __init__(self, session: Any, bucket: str, key: str, binary: bool, enc: str):
|
|
184
|
+
self._session = session
|
|
185
|
+
self._bucket = bucket
|
|
186
|
+
self._key = key
|
|
187
|
+
self._binary = binary
|
|
188
|
+
self._encoding = enc
|
|
189
|
+
self._buffer = bytearray() if binary else []
|
|
190
|
+
|
|
191
|
+
async def write(self, data: Any) -> int:
|
|
192
|
+
if self._binary:
|
|
193
|
+
self._buffer.extend(data)
|
|
194
|
+
return len(data)
|
|
195
|
+
else:
|
|
196
|
+
self._buffer.append(data)
|
|
197
|
+
return len(data)
|
|
198
|
+
|
|
199
|
+
async def close(self) -> None:
|
|
200
|
+
if self._binary:
|
|
201
|
+
content = bytes(self._buffer)
|
|
202
|
+
else:
|
|
203
|
+
content = "".join(self._buffer).encode(self._encoding)
|
|
204
|
+
|
|
205
|
+
async with self._session.client("s3") as client:
|
|
206
|
+
await client.put_object(Bucket=self._bucket, Key=self._key, Body=content)
|
|
207
|
+
|
|
208
|
+
async def __aenter__(self) -> Any:
|
|
209
|
+
return self
|
|
210
|
+
|
|
211
|
+
async def __aexit__(self, *args: Any) -> None:
|
|
212
|
+
await self.close()
|
|
213
|
+
|
|
214
|
+
return AsyncS3WriteBuffer(self._session, bucket, key, "b" in mode, encoding or "utf-8")
|
|
215
|
+
else:
|
|
216
|
+
raise ValueError(f"Unsupported mode: {mode}")
|
|
217
|
+
|
|
218
|
+
async def mkdir(self, path: str, parents: bool = False, exist_ok: bool = False) -> None:
|
|
219
|
+
"""Create a directory marker (empty object with trailing slash).
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
path: S3 path (s3://bucket/path)
|
|
223
|
+
parents: If True, create parent directories as needed (ignored for S3)
|
|
224
|
+
exist_ok: If True, don't raise error if directory already exists
|
|
225
|
+
"""
|
|
226
|
+
bucket, key = self._parse_s3_path(path)
|
|
227
|
+
|
|
228
|
+
# Ensure key ends with / for directory marker
|
|
229
|
+
if key and not key.endswith('/'):
|
|
230
|
+
key += '/'
|
|
231
|
+
|
|
232
|
+
# Check if it already exists
|
|
233
|
+
async with self._session.client("s3") as client:
|
|
234
|
+
try:
|
|
235
|
+
await client.head_object(Bucket=bucket, Key=key)
|
|
236
|
+
if not exist_ok:
|
|
237
|
+
raise FileExistsError(f"Directory already exists: {path}")
|
|
238
|
+
return
|
|
239
|
+
except client.exceptions.NoSuchKey:
|
|
240
|
+
pass
|
|
241
|
+
|
|
242
|
+
# Create empty directory marker
|
|
243
|
+
await client.put_object(Bucket=bucket, Key=key, Body=b"")
|
|
244
|
+
|
|
245
|
+
async def get_metadata(self, path: str) -> dict[str, str]:
|
|
246
|
+
"""Get object metadata.
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
path: S3 path
|
|
250
|
+
|
|
251
|
+
Returns:
|
|
252
|
+
Dictionary of metadata key-value pairs
|
|
253
|
+
"""
|
|
254
|
+
bucket, key = self._parse_s3_path(path)
|
|
255
|
+
async with self._session.client("s3") as client:
|
|
256
|
+
try:
|
|
257
|
+
response = await client.head_object(Bucket=bucket, Key=key)
|
|
258
|
+
return response.get("Metadata", {})
|
|
259
|
+
except ClientError as e:
|
|
260
|
+
if e.response["Error"]["Code"] == "404":
|
|
261
|
+
raise NoSuchFileError(f"S3 object not found: {path}")
|
|
262
|
+
raise
|
|
263
|
+
|
|
264
|
+
async def set_metadata(self, path: str, metadata: dict[str, str]) -> None:
|
|
265
|
+
"""Set object metadata.
|
|
266
|
+
|
|
267
|
+
Args:
|
|
268
|
+
path: S3 path
|
|
269
|
+
metadata: Dictionary of metadata key-value pairs
|
|
270
|
+
"""
|
|
271
|
+
bucket, key = self._parse_s3_path(path)
|
|
272
|
+
|
|
273
|
+
async with self._session.client("s3") as client:
|
|
274
|
+
# S3 requires copying object to itself to update metadata
|
|
275
|
+
await client.copy_object(
|
|
276
|
+
Bucket=bucket,
|
|
277
|
+
Key=key,
|
|
278
|
+
CopySource={"Bucket": bucket, "Key": key},
|
|
279
|
+
Metadata=metadata,
|
|
280
|
+
MetadataDirective="REPLACE"
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
async def is_symlink(self, path: str) -> bool:
|
|
284
|
+
"""Check if object is a symlink (has symlink-target metadata).
|
|
285
|
+
|
|
286
|
+
Args:
|
|
287
|
+
path: S3 path
|
|
288
|
+
|
|
289
|
+
Returns:
|
|
290
|
+
True if symlink metadata exists
|
|
291
|
+
"""
|
|
292
|
+
try:
|
|
293
|
+
metadata = await self.get_metadata(path)
|
|
294
|
+
return "symlink-target" in metadata
|
|
295
|
+
except NoSuchFileError:
|
|
296
|
+
return False
|
|
297
|
+
|
|
298
|
+
async def readlink(self, path: str) -> str:
|
|
299
|
+
"""Read symlink target from metadata.
|
|
300
|
+
|
|
301
|
+
Args:
|
|
302
|
+
path: S3 path
|
|
303
|
+
|
|
304
|
+
Returns:
|
|
305
|
+
Symlink target path
|
|
306
|
+
"""
|
|
307
|
+
metadata = await self.get_metadata(path)
|
|
308
|
+
target = metadata.get("symlink-target")
|
|
309
|
+
if not target:
|
|
310
|
+
raise ValueError(f"Not a symlink: {path}")
|
|
311
|
+
return target
|
|
312
|
+
|
|
313
|
+
async def symlink_to(self, path: str, target: str) -> None:
|
|
314
|
+
"""Create symlink by storing target in metadata.
|
|
315
|
+
|
|
316
|
+
Args:
|
|
317
|
+
path: S3 path for the symlink
|
|
318
|
+
target: Target path the symlink should point to
|
|
319
|
+
"""
|
|
320
|
+
bucket, key = self._parse_s3_path(path)
|
|
321
|
+
|
|
322
|
+
async with self._session.client("s3") as client:
|
|
323
|
+
# Create empty object with symlink metadata
|
|
324
|
+
await client.put_object(
|
|
325
|
+
Bucket=bucket,
|
|
326
|
+
Key=key,
|
|
327
|
+
Body=b"",
|
|
328
|
+
Metadata={"symlink-target": target}
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
async def glob(self, path: str, pattern: str) -> list["Any"]:
|
|
332
|
+
"""Glob for files matching pattern.
|
|
333
|
+
|
|
334
|
+
Args:
|
|
335
|
+
path: Base S3 path
|
|
336
|
+
pattern: Glob pattern (e.g., "*.txt", "**/*.py")
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
List of matching AsyncCloudPath objects
|
|
340
|
+
"""
|
|
341
|
+
from fnmatch import fnmatch
|
|
342
|
+
from panpath.router import PanPath
|
|
343
|
+
|
|
344
|
+
bucket, prefix = self._parse_s3_path(path)
|
|
345
|
+
|
|
346
|
+
async with self._session.client("s3") as client:
|
|
347
|
+
# Handle recursive patterns
|
|
348
|
+
if "**" in pattern:
|
|
349
|
+
# Recursive search - list all objects under prefix
|
|
350
|
+
paginator = client.get_paginator("list_objects_v2")
|
|
351
|
+
pages = paginator.paginate(Bucket=bucket, Prefix=prefix)
|
|
352
|
+
|
|
353
|
+
# Extract the pattern part after **
|
|
354
|
+
pattern_parts = pattern.split("**/")
|
|
355
|
+
if len(pattern_parts) > 1:
|
|
356
|
+
file_pattern = pattern_parts[-1]
|
|
357
|
+
else:
|
|
358
|
+
file_pattern = "*"
|
|
359
|
+
|
|
360
|
+
results = []
|
|
361
|
+
async for page in pages:
|
|
362
|
+
for obj in page.get("Contents", []):
|
|
363
|
+
key = obj["Key"]
|
|
364
|
+
if fnmatch(key, f"*{file_pattern}"):
|
|
365
|
+
results.append(PanPath(f"s3://{bucket}/{key}", mode="async"))
|
|
366
|
+
return results
|
|
367
|
+
else:
|
|
368
|
+
# Non-recursive - list objects with delimiter
|
|
369
|
+
prefix_with_slash = f"{prefix}/" if prefix and not prefix.endswith("/") else prefix
|
|
370
|
+
response = await client.list_objects_v2(
|
|
371
|
+
Bucket=bucket,
|
|
372
|
+
Prefix=prefix_with_slash,
|
|
373
|
+
Delimiter="/"
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
results = []
|
|
377
|
+
for obj in response.get("Contents", []):
|
|
378
|
+
key = obj["Key"]
|
|
379
|
+
if fnmatch(key, f"{prefix_with_slash}{pattern}"):
|
|
380
|
+
results.append(PanPath(f"s3://{bucket}/{key}", mode="async"))
|
|
381
|
+
return results
|
|
382
|
+
|
|
383
|
+
async def walk(self, path: str) -> list[tuple[str, list[str], list[str]]]:
|
|
384
|
+
"""Walk directory tree.
|
|
385
|
+
|
|
386
|
+
Args:
|
|
387
|
+
path: Base S3 path
|
|
388
|
+
|
|
389
|
+
Returns:
|
|
390
|
+
List of (dirpath, dirnames, filenames) tuples
|
|
391
|
+
"""
|
|
392
|
+
bucket, prefix = self._parse_s3_path(path)
|
|
393
|
+
|
|
394
|
+
# List all objects under prefix
|
|
395
|
+
if prefix and not prefix.endswith("/"):
|
|
396
|
+
prefix += "/"
|
|
397
|
+
|
|
398
|
+
async with self._session.client("s3") as client:
|
|
399
|
+
paginator = client.get_paginator("list_objects_v2")
|
|
400
|
+
pages = paginator.paginate(Bucket=bucket, Prefix=prefix)
|
|
401
|
+
|
|
402
|
+
# Organize into directory structure
|
|
403
|
+
dirs: dict[str, tuple[set[str], set[str]]] = {} # dirpath -> (subdirs, files)
|
|
404
|
+
|
|
405
|
+
async for page in pages:
|
|
406
|
+
for obj in page.get("Contents", []):
|
|
407
|
+
key = obj["Key"]
|
|
408
|
+
# Get relative path from prefix
|
|
409
|
+
rel_path = key[len(prefix):] if prefix else key
|
|
410
|
+
|
|
411
|
+
# Split into directory and filename
|
|
412
|
+
parts = rel_path.split("/")
|
|
413
|
+
if len(parts) == 1:
|
|
414
|
+
# File in root
|
|
415
|
+
if path not in dirs:
|
|
416
|
+
dirs[path] = (set(), set())
|
|
417
|
+
if parts[0]: # Skip empty strings
|
|
418
|
+
dirs[path][1].add(parts[0])
|
|
419
|
+
else:
|
|
420
|
+
# File in subdirectory
|
|
421
|
+
for i in range(len(parts) - 1):
|
|
422
|
+
dir_path = f"{path}/" + "/".join(parts[:i+1]) if path else "/".join(parts[:i+1])
|
|
423
|
+
if dir_path not in dirs:
|
|
424
|
+
dirs[dir_path] = (set(), set())
|
|
425
|
+
|
|
426
|
+
# Add subdirectory if not last part
|
|
427
|
+
if i < len(parts) - 2:
|
|
428
|
+
dirs[dir_path][0].add(parts[i+1])
|
|
429
|
+
|
|
430
|
+
# Add file to its parent directory
|
|
431
|
+
parent_dir = f"{path}/" + "/".join(parts[:-1]) if path else "/".join(parts[:-1])
|
|
432
|
+
if parent_dir not in dirs:
|
|
433
|
+
dirs[parent_dir] = (set(), set())
|
|
434
|
+
if parts[-1]: # Skip empty strings
|
|
435
|
+
dirs[parent_dir][1].add(parts[-1])
|
|
436
|
+
|
|
437
|
+
# Convert to list of tuples
|
|
438
|
+
return [(d, sorted(subdirs), sorted(files)) for d, (subdirs, files) in sorted(dirs.items())]
|
|
439
|
+
|
|
440
|
+
async def touch(self, path: str, exist_ok: bool = True) -> None:
|
|
441
|
+
"""Create empty file.
|
|
442
|
+
|
|
443
|
+
Args:
|
|
444
|
+
path: S3 path
|
|
445
|
+
exist_ok: If False, raise error if file exists
|
|
446
|
+
"""
|
|
447
|
+
if not exist_ok and await self.exists(path):
|
|
448
|
+
raise FileExistsError(f"File already exists: {path}")
|
|
449
|
+
|
|
450
|
+
bucket, key = self._parse_s3_path(path)
|
|
451
|
+
async with self._session.client("s3") as client:
|
|
452
|
+
await client.put_object(Bucket=bucket, Key=key, Body=b"")
|
|
453
|
+
|
|
454
|
+
async def rename(self, source: str, target: str) -> None:
|
|
455
|
+
"""Rename/move file.
|
|
456
|
+
|
|
457
|
+
Args:
|
|
458
|
+
source: Source S3 path
|
|
459
|
+
target: Target S3 path
|
|
460
|
+
"""
|
|
461
|
+
# Copy to new location
|
|
462
|
+
src_bucket, src_key = self._parse_s3_path(source)
|
|
463
|
+
tgt_bucket, tgt_key = self._parse_s3_path(target)
|
|
464
|
+
|
|
465
|
+
async with self._session.client("s3") as client:
|
|
466
|
+
# Copy object
|
|
467
|
+
await client.copy_object(
|
|
468
|
+
Bucket=tgt_bucket,
|
|
469
|
+
Key=tgt_key,
|
|
470
|
+
CopySource={"Bucket": src_bucket, "Key": src_key}
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
# Delete source
|
|
474
|
+
await client.delete_object(Bucket=src_bucket, Key=src_key)
|
|
475
|
+
|
|
476
|
+
async def rmdir(self, path: str) -> None:
|
|
477
|
+
"""Remove directory marker.
|
|
478
|
+
|
|
479
|
+
Args:
|
|
480
|
+
path: S3 path
|
|
481
|
+
"""
|
|
482
|
+
bucket, key = self._parse_s3_path(path)
|
|
483
|
+
|
|
484
|
+
# Ensure key ends with / for directory marker
|
|
485
|
+
if key and not key.endswith('/'):
|
|
486
|
+
key += '/'
|
|
487
|
+
|
|
488
|
+
async with self._session.client("s3") as client:
|
|
489
|
+
try:
|
|
490
|
+
await client.delete_object(Bucket=bucket, Key=key)
|
|
491
|
+
except ClientError as e:
|
|
492
|
+
if e.response["Error"]["Code"] == "404":
|
|
493
|
+
raise NoSuchFileError(f"Directory not found: {path}")
|
|
494
|
+
raise
|
|
495
|
+
|
|
496
|
+
async def rmtree(self, path: str, ignore_errors: bool = False, onerror: Optional[Any] = None) -> None:
|
|
497
|
+
"""Remove directory and all its contents recursively.
|
|
498
|
+
|
|
499
|
+
Args:
|
|
500
|
+
path: S3 path
|
|
501
|
+
ignore_errors: If True, errors are ignored
|
|
502
|
+
onerror: Callable that accepts (function, path, excinfo)
|
|
503
|
+
"""
|
|
504
|
+
bucket, prefix = self._parse_s3_path(path)
|
|
505
|
+
|
|
506
|
+
# Ensure prefix ends with / for directory listing
|
|
507
|
+
if prefix and not prefix.endswith('/'):
|
|
508
|
+
prefix += '/'
|
|
509
|
+
|
|
510
|
+
try:
|
|
511
|
+
async with self._session.client("s3") as client:
|
|
512
|
+
# List all objects with this prefix
|
|
513
|
+
objects_to_delete = []
|
|
514
|
+
paginator = client.get_paginator('list_objects_v2')
|
|
515
|
+
async for page in paginator.paginate(Bucket=bucket, Prefix=prefix):
|
|
516
|
+
if 'Contents' in page:
|
|
517
|
+
objects_to_delete.extend([{'Key': obj['Key']} for obj in page['Contents']])
|
|
518
|
+
|
|
519
|
+
# Delete in batches (max 1000 per request)
|
|
520
|
+
if objects_to_delete:
|
|
521
|
+
for i in range(0, len(objects_to_delete), 1000):
|
|
522
|
+
batch = objects_to_delete[i:i+1000]
|
|
523
|
+
await client.delete_objects(
|
|
524
|
+
Bucket=bucket,
|
|
525
|
+
Delete={'Objects': batch}
|
|
526
|
+
)
|
|
527
|
+
except Exception as e:
|
|
528
|
+
if ignore_errors:
|
|
529
|
+
return
|
|
530
|
+
if onerror is not None:
|
|
531
|
+
import sys
|
|
532
|
+
onerror(client.delete_objects, path, sys.exc_info())
|
|
533
|
+
else:
|
|
534
|
+
raise
|
|
535
|
+
|
|
536
|
+
async def copy(self, source: str, target: str, follow_symlinks: bool = True) -> None:
|
|
537
|
+
"""Copy file to target.
|
|
538
|
+
|
|
539
|
+
Args:
|
|
540
|
+
source: Source S3 path
|
|
541
|
+
target: Target S3 path
|
|
542
|
+
follow_symlinks: If False, symlinks are copied as symlinks (not dereferenced)
|
|
543
|
+
"""
|
|
544
|
+
src_bucket, src_key = self._parse_s3_path(source)
|
|
545
|
+
tgt_bucket, tgt_key = self._parse_s3_path(target)
|
|
546
|
+
|
|
547
|
+
async with self._session.client("s3") as client:
|
|
548
|
+
# Use S3's native copy operation
|
|
549
|
+
await client.copy_object(
|
|
550
|
+
Bucket=tgt_bucket,
|
|
551
|
+
Key=tgt_key,
|
|
552
|
+
CopySource={"Bucket": src_bucket, "Key": src_key}
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
async def copytree(self, source: str, target: str, follow_symlinks: bool = True) -> None:
|
|
556
|
+
"""Copy directory tree to target recursively.
|
|
557
|
+
|
|
558
|
+
Args:
|
|
559
|
+
source: Source S3 path
|
|
560
|
+
target: Target S3 path
|
|
561
|
+
follow_symlinks: If False, symlinks are copied as symlinks (not dereferenced)
|
|
562
|
+
"""
|
|
563
|
+
src_bucket, src_prefix = self._parse_s3_path(source)
|
|
564
|
+
tgt_bucket, tgt_prefix = self._parse_s3_path(target)
|
|
565
|
+
|
|
566
|
+
# Ensure prefixes end with / for directory operations
|
|
567
|
+
if src_prefix and not src_prefix.endswith('/'):
|
|
568
|
+
src_prefix += '/'
|
|
569
|
+
if tgt_prefix and not tgt_prefix.endswith('/'):
|
|
570
|
+
tgt_prefix += '/'
|
|
571
|
+
|
|
572
|
+
async with self._session.client("s3") as client:
|
|
573
|
+
# List all objects with source prefix
|
|
574
|
+
paginator = client.get_paginator('list_objects_v2')
|
|
575
|
+
async for page in paginator.paginate(Bucket=src_bucket, Prefix=src_prefix):
|
|
576
|
+
if 'Contents' not in page:
|
|
577
|
+
continue
|
|
578
|
+
|
|
579
|
+
for obj in page['Contents']:
|
|
580
|
+
src_key = obj['Key']
|
|
581
|
+
# Calculate relative path and target key
|
|
582
|
+
rel_path = src_key[len(src_prefix):]
|
|
583
|
+
tgt_key = tgt_prefix + rel_path
|
|
584
|
+
|
|
585
|
+
# Copy object
|
|
586
|
+
await client.copy_object(
|
|
587
|
+
Bucket=tgt_bucket,
|
|
588
|
+
Key=tgt_key,
|
|
589
|
+
CopySource={"Bucket": src_bucket, "Key": src_key}
|
|
590
|
+
)
|