nacho-python 0.0.1__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.
- nacho/__init__.py +39 -0
- nacho/_version.py +4 -0
- nacho/cli/__init__.py +11 -0
- nacho/cli/main.py +638 -0
- nacho/config.py +544 -0
- nacho/env.py +117 -0
- nacho/event.py +409 -0
- nacho/schema.py +121 -0
- nacho/server/__init__.py +35 -0
- nacho/server/app.py +515 -0
- nacho/server/auth.py +93 -0
- nacho/server/models.py +165 -0
- nacho/server/runtime.py +452 -0
- nacho/server/ui/index.html +1282 -0
- nacho/storage/__init__.py +27 -0
- nacho/storage/base.py +33 -0
- nacho/storage/file.py +40 -0
- nacho/storage/remote.py +293 -0
- nacho/utils/__init__.py +14 -0
- nacho/utils/io.py +143 -0
- nacho/utils/path.py +145 -0
- nacho_python-0.0.1.dist-info/METADATA +605 -0
- nacho_python-0.0.1.dist-info/RECORD +27 -0
- nacho_python-0.0.1.dist-info/WHEEL +5 -0
- nacho_python-0.0.1.dist-info/entry_points.txt +2 -0
- nacho_python-0.0.1.dist-info/licenses/LICENSE +21 -0
- nacho_python-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from .base import StorageBackend, StorageError
|
|
2
|
+
from .file import FileStorageBackend
|
|
3
|
+
|
|
4
|
+
try:
|
|
5
|
+
import requests
|
|
6
|
+
import websocket # noqa: F401
|
|
7
|
+
|
|
8
|
+
HAS_REMOTE_DEPS = True
|
|
9
|
+
from .remote import RemoteStorageBackend
|
|
10
|
+
except ImportError:
|
|
11
|
+
HAS_REMOTE_DEPS = False
|
|
12
|
+
|
|
13
|
+
class RemoteStorageBackend: # type: ignore[no-redef]
|
|
14
|
+
def __init__(self, *args, **kwargs):
|
|
15
|
+
raise ImportError(
|
|
16
|
+
"RemoteStorageBackend requires extra dependencies. "
|
|
17
|
+
"Install with: pip install nacho[remote]"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"StorageBackend",
|
|
23
|
+
"StorageError",
|
|
24
|
+
"FileStorageBackend",
|
|
25
|
+
"RemoteStorageBackend",
|
|
26
|
+
"HAS_REMOTE_DEPS",
|
|
27
|
+
]
|
nacho/storage/base.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Abstract base for storage backends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from typing import Any, Callable, Dict, Optional
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class StorageError(Exception):
|
|
10
|
+
"""Raised when a storage operation fails."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class StorageBackend(ABC):
|
|
14
|
+
"""Pluggable persistence layer for Nacho.
|
|
15
|
+
|
|
16
|
+
Subclasses implement load() and save(); everything else is optional.
|
|
17
|
+
The on_remote_change callback is set by Nacho to propagate
|
|
18
|
+
externally-triggered changes back into the in-memory config.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self) -> None:
|
|
22
|
+
self.on_remote_change: Optional[Callable[[Dict[str, Any]], None]] = None
|
|
23
|
+
|
|
24
|
+
@abstractmethod
|
|
25
|
+
def load(self) -> Dict[str, Any]:
|
|
26
|
+
"""Read and return the full config dict."""
|
|
27
|
+
|
|
28
|
+
@abstractmethod
|
|
29
|
+
def save(self, data: Dict[str, Any]) -> None:
|
|
30
|
+
"""Persist *data*. Raises StorageError on failure."""
|
|
31
|
+
|
|
32
|
+
def cleanup(self) -> None:
|
|
33
|
+
"""Release resources (connections, threads, file handles). Optional."""
|
nacho/storage/file.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""File-based storage backend (YAML / JSON / TOML)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Dict, Union
|
|
8
|
+
|
|
9
|
+
from ..utils.io import create_file_if_not_exists, load_file, save_file
|
|
10
|
+
from .base import StorageBackend, StorageError
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class FileStorageBackend(StorageBackend):
|
|
16
|
+
"""Persist configuration to a local file.
|
|
17
|
+
|
|
18
|
+
The file is created (empty) on first use if it does not already exist.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, path: Union[str, Path]) -> None:
|
|
22
|
+
super().__init__()
|
|
23
|
+
self.path = Path(path)
|
|
24
|
+
create_file_if_not_exists(self.path)
|
|
25
|
+
|
|
26
|
+
def __str__(self) -> str:
|
|
27
|
+
return f"FileStorageBackend({self.path})"
|
|
28
|
+
|
|
29
|
+
def load(self) -> Dict[str, Any]:
|
|
30
|
+
try:
|
|
31
|
+
return load_file(self.path)
|
|
32
|
+
except (ValueError, IOError) as exc:
|
|
33
|
+
raise StorageError(f"Cannot load {self.path}: {exc}") from exc
|
|
34
|
+
|
|
35
|
+
def save(self, data: Dict[str, Any]) -> None:
|
|
36
|
+
try:
|
|
37
|
+
save_file(self.path, data)
|
|
38
|
+
logger.debug("Saved config to %s", self.path)
|
|
39
|
+
except (ValueError, IOError) as exc:
|
|
40
|
+
raise StorageError(f"Cannot save {self.path}: {exc}") from exc
|
nacho/storage/remote.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""Remote storage backend — connects to a Nacho server.
|
|
2
|
+
|
|
3
|
+
Write path : REST API (PUT /api/apps/{app}/config)
|
|
4
|
+
Read path : REST API (GET /api/apps/{app}/config)
|
|
5
|
+
Push path : WebSocket (server → client notifications only; client never writes via WS)
|
|
6
|
+
|
|
7
|
+
The WebSocket subscription keeps the local snapshot up-to-date in near-real-time.
|
|
8
|
+
Writes always go through REST so there is no ambiguity about who owns the state.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
from typing import Any, Dict, Optional
|
|
18
|
+
|
|
19
|
+
import requests
|
|
20
|
+
import websocket
|
|
21
|
+
|
|
22
|
+
from .base import StorageBackend, StorageError
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
_DEFAULT_TIMEOUT = 10.0
|
|
27
|
+
_WS_RECONNECT_DELAY = 5.0
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RemoteStorageBackend(StorageBackend):
|
|
31
|
+
"""Storage backend that mirrors a remote Nacho app via REST + WebSocket.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
url: Base URL of the remote Nacho server (e.g. "http://host:8000")
|
|
35
|
+
app_name: Name of the app to connect to (default: "default")
|
|
36
|
+
api_key: Bearer token for authentication
|
|
37
|
+
timeout: HTTP request timeout in seconds
|
|
38
|
+
reconnect: Number of WS reconnection attempts (0 = unlimited)
|
|
39
|
+
auto_connect: Verify the server/app during construction
|
|
40
|
+
watch: Start the WebSocket watcher during construction
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
url: str,
|
|
46
|
+
app_name: str = "default",
|
|
47
|
+
api_key: Optional[str] = None,
|
|
48
|
+
timeout: float = _DEFAULT_TIMEOUT,
|
|
49
|
+
reconnect: int = 0,
|
|
50
|
+
auto_connect: bool = True,
|
|
51
|
+
watch: bool = False,
|
|
52
|
+
) -> None:
|
|
53
|
+
super().__init__()
|
|
54
|
+
self._base = url.rstrip("/")
|
|
55
|
+
self.app_name = app_name
|
|
56
|
+
self._api_key = api_key
|
|
57
|
+
self._timeout = timeout
|
|
58
|
+
self._reconnect = reconnect
|
|
59
|
+
|
|
60
|
+
self._api_url = f"{self._base}/api/apps/{app_name}/config"
|
|
61
|
+
self._ws_url = (
|
|
62
|
+
self._base.replace("https://", "wss://").replace("http://", "ws://") + f"/ws/{app_name}"
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
self._ws: Optional[websocket.WebSocketApp] = None
|
|
66
|
+
self._ws_thread: Optional[threading.Thread] = None
|
|
67
|
+
self._running = False
|
|
68
|
+
self._connected = False
|
|
69
|
+
self._watch_requested = watch
|
|
70
|
+
|
|
71
|
+
if auto_connect:
|
|
72
|
+
self.connect(watch=watch)
|
|
73
|
+
|
|
74
|
+
# ------------------------------------------------------------------
|
|
75
|
+
# StorageBackend interface
|
|
76
|
+
# ------------------------------------------------------------------
|
|
77
|
+
|
|
78
|
+
def load(self) -> Dict[str, Any]:
|
|
79
|
+
self._ensure_connected()
|
|
80
|
+
resp = self._get(self._api_url)
|
|
81
|
+
data = resp.json()
|
|
82
|
+
if not isinstance(data, dict):
|
|
83
|
+
raise StorageError(f"Remote app {self.app_name!r} returned non-object config")
|
|
84
|
+
return data
|
|
85
|
+
|
|
86
|
+
def save(self, data: Dict[str, Any]) -> None:
|
|
87
|
+
"""Persist *data* by replacing the app's config on the server."""
|
|
88
|
+
self._ensure_connected()
|
|
89
|
+
payload = {"data": json.dumps(data), "format": "json"}
|
|
90
|
+
resp = self._put(self._api_url, payload)
|
|
91
|
+
if resp.status_code == 404:
|
|
92
|
+
self._create_app(data)
|
|
93
|
+
return
|
|
94
|
+
try:
|
|
95
|
+
resp.raise_for_status()
|
|
96
|
+
except requests.RequestException as exc:
|
|
97
|
+
raise StorageError(f"PUT {self._api_url} failed: {exc}") from exc
|
|
98
|
+
logger.debug("Saved config to remote app %r", self.app_name)
|
|
99
|
+
|
|
100
|
+
def cleanup(self) -> None:
|
|
101
|
+
self.close()
|
|
102
|
+
|
|
103
|
+
def connect(self, *, watch: Optional[bool] = None) -> None:
|
|
104
|
+
"""Verify the remote app and optionally start receiving push updates."""
|
|
105
|
+
self._ensure_connected()
|
|
106
|
+
should_watch = self._watch_requested if watch is None else watch
|
|
107
|
+
if should_watch:
|
|
108
|
+
self.start_watching()
|
|
109
|
+
|
|
110
|
+
def start_watching(self) -> None:
|
|
111
|
+
"""Start the WebSocket watcher if it is not already running."""
|
|
112
|
+
self._ensure_connected()
|
|
113
|
+
self._start_ws()
|
|
114
|
+
|
|
115
|
+
def close(self) -> None:
|
|
116
|
+
self._running = False
|
|
117
|
+
if self._ws:
|
|
118
|
+
self._ws.close()
|
|
119
|
+
if self._ws_thread and self._ws_thread.is_alive():
|
|
120
|
+
self._ws_thread.join(timeout=2.0)
|
|
121
|
+
|
|
122
|
+
# ------------------------------------------------------------------
|
|
123
|
+
# Internals — HTTP
|
|
124
|
+
# ------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
def _headers(self) -> Dict[str, str]:
|
|
127
|
+
h = {"Content-Type": "application/json"}
|
|
128
|
+
if self._api_key:
|
|
129
|
+
h["Authorization"] = f"Bearer {self._api_key}"
|
|
130
|
+
return h
|
|
131
|
+
|
|
132
|
+
def _ensure_connected(self) -> None:
|
|
133
|
+
if self._connected:
|
|
134
|
+
return
|
|
135
|
+
self._verify_connection()
|
|
136
|
+
self._connected = True
|
|
137
|
+
|
|
138
|
+
def _get(self, url: str) -> requests.Response:
|
|
139
|
+
try:
|
|
140
|
+
resp = requests.get(url, headers=self._headers(), timeout=self._timeout)
|
|
141
|
+
resp.raise_for_status()
|
|
142
|
+
return resp
|
|
143
|
+
except requests.RequestException as exc:
|
|
144
|
+
raise StorageError(f"GET {url} failed: {exc}") from exc
|
|
145
|
+
|
|
146
|
+
def _put(self, url: str, payload: Dict[str, Any]) -> requests.Response:
|
|
147
|
+
try:
|
|
148
|
+
return requests.put(
|
|
149
|
+
url,
|
|
150
|
+
json=payload,
|
|
151
|
+
headers=self._headers(),
|
|
152
|
+
timeout=self._timeout,
|
|
153
|
+
)
|
|
154
|
+
except requests.RequestException as exc:
|
|
155
|
+
raise StorageError(f"PUT {url} failed: {exc}") from exc
|
|
156
|
+
|
|
157
|
+
def _post(self, url: str, payload: Dict[str, Any]) -> requests.Response:
|
|
158
|
+
try:
|
|
159
|
+
return requests.post(
|
|
160
|
+
url,
|
|
161
|
+
json=payload,
|
|
162
|
+
headers=self._headers(),
|
|
163
|
+
timeout=self._timeout,
|
|
164
|
+
)
|
|
165
|
+
except requests.RequestException as exc:
|
|
166
|
+
raise StorageError(f"POST {url} failed: {exc}") from exc
|
|
167
|
+
|
|
168
|
+
def _verify_connection(self) -> None:
|
|
169
|
+
"""Confirm the server is reachable and the app exists (or create it).
|
|
170
|
+
|
|
171
|
+
Raises StorageError on any connectivity problem so failures surface at
|
|
172
|
+
construction time, not silently later.
|
|
173
|
+
"""
|
|
174
|
+
health_url = f"{self._base}/health"
|
|
175
|
+
try:
|
|
176
|
+
resp = requests.get(health_url, headers=self._headers(), timeout=self._timeout)
|
|
177
|
+
resp.raise_for_status()
|
|
178
|
+
except requests.RequestException as exc:
|
|
179
|
+
raise StorageError(f"Cannot reach Nacho server at {self._base}: {exc}") from exc
|
|
180
|
+
|
|
181
|
+
# Ensure the target app exists
|
|
182
|
+
info_url = f"{self._base}/api/apps/{self.app_name}"
|
|
183
|
+
resp = requests.get(info_url, headers=self._headers(), timeout=self._timeout)
|
|
184
|
+
if resp.status_code == 404:
|
|
185
|
+
self._create_app({})
|
|
186
|
+
elif not resp.ok:
|
|
187
|
+
raise StorageError(
|
|
188
|
+
f"App {self.app_name!r} check failed: {resp.status_code} {resp.text}"
|
|
189
|
+
)
|
|
190
|
+
logger.info("Connected to Nacho server %s (app: %r)", self._base, self.app_name)
|
|
191
|
+
|
|
192
|
+
def _create_app(self, initial_data: Dict[str, Any]) -> None:
|
|
193
|
+
payload = {
|
|
194
|
+
"name": self.app_name,
|
|
195
|
+
"data": json.dumps(initial_data),
|
|
196
|
+
"format": "json",
|
|
197
|
+
}
|
|
198
|
+
resp = self._post(f"{self._base}/api/apps", payload)
|
|
199
|
+
if resp.status_code not in (200, 201):
|
|
200
|
+
raise StorageError(
|
|
201
|
+
f"Failed to create app {self.app_name!r}: {resp.status_code} {resp.text}"
|
|
202
|
+
)
|
|
203
|
+
logger.info("Created remote app %r", self.app_name)
|
|
204
|
+
|
|
205
|
+
# ------------------------------------------------------------------
|
|
206
|
+
# Internals — WebSocket (receive-only)
|
|
207
|
+
# ------------------------------------------------------------------
|
|
208
|
+
|
|
209
|
+
def _start_ws(self) -> None:
|
|
210
|
+
if self._running:
|
|
211
|
+
return
|
|
212
|
+
self._running = True
|
|
213
|
+
self._ws_thread = threading.Thread(
|
|
214
|
+
target=self._ws_loop,
|
|
215
|
+
daemon=True,
|
|
216
|
+
name=f"NACHO-ws-{self.app_name}",
|
|
217
|
+
)
|
|
218
|
+
self._ws_thread.start()
|
|
219
|
+
|
|
220
|
+
def _ws_loop(self) -> None:
|
|
221
|
+
attempt = 0
|
|
222
|
+
while self._running:
|
|
223
|
+
try:
|
|
224
|
+
self._ws = websocket.WebSocketApp(
|
|
225
|
+
self._ws_url,
|
|
226
|
+
header=self._headers(),
|
|
227
|
+
on_open=self._on_open,
|
|
228
|
+
on_message=self._on_message,
|
|
229
|
+
on_error=self._on_error,
|
|
230
|
+
on_close=self._on_close,
|
|
231
|
+
)
|
|
232
|
+
self._ws.run_forever()
|
|
233
|
+
except Exception as exc:
|
|
234
|
+
logger.error("WS error for %r: %s", self.app_name, exc)
|
|
235
|
+
|
|
236
|
+
if not self._running:
|
|
237
|
+
break
|
|
238
|
+
|
|
239
|
+
attempt += 1
|
|
240
|
+
if self._reconnect and attempt > self._reconnect:
|
|
241
|
+
logger.error(
|
|
242
|
+
"WS: max reconnect attempts (%d) reached for %r — giving up",
|
|
243
|
+
self._reconnect,
|
|
244
|
+
self.app_name,
|
|
245
|
+
)
|
|
246
|
+
break
|
|
247
|
+
logger.debug(
|
|
248
|
+
"WS: reconnecting to %r in %.1fs (attempt %d)",
|
|
249
|
+
self.app_name,
|
|
250
|
+
_WS_RECONNECT_DELAY,
|
|
251
|
+
attempt,
|
|
252
|
+
)
|
|
253
|
+
time.sleep(_WS_RECONNECT_DELAY)
|
|
254
|
+
|
|
255
|
+
def _on_open(self, ws: websocket.WebSocketApp) -> None:
|
|
256
|
+
logger.debug("WS connected for app %r", self.app_name)
|
|
257
|
+
|
|
258
|
+
def _on_message(self, ws: websocket.WebSocketApp, raw: str) -> None:
|
|
259
|
+
try:
|
|
260
|
+
msg = json.loads(raw)
|
|
261
|
+
except json.JSONDecodeError:
|
|
262
|
+
logger.warning("WS: malformed message for %r: %r", self.app_name, raw)
|
|
263
|
+
return
|
|
264
|
+
|
|
265
|
+
if not isinstance(msg, dict):
|
|
266
|
+
logger.warning("WS: ignored non-object message for %r", self.app_name)
|
|
267
|
+
return
|
|
268
|
+
|
|
269
|
+
msg_type = msg.get("type")
|
|
270
|
+
data = msg.get("data")
|
|
271
|
+
if msg_type in ("update", "initial_config") and isinstance(data, dict):
|
|
272
|
+
callback = self.on_remote_change
|
|
273
|
+
if callback:
|
|
274
|
+
try:
|
|
275
|
+
callback(data)
|
|
276
|
+
except Exception as exc:
|
|
277
|
+
logger.error("on_remote_change raised: %s", exc)
|
|
278
|
+
elif msg_type in ("update", "initial_config"):
|
|
279
|
+
logger.warning("WS: ignored invalid config payload for %r", self.app_name)
|
|
280
|
+
|
|
281
|
+
def _on_error(self, ws: websocket.WebSocketApp, error: Exception) -> None:
|
|
282
|
+
logger.warning("WS error for %r: %s", self.app_name, error)
|
|
283
|
+
|
|
284
|
+
def _on_close(
|
|
285
|
+
self,
|
|
286
|
+
ws: websocket.WebSocketApp,
|
|
287
|
+
code: Optional[int],
|
|
288
|
+
reason: Optional[str],
|
|
289
|
+
) -> None:
|
|
290
|
+
logger.debug("WS closed for %r: %s %s", self.app_name, code, reason)
|
|
291
|
+
|
|
292
|
+
def __str__(self) -> str:
|
|
293
|
+
return f"RemoteStorageBackend(url={self._base!r}, app={self.app_name!r})"
|
nacho/utils/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from .io import create_file_if_not_exists, load_file, load_string, save_file
|
|
2
|
+
from .path import deep_merge, delete_nested_value, get_nested_value, parse_path, set_nested_value
|
|
3
|
+
|
|
4
|
+
__all__ = [
|
|
5
|
+
"parse_path",
|
|
6
|
+
"get_nested_value",
|
|
7
|
+
"set_nested_value",
|
|
8
|
+
"delete_nested_value",
|
|
9
|
+
"deep_merge",
|
|
10
|
+
"load_file",
|
|
11
|
+
"save_file",
|
|
12
|
+
"load_string",
|
|
13
|
+
"create_file_if_not_exists",
|
|
14
|
+
]
|
nacho/utils/io.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""File I/O utilities supporting YAML, JSON, and TOML formats."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import tempfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Dict, Union
|
|
11
|
+
|
|
12
|
+
import yaml
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
import tomllib # Python ≥ 3.11
|
|
16
|
+
except ImportError:
|
|
17
|
+
import tomli as tomllib # type: ignore[no-redef]
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
import tomli_w
|
|
21
|
+
except ImportError:
|
|
22
|
+
tomli_w = None # type: ignore[assignment]
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _suffix(path: Path) -> str:
|
|
28
|
+
return path.suffix.lower()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def load_file(path: Union[str, Path]) -> Dict[str, Any]:
|
|
32
|
+
"""Load a YAML / JSON / TOML file and return a dict.
|
|
33
|
+
|
|
34
|
+
Returns an empty dict when the file is missing or empty.
|
|
35
|
+
Raises ValueError on parse errors so callers can decide how to handle.
|
|
36
|
+
"""
|
|
37
|
+
path = Path(path)
|
|
38
|
+
if not path.exists():
|
|
39
|
+
return {}
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
suffix = _suffix(path)
|
|
43
|
+
if suffix in (".yaml", ".yml"):
|
|
44
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
45
|
+
return yaml.safe_load(f) or {}
|
|
46
|
+
if suffix == ".json":
|
|
47
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
48
|
+
return json.load(f) or {}
|
|
49
|
+
if suffix == ".toml":
|
|
50
|
+
with open(path, "rb") as f:
|
|
51
|
+
return tomllib.load(f) or {}
|
|
52
|
+
# Unknown extension → try YAML
|
|
53
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
54
|
+
return yaml.safe_load(f) or {}
|
|
55
|
+
except (json.JSONDecodeError, yaml.YAMLError, tomllib.TOMLDecodeError) as exc:
|
|
56
|
+
raise ValueError(f"Failed to parse {path}: {exc}") from exc
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def save_file(path: Union[str, Path], data: Dict[str, Any]) -> None:
|
|
60
|
+
"""Persist *data* to a YAML / JSON / TOML file.
|
|
61
|
+
|
|
62
|
+
Raises IOError on write failures, ValueError for unsupported formats.
|
|
63
|
+
"""
|
|
64
|
+
path = Path(path)
|
|
65
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
66
|
+
|
|
67
|
+
suffix = _suffix(path)
|
|
68
|
+
tmp_name = ""
|
|
69
|
+
try:
|
|
70
|
+
fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
|
|
71
|
+
os.close(fd)
|
|
72
|
+
tmp_path = Path(tmp_name)
|
|
73
|
+
if suffix in (".yaml", ".yml"):
|
|
74
|
+
with open(tmp_path, "w", encoding="utf-8") as f:
|
|
75
|
+
yaml.dump(data, f, default_flow_style=False, sort_keys=False, indent=2)
|
|
76
|
+
elif suffix == ".json":
|
|
77
|
+
with open(tmp_path, "w", encoding="utf-8") as f:
|
|
78
|
+
json.dump(data, f, indent=2, ensure_ascii=False)
|
|
79
|
+
elif suffix == ".toml":
|
|
80
|
+
if tomli_w is None:
|
|
81
|
+
raise ValueError(
|
|
82
|
+
"TOML write support requires 'tomli_w'. Install with: pip install tomli-w"
|
|
83
|
+
)
|
|
84
|
+
with open(tmp_path, "wb") as f:
|
|
85
|
+
tomli_w.dump(data, f)
|
|
86
|
+
else:
|
|
87
|
+
# Unknown extension → YAML
|
|
88
|
+
with open(tmp_path, "w", encoding="utf-8") as f:
|
|
89
|
+
yaml.dump(data, f, default_flow_style=False, sort_keys=False, indent=2)
|
|
90
|
+
os.replace(tmp_path, path)
|
|
91
|
+
except OSError as exc:
|
|
92
|
+
raise IOError(f"Failed to write {path}: {exc}") from exc
|
|
93
|
+
finally:
|
|
94
|
+
if tmp_name:
|
|
95
|
+
try:
|
|
96
|
+
Path(tmp_name).unlink(missing_ok=True)
|
|
97
|
+
except OSError:
|
|
98
|
+
logger.warning("Failed to clean temporary file %s", tmp_name)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def load_string(text: str, fmt: str = "json") -> Dict[str, Any]:
|
|
102
|
+
"""Parse a config string in the given format ('json', 'yaml', 'toml').
|
|
103
|
+
|
|
104
|
+
Returns an empty dict for blank input.
|
|
105
|
+
"""
|
|
106
|
+
if not text or not text.strip():
|
|
107
|
+
return {}
|
|
108
|
+
if fmt == "yaml":
|
|
109
|
+
return yaml.safe_load(text) or {}
|
|
110
|
+
if fmt == "toml":
|
|
111
|
+
return tomllib.loads(text) or {}
|
|
112
|
+
return json.loads(text)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def dump_string(data: Dict[str, Any], fmt: str = "json") -> str:
|
|
116
|
+
"""Serialize a config dict to a string in the given format.
|
|
117
|
+
|
|
118
|
+
Raises ValueError for unsupported formats or data the format cannot
|
|
119
|
+
represent (e.g. ``null`` values in TOML).
|
|
120
|
+
"""
|
|
121
|
+
if fmt == "yaml":
|
|
122
|
+
return yaml.dump(
|
|
123
|
+
data, default_flow_style=False, sort_keys=False, indent=2, allow_unicode=True
|
|
124
|
+
)
|
|
125
|
+
if fmt == "toml":
|
|
126
|
+
if tomli_w is None:
|
|
127
|
+
raise ValueError(
|
|
128
|
+
"TOML write support requires 'tomli_w'. Install with: pip install tomli-w"
|
|
129
|
+
)
|
|
130
|
+
try:
|
|
131
|
+
return tomli_w.dumps(data)
|
|
132
|
+
except (TypeError, ValueError) as exc:
|
|
133
|
+
raise ValueError(f"Data cannot be represented as TOML: {exc}") from exc
|
|
134
|
+
return json.dumps(data, indent=2, ensure_ascii=False)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def create_file_if_not_exists(path: Union[str, Path]) -> None:
|
|
138
|
+
"""Touch *path* and its parent directories into existence."""
|
|
139
|
+
path = Path(path)
|
|
140
|
+
if path.exists():
|
|
141
|
+
return
|
|
142
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
143
|
+
path.touch()
|
nacho/utils/path.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Path navigation utilities for dot-notation config access."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import re
|
|
7
|
+
from typing import Any, Dict, List, MutableMapping, Tuple
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _parse_segment(segment: str) -> List[str]:
|
|
11
|
+
m = re.match(r"^([^[\]]+)\[([^\]]+)\]$", segment)
|
|
12
|
+
if m:
|
|
13
|
+
key, index = m.groups()
|
|
14
|
+
return [key, index]
|
|
15
|
+
return [segment]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def parse_path(path: str) -> List[str]:
|
|
19
|
+
"""Split a dot-notation path into a flat list of keys and array indices.
|
|
20
|
+
|
|
21
|
+
Examples:
|
|
22
|
+
"database.host" → ["database", "host"]
|
|
23
|
+
"servers[0].port" → ["servers", "0", "port"]
|
|
24
|
+
"""
|
|
25
|
+
if not path:
|
|
26
|
+
return []
|
|
27
|
+
result = []
|
|
28
|
+
for segment in path.split("."):
|
|
29
|
+
result.extend(_parse_segment(segment))
|
|
30
|
+
return result
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def get_nested_value(data: Dict[str, Any], path: str, default: Any = None) -> Any:
|
|
34
|
+
"""Retrieve a value by dot-notation path; return *default* when absent."""
|
|
35
|
+
if not path:
|
|
36
|
+
return data
|
|
37
|
+
try:
|
|
38
|
+
current = data
|
|
39
|
+
for key in parse_path(path):
|
|
40
|
+
current = current[int(key)] if key.isdigit() else current[key]
|
|
41
|
+
return current
|
|
42
|
+
except (KeyError, IndexError, TypeError):
|
|
43
|
+
return default
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def set_nested_value(data: Dict[str, Any], path: str, value: Any) -> bool:
|
|
47
|
+
"""Set a value by dot-notation path, creating intermediate dicts as needed.
|
|
48
|
+
|
|
49
|
+
Returns True when the value changed, False when it was already equal.
|
|
50
|
+
"""
|
|
51
|
+
if not path:
|
|
52
|
+
return False
|
|
53
|
+
|
|
54
|
+
_MISSING = object()
|
|
55
|
+
if get_nested_value(data, path, _MISSING) == value:
|
|
56
|
+
return False
|
|
57
|
+
|
|
58
|
+
keys = parse_path(path)
|
|
59
|
+
if not keys:
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
current: Any = data
|
|
63
|
+
for index, key in enumerate(keys[:-1]):
|
|
64
|
+
next_key = keys[index + 1]
|
|
65
|
+
if key.isdigit():
|
|
66
|
+
idx = int(key)
|
|
67
|
+
if not isinstance(current, list):
|
|
68
|
+
return False
|
|
69
|
+
while len(current) <= idx:
|
|
70
|
+
current.append([] if next_key.isdigit() else {})
|
|
71
|
+
current = current[idx]
|
|
72
|
+
else:
|
|
73
|
+
if not isinstance(current, MutableMapping):
|
|
74
|
+
return False
|
|
75
|
+
if key not in current:
|
|
76
|
+
current[key] = [] if next_key.isdigit() else {}
|
|
77
|
+
elif not isinstance(current[key], (dict, list)):
|
|
78
|
+
return False
|
|
79
|
+
current = current[key]
|
|
80
|
+
|
|
81
|
+
final = keys[-1]
|
|
82
|
+
try:
|
|
83
|
+
if final.isdigit() and isinstance(current, list):
|
|
84
|
+
idx = int(final)
|
|
85
|
+
while len(current) <= idx:
|
|
86
|
+
current.append(None)
|
|
87
|
+
current[idx] = value
|
|
88
|
+
elif isinstance(current, MutableMapping):
|
|
89
|
+
current[final] = value
|
|
90
|
+
else:
|
|
91
|
+
return False
|
|
92
|
+
return True
|
|
93
|
+
except (KeyError, IndexError, TypeError):
|
|
94
|
+
return False
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def delete_nested_value(data: Dict[str, Any], path: str) -> Tuple[bool, Any]:
|
|
98
|
+
"""Delete a value by dot-notation path.
|
|
99
|
+
|
|
100
|
+
Returns (True, old_value) on success, (False, None) when the key is absent.
|
|
101
|
+
"""
|
|
102
|
+
if not path:
|
|
103
|
+
return False, None
|
|
104
|
+
|
|
105
|
+
_MISSING = object()
|
|
106
|
+
old_value = get_nested_value(data, path, _MISSING)
|
|
107
|
+
if old_value is _MISSING:
|
|
108
|
+
return False, None
|
|
109
|
+
|
|
110
|
+
keys = parse_path(path)
|
|
111
|
+
current = data
|
|
112
|
+
try:
|
|
113
|
+
for key in keys[:-1]:
|
|
114
|
+
current = current[int(key)] if key.isdigit() else current[key]
|
|
115
|
+
except (KeyError, IndexError, TypeError):
|
|
116
|
+
return False, None
|
|
117
|
+
|
|
118
|
+
final = keys[-1]
|
|
119
|
+
try:
|
|
120
|
+
if final.isdigit():
|
|
121
|
+
idx = int(final)
|
|
122
|
+
if not isinstance(current, list):
|
|
123
|
+
return False, None
|
|
124
|
+
del current[idx]
|
|
125
|
+
else:
|
|
126
|
+
del current[final]
|
|
127
|
+
return True, old_value
|
|
128
|
+
except (KeyError, IndexError, TypeError):
|
|
129
|
+
return False, None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def deep_merge(source: Dict[str, Any], destination: Dict[str, Any]) -> Dict[str, Any]:
|
|
133
|
+
"""Return a new dict that is *destination* deep-merged with *source*.
|
|
134
|
+
|
|
135
|
+
Source keys take precedence; nested dicts are merged recursively.
|
|
136
|
+
"""
|
|
137
|
+
if not isinstance(destination, dict) or not isinstance(source, dict):
|
|
138
|
+
return copy.deepcopy(source)
|
|
139
|
+
result = copy.deepcopy(destination)
|
|
140
|
+
for key, value in source.items():
|
|
141
|
+
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
|
142
|
+
result[key] = deep_merge(value, result[key])
|
|
143
|
+
else:
|
|
144
|
+
result[key] = copy.deepcopy(value)
|
|
145
|
+
return result
|