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