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