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