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/local_sync.py ADDED
@@ -0,0 +1,29 @@
1
+ """Synchronous local path implementation."""
2
+ from pathlib import Path, PosixPath, WindowsPath
3
+ import os
4
+
5
+
6
+ # Determine the concrete Path class based on OS
7
+ if os.name == "nt":
8
+ _ConcretePath = WindowsPath
9
+ else:
10
+ _ConcretePath = PosixPath
11
+
12
+
13
+ class LocalPath(_ConcretePath): # type: ignore
14
+ """Local filesystem path (drop-in replacement for pathlib.Path).
15
+
16
+ Inherits from the concrete PosixPath or WindowsPath for full compatibility.
17
+ """
18
+
19
+ def __eq__(self, other): # type: ignore
20
+ """Check equality - sync paths never equal async paths."""
21
+ from panpath.local_async import AsyncLocalPath
22
+
23
+ if isinstance(other, AsyncLocalPath):
24
+ return False
25
+ return super().__eq__(other)
26
+
27
+ def __hash__(self) -> int:
28
+ """Return hash of path."""
29
+ return super().__hash__()
panpath/py.typed ADDED
File without changes
panpath/registry.py ADDED
@@ -0,0 +1,71 @@
1
+ """Registry for path class implementations."""
2
+ from typing import TYPE_CHECKING, Any, Dict, Tuple, Type
3
+
4
+ if TYPE_CHECKING:
5
+ from panpath.base import CloudPath, AsyncCloudPath
6
+
7
+
8
+ # Registry mapping URI schemes to (sync_class, async_class) tuples
9
+ _REGISTRY: Dict[str, Tuple[Type["CloudPath"], Type["AsyncCloudPath"]]] = {}
10
+
11
+
12
+ def register_path_class(
13
+ scheme: str,
14
+ sync_class: Type["CloudPath"],
15
+ async_class: Type["AsyncCloudPath"],
16
+ ) -> None:
17
+ """Register a path class implementation for a URI scheme.
18
+
19
+ Args:
20
+ scheme: URI scheme (e.g., 's3', 'gs', 'az')
21
+ sync_class: Synchronous path class
22
+ async_class: Asynchronous path class
23
+ """
24
+ _REGISTRY[scheme] = (sync_class, async_class)
25
+
26
+
27
+ def get_path_class(scheme: str, is_async: bool = False) -> Type[Any]:
28
+ """Get the path class for a URI scheme and mode.
29
+
30
+ Args:
31
+ scheme: URI scheme (e.g., 's3', 'gs', 'az')
32
+ is_async: Whether to return async class
33
+
34
+ Returns:
35
+ Path class for the scheme and mode
36
+
37
+ Raises:
38
+ KeyError: If scheme is not registered
39
+ """
40
+ sync_class, async_class = _REGISTRY[scheme]
41
+ return async_class if is_async else sync_class
42
+
43
+
44
+ def get_registered_schemes() -> list[str]:
45
+ """Get all registered URI schemes."""
46
+ return list(_REGISTRY.keys())
47
+
48
+
49
+ def clear_registry() -> None:
50
+ """Clear the registry (mainly for testing)."""
51
+ _REGISTRY.clear()
52
+
53
+
54
+ def swap_implementation(
55
+ scheme: str,
56
+ sync_class: Type["CloudPath"],
57
+ async_class: Type["AsyncCloudPath"],
58
+ ) -> Tuple[Type["CloudPath"], Type["AsyncCloudPath"]]:
59
+ """Swap implementation for a scheme (for testing with local mocks).
60
+
61
+ Args:
62
+ scheme: URI scheme to swap
63
+ sync_class: New synchronous path class
64
+ async_class: New asynchronous path class
65
+
66
+ Returns:
67
+ Tuple of (old_sync_class, old_async_class)
68
+ """
69
+ old_classes = _REGISTRY.get(scheme, (None, None)) # type: ignore
70
+ _REGISTRY[scheme] = (sync_class, async_class)
71
+ return old_classes
panpath/router.py ADDED
@@ -0,0 +1,174 @@
1
+ """Router classes for dispatching to sync/async path implementations."""
2
+ import re
3
+ from pathlib import Path as PathlibPath
4
+ from typing import Any, Literal, Optional, Type, Union, overload
5
+
6
+ from panpath.exceptions import InvalidModeError
7
+ from panpath.registry import get_path_class
8
+
9
+
10
+ # URI scheme pattern
11
+ _URI_PATTERN = re.compile(r"^([a-z][a-z0-9+.-]*):\/\/", re.IGNORECASE)
12
+
13
+
14
+ def _parse_uri(path: str) -> tuple[Optional[str], str]:
15
+ """Parse URI to extract scheme and path.
16
+
17
+ Args:
18
+ path: Path string that may contain URI scheme
19
+
20
+ Returns:
21
+ Tuple of (scheme, path_without_scheme) or (None, path) for local paths
22
+ """
23
+ match = _URI_PATTERN.match(path)
24
+ if match:
25
+ scheme = match.group(1).lower()
26
+ # Special handling for file:// URLs - strip to local path
27
+ if scheme == "file":
28
+ return None, path[7:] # Remove 'file://'
29
+ return scheme, path
30
+ return None, path
31
+
32
+
33
+ class PanPathMeta(type):
34
+ """Metaclass for PanPath that dispatches based on URI scheme and mode."""
35
+
36
+ @overload
37
+ def __call__(
38
+ cls,
39
+ path: Union[str, PathlibPath],
40
+ mode: Literal["sync"] = "sync",
41
+ **kwargs: Any,
42
+ ) -> Any: # Returns sync path class
43
+ ...
44
+
45
+ @overload
46
+ def __call__(
47
+ cls,
48
+ path: Union[str, PathlibPath],
49
+ mode: Literal["async"],
50
+ **kwargs: Any,
51
+ ) -> Any: # Returns async path class
52
+ ...
53
+
54
+ def __call__(
55
+ cls,
56
+ path: Union[str, PathlibPath],
57
+ mode: str = "sync",
58
+ **kwargs: Any,
59
+ ) -> Any:
60
+ """Dispatch path creation based on URI scheme and mode.
61
+
62
+ Args:
63
+ path: Path string or pathlib.Path instance
64
+ mode: 'sync' or 'async'
65
+ **kwargs: Additional arguments passed to path class constructor
66
+
67
+ Returns:
68
+ Instance of appropriate path class (sync or async, local or cloud)
69
+
70
+ Raises:
71
+ InvalidModeError: If mode is not 'sync' or 'async'
72
+ """
73
+ if mode not in ("sync", "async"):
74
+ raise InvalidModeError(f"Invalid mode: {mode!r}. Must be 'sync' or 'async'.")
75
+
76
+ is_async = mode == "async"
77
+ path_str = str(path)
78
+
79
+ # Parse URI to get scheme
80
+ scheme, clean_path = _parse_uri(path_str)
81
+
82
+ if scheme is None:
83
+ # Local path
84
+ if is_async:
85
+ from panpath.local_async import AsyncLocalPath
86
+
87
+ return AsyncLocalPath(clean_path, **kwargs)
88
+ else:
89
+ from panpath.local_sync import LocalPath
90
+
91
+ return LocalPath(clean_path)
92
+
93
+ # Cloud path - look up in registry
94
+ try:
95
+ path_class = get_path_class(scheme, is_async=is_async)
96
+ return path_class(path_str, **kwargs)
97
+ except KeyError:
98
+ raise ValueError(f"Unsupported URI scheme: {scheme!r}")
99
+
100
+
101
+ class PanPath(metaclass=PanPathMeta):
102
+ """Universal path router supporting sync and async modes.
103
+
104
+ Examples:
105
+ >>> # Synchronous local path
106
+ >>> path = PanPath("/local/file.txt")
107
+ >>> path.read_text()
108
+
109
+ >>> # Synchronous S3 path
110
+ >>> path = PanPath("s3://bucket/key.txt")
111
+ >>> path.read_text()
112
+
113
+ >>> # Asynchronous S3 path
114
+ >>> path = PanPath("s3://bucket/key.txt", mode="async")
115
+ >>> await path.read_text()
116
+ """
117
+
118
+ def __init__(self, path: Union[str, PathlibPath], mode: str = "sync", **kwargs: Any):
119
+ """This is never called due to metaclass, but needed for type hints."""
120
+ pass
121
+
122
+
123
+ class AsyncPanPathMeta(type):
124
+ """Metaclass for AsyncPanPath that always returns async paths."""
125
+
126
+ def __call__(
127
+ cls,
128
+ path: Union[str, PathlibPath],
129
+ **kwargs: Any,
130
+ ) -> Any:
131
+ """Dispatch path creation to async implementation.
132
+
133
+ Args:
134
+ path: Path string or pathlib.Path instance
135
+ **kwargs: Additional arguments passed to async path class constructor
136
+
137
+ Returns:
138
+ Instance of appropriate async path class
139
+ """
140
+ path_str = str(path)
141
+
142
+ # Parse URI to get scheme
143
+ scheme, clean_path = _parse_uri(path_str)
144
+
145
+ if scheme is None:
146
+ # Local async path
147
+ from panpath.local_async import AsyncLocalPath
148
+
149
+ return AsyncLocalPath(clean_path, **kwargs)
150
+
151
+ # Cloud async path - look up in registry
152
+ try:
153
+ path_class = get_path_class(scheme, is_async=True)
154
+ return path_class(path_str, **kwargs)
155
+ except KeyError:
156
+ raise ValueError(f"Unsupported URI scheme: {scheme!r}")
157
+
158
+
159
+ class AsyncPanPath(metaclass=AsyncPanPathMeta):
160
+ """Universal async path router (always returns async paths).
161
+
162
+ Examples:
163
+ >>> # Asynchronous local path
164
+ >>> path = AsyncPanPath("/local/file.txt")
165
+ >>> await path.read_text()
166
+
167
+ >>> # Asynchronous S3 path
168
+ >>> path = AsyncPanPath("s3://bucket/key.txt")
169
+ >>> await path.read_text()
170
+ """
171
+
172
+ def __init__(self, path: Union[str, PathlibPath], **kwargs: Any):
173
+ """This is never called due to metaclass, but needed for type hints."""
174
+ pass
panpath/s3_async.py ADDED
@@ -0,0 +1,20 @@
1
+ """Async S3 path implementation."""
2
+ from typing import TYPE_CHECKING, Optional
3
+
4
+ from panpath.base import AsyncCloudPath
5
+ from panpath.s3_async_client import AsyncS3Client
6
+
7
+ if TYPE_CHECKING:
8
+ from panpath.clients import AsyncClient
9
+
10
+
11
+ class AsyncS3Path(AsyncCloudPath):
12
+ """Asynchronous S3 path implementation."""
13
+
14
+ _client: Optional[AsyncS3Client] = None
15
+ _default_client: Optional[AsyncS3Client] = None
16
+
17
+ @classmethod
18
+ def _create_default_client(cls) -> "AsyncClient":
19
+ """Create default async S3 client."""
20
+ return AsyncS3Client()