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