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/__init__.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""PanPath - Universal sync/async local/cloud path library.
|
|
2
|
+
|
|
3
|
+
Examples:
|
|
4
|
+
>>> from panpath import PanPath, AsyncPanPath
|
|
5
|
+
>>>
|
|
6
|
+
>>> # Sync local path
|
|
7
|
+
>>> path = PanPath("/path/to/file.txt")
|
|
8
|
+
>>> content = path.read_text()
|
|
9
|
+
>>>
|
|
10
|
+
>>> # Sync S3 path
|
|
11
|
+
>>> s3_path = PanPath("s3://bucket/key.txt")
|
|
12
|
+
>>> content = s3_path.read_text()
|
|
13
|
+
>>>
|
|
14
|
+
>>> # Async S3 path
|
|
15
|
+
>>> async_path = PanPath("s3://bucket/key.txt", mode="async")
|
|
16
|
+
>>> content = await async_path.read_text()
|
|
17
|
+
>>>
|
|
18
|
+
>>> # AsyncPanPath (always async)
|
|
19
|
+
>>> async_path = AsyncPanPath("s3://bucket/key.txt")
|
|
20
|
+
>>> content = await async_path.read_text()
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from panpath.router import AsyncPanPath, PanPath
|
|
24
|
+
from panpath.local_sync import LocalPath
|
|
25
|
+
from panpath.local_async import AsyncLocalPath
|
|
26
|
+
|
|
27
|
+
# Import path classes and register them
|
|
28
|
+
from panpath.registry import register_path_class
|
|
29
|
+
|
|
30
|
+
# Register S3
|
|
31
|
+
try:
|
|
32
|
+
from panpath.s3_sync import S3Path
|
|
33
|
+
from panpath.s3_async import AsyncS3Path
|
|
34
|
+
|
|
35
|
+
register_path_class("s3", S3Path, AsyncS3Path)
|
|
36
|
+
except ImportError:
|
|
37
|
+
# S3 dependencies not installed
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
# Register Google Cloud Storage
|
|
41
|
+
try:
|
|
42
|
+
from panpath.gs_sync import GSPath
|
|
43
|
+
from panpath.gs_async import AsyncGSPath
|
|
44
|
+
|
|
45
|
+
register_path_class("gs", GSPath, AsyncGSPath)
|
|
46
|
+
except ImportError:
|
|
47
|
+
# GCS dependencies not installed
|
|
48
|
+
pass
|
|
49
|
+
|
|
50
|
+
# Register Azure Blob Storage
|
|
51
|
+
try:
|
|
52
|
+
from panpath.azure_sync import AzureBlobPath
|
|
53
|
+
from panpath.azure_async import AsyncAzureBlobPath
|
|
54
|
+
|
|
55
|
+
register_path_class("az", AzureBlobPath, AsyncAzureBlobPath)
|
|
56
|
+
register_path_class("azure", AzureBlobPath, AsyncAzureBlobPath) # Support both schemes
|
|
57
|
+
except ImportError:
|
|
58
|
+
# Azure dependencies not installed
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
__version__ = "0.1.0"
|
|
62
|
+
|
|
63
|
+
__all__ = [
|
|
64
|
+
"PanPath",
|
|
65
|
+
"AsyncPanPath",
|
|
66
|
+
"LocalPath",
|
|
67
|
+
"AsyncLocalPath",
|
|
68
|
+
# Export cloud paths if available
|
|
69
|
+
# Users can import specific classes if needed
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
# Add cloud path classes to __all__ if they're available
|
|
73
|
+
try:
|
|
74
|
+
__all__.extend(["S3Path", "AsyncS3Path"])
|
|
75
|
+
except NameError:
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
__all__.extend(["GSPath", "AsyncGSPath"])
|
|
80
|
+
except NameError:
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
__all__.extend(["AzureBlobPath", "AsyncAzureBlobPath"])
|
|
85
|
+
except NameError:
|
|
86
|
+
pass
|
panpath/azure_async.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Async Azure Blob Storage path implementation."""
|
|
2
|
+
from typing import TYPE_CHECKING, Optional
|
|
3
|
+
|
|
4
|
+
from panpath.base import AsyncCloudPath
|
|
5
|
+
from panpath.azure_async_client import AsyncAzureBlobClient
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from panpath.clients import AsyncClient
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AsyncAzureBlobPath(AsyncCloudPath):
|
|
12
|
+
"""Asynchronous Azure Blob Storage path implementation."""
|
|
13
|
+
|
|
14
|
+
_client: Optional[AsyncAzureBlobClient] = None
|
|
15
|
+
_default_client: Optional[AsyncAzureBlobClient] = None
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def _create_default_client(cls) -> "AsyncClient":
|
|
19
|
+
"""Create default async Azure Blob client."""
|
|
20
|
+
return AsyncAzureBlobClient()
|
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
"""Async Azure Blob 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 azure.storage.blob.aio import BlobServiceClient
|
|
9
|
+
from azure.core.exceptions import ResourceNotFoundError
|
|
10
|
+
|
|
11
|
+
HAS_AZURE_AIO = True
|
|
12
|
+
except ImportError:
|
|
13
|
+
HAS_AZURE_AIO = False
|
|
14
|
+
BlobServiceClient = None # type: ignore
|
|
15
|
+
ResourceNotFoundError = Exception # type: ignore
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AsyncAzureBlobClient(AsyncClient):
|
|
19
|
+
"""Asynchronous Azure Blob Storage client implementation."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, connection_string: Optional[str] = None, **kwargs: Any):
|
|
22
|
+
"""Initialize async Azure Blob client.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
connection_string: Azure storage connection string
|
|
26
|
+
**kwargs: Additional arguments
|
|
27
|
+
"""
|
|
28
|
+
if not HAS_AZURE_AIO:
|
|
29
|
+
raise MissingDependencyError(
|
|
30
|
+
backend="async Azure Blob Storage",
|
|
31
|
+
package="azure-storage-blob[aio]",
|
|
32
|
+
extra="async-azure",
|
|
33
|
+
)
|
|
34
|
+
if connection_string:
|
|
35
|
+
self._client = BlobServiceClient.from_connection_string(connection_string, **kwargs)
|
|
36
|
+
else:
|
|
37
|
+
self._client = BlobServiceClient(**kwargs)
|
|
38
|
+
|
|
39
|
+
def _parse_azure_path(self, path: str) -> tuple[str, str]:
|
|
40
|
+
"""Parse Azure path into container and blob name."""
|
|
41
|
+
if path.startswith("az://"):
|
|
42
|
+
path = path[5:]
|
|
43
|
+
elif path.startswith("azure://"):
|
|
44
|
+
path = path[8:]
|
|
45
|
+
|
|
46
|
+
parts = path.split("/", 1)
|
|
47
|
+
container = parts[0]
|
|
48
|
+
blob = parts[1] if len(parts) > 1 else ""
|
|
49
|
+
return container, blob
|
|
50
|
+
|
|
51
|
+
async def exists(self, path: str) -> bool:
|
|
52
|
+
"""Check if Azure blob exists."""
|
|
53
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
54
|
+
if not blob_name:
|
|
55
|
+
try:
|
|
56
|
+
container_client = self._client.get_container_client(container_name)
|
|
57
|
+
return await container_client.exists()
|
|
58
|
+
except Exception:
|
|
59
|
+
return False
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
63
|
+
return await blob_client.exists()
|
|
64
|
+
except Exception:
|
|
65
|
+
return False
|
|
66
|
+
|
|
67
|
+
async def read_bytes(self, path: str) -> bytes:
|
|
68
|
+
"""Read Azure blob as bytes."""
|
|
69
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
70
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
download_stream = await blob_client.download_blob()
|
|
74
|
+
return await download_stream.readall()
|
|
75
|
+
except ResourceNotFoundError:
|
|
76
|
+
raise NoSuchFileError(f"Azure blob not found: {path}")
|
|
77
|
+
|
|
78
|
+
async def read_text(self, path: str, encoding: str = "utf-8") -> str:
|
|
79
|
+
"""Read Azure blob as text."""
|
|
80
|
+
data = await self.read_bytes(path)
|
|
81
|
+
return data.decode(encoding)
|
|
82
|
+
|
|
83
|
+
async def write_bytes(self, path: str, data: bytes) -> None:
|
|
84
|
+
"""Write bytes to Azure blob."""
|
|
85
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
86
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
87
|
+
await blob_client.upload_blob(data, overwrite=True)
|
|
88
|
+
|
|
89
|
+
async def write_text(self, path: str, data: str, encoding: str = "utf-8") -> None:
|
|
90
|
+
"""Write text to Azure blob."""
|
|
91
|
+
await self.write_bytes(path, data.encode(encoding))
|
|
92
|
+
|
|
93
|
+
async def delete(self, path: str) -> None:
|
|
94
|
+
"""Delete Azure blob."""
|
|
95
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
96
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
await blob_client.delete_blob()
|
|
100
|
+
except ResourceNotFoundError:
|
|
101
|
+
raise NoSuchFileError(f"Azure blob not found: {path}")
|
|
102
|
+
|
|
103
|
+
async def list_dir(self, path: str) -> list[str]:
|
|
104
|
+
"""List Azure blobs with prefix."""
|
|
105
|
+
container_name, prefix = self._parse_azure_path(path)
|
|
106
|
+
if prefix and not prefix.endswith("/"):
|
|
107
|
+
prefix += "/"
|
|
108
|
+
|
|
109
|
+
container_client = self._client.get_container_client(container_name)
|
|
110
|
+
results = []
|
|
111
|
+
|
|
112
|
+
async for item in container_client.walk_blobs(name_starts_with=prefix, delimiter="/"):
|
|
113
|
+
if hasattr(item, "name"):
|
|
114
|
+
# BlobProperties (file)
|
|
115
|
+
if item.name != prefix:
|
|
116
|
+
results.append(f"az://{container_name}/{item.name}")
|
|
117
|
+
else:
|
|
118
|
+
# BlobPrefix (directory)
|
|
119
|
+
results.append(f"az://{container_name}/{item.prefix.rstrip('/')}")
|
|
120
|
+
|
|
121
|
+
return results
|
|
122
|
+
|
|
123
|
+
async def is_dir(self, path: str) -> bool:
|
|
124
|
+
"""Check if Azure path is a directory."""
|
|
125
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
126
|
+
if not blob_name:
|
|
127
|
+
return True
|
|
128
|
+
|
|
129
|
+
prefix = blob_name if blob_name.endswith("/") else blob_name + "/"
|
|
130
|
+
container_client = self._client.get_container_client(container_name)
|
|
131
|
+
|
|
132
|
+
async for _ in container_client.list_blobs(name_starts_with=prefix, max_results=1):
|
|
133
|
+
return True
|
|
134
|
+
return False
|
|
135
|
+
|
|
136
|
+
async def is_file(self, path: str) -> bool:
|
|
137
|
+
"""Check if Azure path is a file."""
|
|
138
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
139
|
+
if not blob_name:
|
|
140
|
+
return False
|
|
141
|
+
|
|
142
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
143
|
+
return await blob_client.exists()
|
|
144
|
+
|
|
145
|
+
async def stat(self, path: str) -> Any:
|
|
146
|
+
"""Get Azure blob metadata."""
|
|
147
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
148
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
149
|
+
|
|
150
|
+
try:
|
|
151
|
+
return await blob_client.get_blob_properties()
|
|
152
|
+
except ResourceNotFoundError:
|
|
153
|
+
raise NoSuchFileError(f"Azure blob not found: {path}")
|
|
154
|
+
|
|
155
|
+
async def open(
|
|
156
|
+
self,
|
|
157
|
+
path: str,
|
|
158
|
+
mode: str = "r",
|
|
159
|
+
encoding: Optional[str] = None,
|
|
160
|
+
**kwargs: Any,
|
|
161
|
+
) -> Any:
|
|
162
|
+
"""Open Azure blob for reading/writing."""
|
|
163
|
+
if "r" in mode:
|
|
164
|
+
data = await self.read_bytes(path)
|
|
165
|
+
if "b" in mode:
|
|
166
|
+
from io import BytesIO
|
|
167
|
+
|
|
168
|
+
return BytesIO(data)
|
|
169
|
+
else:
|
|
170
|
+
from io import StringIO
|
|
171
|
+
|
|
172
|
+
text = data.decode(encoding or "utf-8")
|
|
173
|
+
return StringIO(text)
|
|
174
|
+
elif "w" in mode:
|
|
175
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
176
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
177
|
+
|
|
178
|
+
class AsyncAzureWriteBuffer:
|
|
179
|
+
def __init__(self, blob_client: Any, binary: bool, enc: str):
|
|
180
|
+
self._blob_client = blob_client
|
|
181
|
+
self._binary = binary
|
|
182
|
+
self._encoding = enc
|
|
183
|
+
self._buffer = bytearray() if binary else []
|
|
184
|
+
|
|
185
|
+
async def write(self, data: Any) -> int:
|
|
186
|
+
if self._binary:
|
|
187
|
+
self._buffer.extend(data)
|
|
188
|
+
return len(data)
|
|
189
|
+
else:
|
|
190
|
+
self._buffer.append(data)
|
|
191
|
+
return len(data)
|
|
192
|
+
|
|
193
|
+
async def close(self) -> None:
|
|
194
|
+
if self._binary:
|
|
195
|
+
content = bytes(self._buffer)
|
|
196
|
+
else:
|
|
197
|
+
content = "".join(self._buffer).encode(self._encoding)
|
|
198
|
+
|
|
199
|
+
await self._blob_client.upload_blob(content, overwrite=True)
|
|
200
|
+
|
|
201
|
+
async def __aenter__(self) -> Any:
|
|
202
|
+
return self
|
|
203
|
+
|
|
204
|
+
async def __aexit__(self, *args: Any) -> None:
|
|
205
|
+
await self.close()
|
|
206
|
+
|
|
207
|
+
return AsyncAzureWriteBuffer(blob_client, "b" in mode, encoding or "utf-8")
|
|
208
|
+
else:
|
|
209
|
+
raise ValueError(f"Unsupported mode: {mode}")
|
|
210
|
+
|
|
211
|
+
async def mkdir(self, path: str, parents: bool = False, exist_ok: bool = False) -> None:
|
|
212
|
+
"""Create a directory marker (empty blob with trailing slash).
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
path: Azure path (az://container/path or azure://container/path)
|
|
216
|
+
parents: If True, create parent directories as needed (ignored for Azure)
|
|
217
|
+
exist_ok: If True, don't raise error if directory already exists
|
|
218
|
+
"""
|
|
219
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
220
|
+
|
|
221
|
+
# Ensure blob_name ends with / for directory marker
|
|
222
|
+
if blob_name and not blob_name.endswith('/'):
|
|
223
|
+
blob_name += '/'
|
|
224
|
+
|
|
225
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
226
|
+
|
|
227
|
+
# Check if it already exists
|
|
228
|
+
if await blob_client.exists():
|
|
229
|
+
if not exist_ok:
|
|
230
|
+
raise FileExistsError(f"Directory already exists: {path}")
|
|
231
|
+
return
|
|
232
|
+
|
|
233
|
+
# Create empty directory marker
|
|
234
|
+
await blob_client.upload_blob(b"", overwrite=False)
|
|
235
|
+
|
|
236
|
+
async def get_metadata(self, path: str) -> dict[str, str]:
|
|
237
|
+
"""Get blob metadata.
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
path: Azure path
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
Dictionary of metadata key-value pairs
|
|
244
|
+
"""
|
|
245
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
246
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
247
|
+
try:
|
|
248
|
+
properties = await blob_client.get_blob_properties()
|
|
249
|
+
return properties.metadata or {}
|
|
250
|
+
except ResourceNotFoundError:
|
|
251
|
+
raise NoSuchFileError(f"Azure blob not found: {path}")
|
|
252
|
+
|
|
253
|
+
async def set_metadata(self, path: str, metadata: dict[str, str]) -> None:
|
|
254
|
+
"""Set blob metadata.
|
|
255
|
+
|
|
256
|
+
Args:
|
|
257
|
+
path: Azure path
|
|
258
|
+
metadata: Dictionary of metadata key-value pairs
|
|
259
|
+
"""
|
|
260
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
261
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
262
|
+
await blob_client.set_blob_metadata(metadata)
|
|
263
|
+
|
|
264
|
+
async def is_symlink(self, path: str) -> bool:
|
|
265
|
+
"""Check if blob is a symlink (has symlink_target metadata).
|
|
266
|
+
|
|
267
|
+
Args:
|
|
268
|
+
path: Azure path
|
|
269
|
+
|
|
270
|
+
Returns:
|
|
271
|
+
True if symlink metadata exists
|
|
272
|
+
"""
|
|
273
|
+
try:
|
|
274
|
+
metadata = await self.get_metadata(path)
|
|
275
|
+
return "symlink_target" in metadata
|
|
276
|
+
except NoSuchFileError:
|
|
277
|
+
return False
|
|
278
|
+
|
|
279
|
+
async def readlink(self, path: str) -> str:
|
|
280
|
+
"""Read symlink target from metadata.
|
|
281
|
+
|
|
282
|
+
Args:
|
|
283
|
+
path: Azure path
|
|
284
|
+
|
|
285
|
+
Returns:
|
|
286
|
+
Symlink target path
|
|
287
|
+
"""
|
|
288
|
+
metadata = await self.get_metadata(path)
|
|
289
|
+
target = metadata.get("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: Azure path for the symlink
|
|
299
|
+
target: Target path the symlink should point to
|
|
300
|
+
"""
|
|
301
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
302
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
303
|
+
|
|
304
|
+
# Create empty blob
|
|
305
|
+
await blob_client.upload_blob(b"", overwrite=True)
|
|
306
|
+
|
|
307
|
+
# Set symlink metadata
|
|
308
|
+
await blob_client.set_blob_metadata({"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 Azure 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
|
+
container_name, blob_prefix = self._parse_azure_path(path)
|
|
324
|
+
container_client = self._client.get_container_client(container_name)
|
|
325
|
+
|
|
326
|
+
# Handle recursive patterns
|
|
327
|
+
if "**" in pattern:
|
|
328
|
+
# Recursive search - list all blobs under prefix
|
|
329
|
+
blobs = []
|
|
330
|
+
async for blob in container_client.list_blobs(name_starts_with=blob_prefix):
|
|
331
|
+
blobs.append(blob)
|
|
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 blob in blobs:
|
|
342
|
+
if fnmatch(blob.name, f"*{file_pattern}"):
|
|
343
|
+
# Determine scheme from original path
|
|
344
|
+
scheme = "az" if path.startswith("az://") else "azure"
|
|
345
|
+
results.append(PanPath(f"{scheme}://{container_name}/{blob.name}", mode="async"))
|
|
346
|
+
return results
|
|
347
|
+
else:
|
|
348
|
+
# Non-recursive - list blobs with prefix
|
|
349
|
+
prefix_with_slash = f"{blob_prefix}/" if blob_prefix and not blob_prefix.endswith("/") else blob_prefix
|
|
350
|
+
blobs = []
|
|
351
|
+
async for blob in container_client.list_blobs(name_starts_with=prefix_with_slash):
|
|
352
|
+
blobs.append(blob)
|
|
353
|
+
|
|
354
|
+
results = []
|
|
355
|
+
for blob in blobs:
|
|
356
|
+
# Only include direct children (no additional slashes)
|
|
357
|
+
rel_name = blob.name[len(prefix_with_slash):]
|
|
358
|
+
if "/" not in rel_name and fnmatch(blob.name, f"{prefix_with_slash}{pattern}"):
|
|
359
|
+
scheme = "az" if path.startswith("az://") else "azure"
|
|
360
|
+
results.append(PanPath(f"{scheme}://{container_name}/{blob.name}", mode="async"))
|
|
361
|
+
return results
|
|
362
|
+
|
|
363
|
+
async def walk(self, path: str) -> list[tuple[str, list[str], list[str]]]:
|
|
364
|
+
"""Walk directory tree.
|
|
365
|
+
|
|
366
|
+
Args:
|
|
367
|
+
path: Base Azure path
|
|
368
|
+
|
|
369
|
+
Returns:
|
|
370
|
+
List of (dirpath, dirnames, filenames) tuples
|
|
371
|
+
"""
|
|
372
|
+
container_name, blob_prefix = self._parse_azure_path(path)
|
|
373
|
+
container_client = self._client.get_container_client(container_name)
|
|
374
|
+
|
|
375
|
+
# List all blobs under prefix
|
|
376
|
+
prefix = blob_prefix if blob_prefix else ""
|
|
377
|
+
if prefix and not prefix.endswith("/"):
|
|
378
|
+
prefix += "/"
|
|
379
|
+
|
|
380
|
+
blobs = []
|
|
381
|
+
async for blob in container_client.list_blobs(name_starts_with=prefix):
|
|
382
|
+
blobs.append(blob)
|
|
383
|
+
|
|
384
|
+
# Organize into directory structure
|
|
385
|
+
dirs: dict[str, tuple[set[str], set[str]]] = {} # dirpath -> (subdirs, files)
|
|
386
|
+
|
|
387
|
+
for blob in blobs:
|
|
388
|
+
# Get relative path from prefix
|
|
389
|
+
rel_path = blob.name[len(prefix):] if prefix else blob.name
|
|
390
|
+
|
|
391
|
+
# Split into directory and filename
|
|
392
|
+
parts = rel_path.split("/")
|
|
393
|
+
if len(parts) == 1:
|
|
394
|
+
# File in root
|
|
395
|
+
if path not in dirs:
|
|
396
|
+
dirs[path] = (set(), set())
|
|
397
|
+
if parts[0]: # Skip empty strings
|
|
398
|
+
dirs[path][1].add(parts[0])
|
|
399
|
+
else:
|
|
400
|
+
# File in subdirectory
|
|
401
|
+
for i in range(len(parts) - 1):
|
|
402
|
+
dir_path = f"{path}/" + "/".join(parts[:i+1]) if path else "/".join(parts[:i+1])
|
|
403
|
+
if dir_path not in dirs:
|
|
404
|
+
dirs[dir_path] = (set(), set())
|
|
405
|
+
|
|
406
|
+
# Add subdirectory if not last part
|
|
407
|
+
if i < len(parts) - 2:
|
|
408
|
+
dirs[dir_path][0].add(parts[i+1])
|
|
409
|
+
|
|
410
|
+
# Add file to its parent directory
|
|
411
|
+
parent_dir = f"{path}/" + "/".join(parts[:-1]) if path else "/".join(parts[:-1])
|
|
412
|
+
if parent_dir not in dirs:
|
|
413
|
+
dirs[parent_dir] = (set(), set())
|
|
414
|
+
if parts[-1]: # Skip empty strings
|
|
415
|
+
dirs[parent_dir][1].add(parts[-1])
|
|
416
|
+
|
|
417
|
+
# Convert to list of tuples
|
|
418
|
+
return [(d, sorted(subdirs), sorted(files)) for d, (subdirs, files) in sorted(dirs.items())]
|
|
419
|
+
|
|
420
|
+
async def touch(self, path: str, exist_ok: bool = True) -> None:
|
|
421
|
+
"""Create empty file.
|
|
422
|
+
|
|
423
|
+
Args:
|
|
424
|
+
path: Azure path
|
|
425
|
+
exist_ok: If False, raise error if file exists
|
|
426
|
+
"""
|
|
427
|
+
if not exist_ok and await self.exists(path):
|
|
428
|
+
raise FileExistsError(f"File already exists: {path}")
|
|
429
|
+
|
|
430
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
431
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
432
|
+
await blob_client.upload_blob(b"", overwrite=True)
|
|
433
|
+
|
|
434
|
+
async def rename(self, source: str, target: str) -> None:
|
|
435
|
+
"""Rename/move file.
|
|
436
|
+
|
|
437
|
+
Args:
|
|
438
|
+
source: Source Azure path
|
|
439
|
+
target: Target Azure path
|
|
440
|
+
"""
|
|
441
|
+
# Copy to new location
|
|
442
|
+
src_container, src_blob = self._parse_azure_path(source)
|
|
443
|
+
tgt_container, tgt_blob = self._parse_azure_path(target)
|
|
444
|
+
|
|
445
|
+
src_blob_client = self._client.get_blob_client(src_container, src_blob)
|
|
446
|
+
tgt_blob_client = self._client.get_blob_client(tgt_container, tgt_blob)
|
|
447
|
+
|
|
448
|
+
# Copy blob
|
|
449
|
+
await tgt_blob_client.start_copy_from_url(src_blob_client.url)
|
|
450
|
+
|
|
451
|
+
# Delete source
|
|
452
|
+
await src_blob_client.delete_blob()
|
|
453
|
+
|
|
454
|
+
async def rmdir(self, path: str) -> None:
|
|
455
|
+
"""Remove directory marker.
|
|
456
|
+
|
|
457
|
+
Args:
|
|
458
|
+
path: Azure path
|
|
459
|
+
"""
|
|
460
|
+
container_name, blob_name = self._parse_azure_path(path)
|
|
461
|
+
|
|
462
|
+
# Ensure blob_name ends with / for directory marker
|
|
463
|
+
if blob_name and not blob_name.endswith('/'):
|
|
464
|
+
blob_name += '/'
|
|
465
|
+
|
|
466
|
+
blob_client = self._client.get_blob_client(container_name, blob_name)
|
|
467
|
+
|
|
468
|
+
try:
|
|
469
|
+
await blob_client.delete_blob()
|
|
470
|
+
except ResourceNotFoundError:
|
|
471
|
+
raise NoSuchFileError(f"Directory not found: {path}")
|
|
472
|
+
|
|
473
|
+
async def rmtree(self, path: str, ignore_errors: bool = False, onerror: Optional[Any] = None) -> None:
|
|
474
|
+
"""Remove directory and all its contents recursively.
|
|
475
|
+
|
|
476
|
+
Args:
|
|
477
|
+
path: Azure path
|
|
478
|
+
ignore_errors: If True, errors are ignored
|
|
479
|
+
onerror: Callable that accepts (function, path, excinfo)
|
|
480
|
+
"""
|
|
481
|
+
container_name, prefix = self._parse_azure_path(path)
|
|
482
|
+
|
|
483
|
+
# Ensure prefix ends with / for directory listing
|
|
484
|
+
if prefix and not prefix.endswith('/'):
|
|
485
|
+
prefix += '/'
|
|
486
|
+
|
|
487
|
+
try:
|
|
488
|
+
container_client = self._client.get_container_client(container_name)
|
|
489
|
+
|
|
490
|
+
# List and delete all blobs with this prefix
|
|
491
|
+
async for blob in container_client.list_blobs(name_starts_with=prefix):
|
|
492
|
+
blob_client = self._client.get_blob_client(container_name, blob.name)
|
|
493
|
+
await blob_client.delete_blob()
|
|
494
|
+
except Exception as e:
|
|
495
|
+
if ignore_errors:
|
|
496
|
+
return
|
|
497
|
+
if onerror is not None:
|
|
498
|
+
import sys
|
|
499
|
+
onerror(blob_client.delete_blob, 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 Azure path
|
|
508
|
+
target: Target Azure path
|
|
509
|
+
follow_symlinks: If False, symlinks are copied as symlinks (not dereferenced)
|
|
510
|
+
"""
|
|
511
|
+
src_container_name, src_blob_name = self._parse_azure_path(source)
|
|
512
|
+
tgt_container_name, tgt_blob_name = self._parse_azure_path(target)
|
|
513
|
+
|
|
514
|
+
src_blob_client = self._client.get_blob_client(src_container_name, src_blob_name)
|
|
515
|
+
tgt_blob_client = self._client.get_blob_client(tgt_container_name, tgt_blob_name)
|
|
516
|
+
|
|
517
|
+
# Use Azure's copy operation
|
|
518
|
+
source_url = src_blob_client.url
|
|
519
|
+
await tgt_blob_client.start_copy_from_url(source_url)
|
|
520
|
+
|
|
521
|
+
async def copytree(self, source: str, target: str, follow_symlinks: bool = True) -> None:
|
|
522
|
+
"""Copy directory tree to target recursively.
|
|
523
|
+
|
|
524
|
+
Args:
|
|
525
|
+
source: Source Azure path
|
|
526
|
+
target: Target Azure path
|
|
527
|
+
follow_symlinks: If False, symlinks are copied as symlinks (not dereferenced)
|
|
528
|
+
"""
|
|
529
|
+
src_container_name, src_prefix = self._parse_azure_path(source)
|
|
530
|
+
tgt_container_name, tgt_prefix = self._parse_azure_path(target)
|
|
531
|
+
|
|
532
|
+
# Ensure prefixes end with / for directory operations
|
|
533
|
+
if src_prefix and not src_prefix.endswith('/'):
|
|
534
|
+
src_prefix += '/'
|
|
535
|
+
if tgt_prefix and not tgt_prefix.endswith('/'):
|
|
536
|
+
tgt_prefix += '/'
|
|
537
|
+
|
|
538
|
+
src_container_client = self._client.get_container_client(src_container_name)
|
|
539
|
+
|
|
540
|
+
# List all blobs with source prefix
|
|
541
|
+
async for blob in src_container_client.list_blobs(name_starts_with=src_prefix):
|
|
542
|
+
src_blob_name = blob.name
|
|
543
|
+
# Calculate relative path and target blob name
|
|
544
|
+
rel_path = src_blob_name[len(src_prefix):]
|
|
545
|
+
tgt_blob_name = tgt_prefix + rel_path
|
|
546
|
+
|
|
547
|
+
# Copy blob
|
|
548
|
+
src_blob_client = self._client.get_blob_client(src_container_name, src_blob_name)
|
|
549
|
+
tgt_blob_client = self._client.get_blob_client(tgt_container_name, tgt_blob_name)
|
|
550
|
+
source_url = src_blob_client.url
|
|
551
|
+
await tgt_blob_client.start_copy_from_url(source_url)
|