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 ADDED
@@ -0,0 +1,39 @@
1
+ """Nacho — schema-first dynamic configuration service."""
2
+
3
+ from ._version import __version__
4
+ from .config import Nacho
5
+ from .event import EventType
6
+ from .schema import HAS_SCHEMA_DEPS, ValidationError
7
+ from .storage import (
8
+ HAS_REMOTE_DEPS,
9
+ FileStorageBackend,
10
+ StorageBackend,
11
+ StorageError,
12
+ )
13
+
14
+ try:
15
+ from .storage import RemoteStorageBackend
16
+ except ImportError:
17
+ pass
18
+
19
+ try:
20
+ from .server.app import NachoOrchestrator
21
+
22
+ HAS_SERVER_DEPS = True
23
+ except ImportError:
24
+ HAS_SERVER_DEPS = False
25
+
26
+ __all__ = [
27
+ "__version__",
28
+ "Nacho",
29
+ "EventType",
30
+ "ValidationError",
31
+ "StorageBackend",
32
+ "StorageError",
33
+ "FileStorageBackend",
34
+ "RemoteStorageBackend",
35
+ "NachoOrchestrator",
36
+ "HAS_SCHEMA_DEPS",
37
+ "HAS_REMOTE_DEPS",
38
+ "HAS_SERVER_DEPS",
39
+ ]
nacho/_version.py ADDED
@@ -0,0 +1,4 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Version information for Nacho."""
3
+
4
+ __version__ = "0.0.1"
nacho/cli/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """Nacho CLI package.
2
+
3
+ This package provides the command-line interface for Nacho.
4
+ """
5
+
6
+ def main_cli(*args, **kwargs):
7
+ from .main import main_cli as _main_cli
8
+
9
+ return _main_cli(*args, **kwargs)
10
+
11
+ __all__ = ["main_cli"]
nacho/cli/main.py ADDED
@@ -0,0 +1,638 @@
1
+ """
2
+ Command-line interface for Nacho.
3
+ """
4
+
5
+ import argparse
6
+ import json
7
+ import logging
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Any, Optional
11
+ from urllib.parse import quote
12
+
13
+ import yaml
14
+
15
+ from nacho import HAS_REMOTE_DEPS, HAS_SCHEMA_DEPS, HAS_SERVER_DEPS
16
+ from nacho._version import __version__
17
+ from nacho.config import Nacho
18
+ from nacho.env import _parse_value as parse_value
19
+ from nacho.server import NachoOrchestrator
20
+ from nacho.utils.io import save_file
21
+
22
+ LOGGER = logging.getLogger("nacho.cli")
23
+
24
+ BANNER = r"""
25
+ _ _ _ ____ _ _ ___
26
+ | \ | | / \ / ___|| | | | / _ \
27
+ | \| | / _ \ | | | |_| || | | |
28
+ | |\ | / ___ \ | |___ | _ || |_| |
29
+ |_| \_|/_/ \_\ \____||_| |_| \___/
30
+ """
31
+
32
+
33
+ def banner() -> str:
34
+ """Return the ASCII banner with a version tagline."""
35
+ return (
36
+ f"{BANNER}"
37
+ f" Lightweight, schema-first dynamic configuration · v{__version__}\n"
38
+ )
39
+
40
+
41
+ BUILT_IN_TEMPLATES = {
42
+ "empty": {
43
+ "name": "Empty Configuration",
44
+ "description": "Start with a blank configuration",
45
+ "icon": "📄",
46
+ "data": {},
47
+ "format": "json",
48
+ },
49
+ "web-app": {
50
+ "name": "Web Application",
51
+ "description": "Frontend application with server and API settings",
52
+ "icon": "🌐",
53
+ "data": {
54
+ "app": {"name": "web-app", "version": "1.0.0", "port": 3000},
55
+ "server": {"host": "localhost", "ssl": False},
56
+ "api": {"baseUrl": "/api/v1", "timeout": 5000},
57
+ },
58
+ "format": "json",
59
+ },
60
+ "api-service": {
61
+ "name": "API Service",
62
+ "description": "Backend service with database and auth configuration",
63
+ "icon": "🔌",
64
+ "data": {
65
+ "service": {"name": "api-service", "version": "1.0.0", "port": 8000},
66
+ "database": {"host": "localhost", "port": 5432, "name": "app_db"},
67
+ "auth": {"jwt_secret": "your-secret-key", "expires_in": "24h"},
68
+ },
69
+ "format": "json",
70
+ },
71
+ # Add more templates as needed
72
+ "microservice": {
73
+ "name": "Microservice",
74
+ "description": "Containerized service with logging and metrics",
75
+ "icon": "🐳",
76
+ "data": {
77
+ "service": {"name": "microservice", "version": "1.0.0", "port": 8080},
78
+ "logging": {"level": "info", "format": "json"},
79
+ "metrics": {"enabled": True, "endpoint": "/metrics"},
80
+ "health": {"endpoint": "/health", "timeout": 30},
81
+ },
82
+ "format": "json",
83
+ },
84
+ "default": {
85
+ "name": "Default Configuration",
86
+ "description": "Basic configuration template",
87
+ "icon": "⚙️",
88
+ "data": {
89
+ "app": {"name": "default-app", "version": "1.0.0"},
90
+ "settings": {"debug": True, "log_level": "info"},
91
+ },
92
+ "format": "json",
93
+ },
94
+ }
95
+
96
+
97
+ def str2bool(x):
98
+ if x.lower() in ("yes", "true", "t", "1"):
99
+ return True
100
+ if x.lower() in ("no", "false", "f", "0"):
101
+ return False
102
+ raise argparse.ArgumentTypeError(f"Boolean value expected, got {x!r}")
103
+
104
+
105
+ def create_parser() -> argparse.ArgumentParser:
106
+ """
107
+ Create the main argument parser.
108
+ """
109
+ parser = argparse.ArgumentParser(
110
+ prog="nacho",
111
+ description=banner(),
112
+ formatter_class=argparse.RawDescriptionHelpFormatter,
113
+ )
114
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
115
+ parser.add_argument(
116
+ "--debug",
117
+ type=str2bool,
118
+ nargs="?",
119
+ const=True,
120
+ default=False,
121
+ help="Enable debug logging",
122
+ )
123
+
124
+ subparsers = parser.add_subparsers(dest="command", help="Available commands")
125
+
126
+ # Server command
127
+ server = subparsers.add_parser("server", help="Start configuration server")
128
+ server.add_argument("--host", default="0.0.0.0", help="Server host")
129
+ server.add_argument("--port", type=int, default=8000, help="Server port")
130
+ server.add_argument("--config", "-c", help="Configuration file path")
131
+ server.add_argument("--schema", help="Schema file path")
132
+ server.add_argument("--data-dir", help="Directory for API-created app state")
133
+ server.add_argument("--api-key", help="API key for authentication")
134
+ server.add_argument("--app-name", help="Application name for config server")
135
+ server.add_argument(
136
+ "--event",
137
+ type=str2bool,
138
+ nargs="?",
139
+ const=True,
140
+ default=False,
141
+ help="Event pipeline for configuration changes",
142
+ )
143
+ server.add_argument(
144
+ "--read-only",
145
+ type=str2bool,
146
+ nargs="?",
147
+ const=True,
148
+ default=False,
149
+ help="Read-only mode",
150
+ )
151
+ server.add_argument(
152
+ "--reload",
153
+ type=str2bool,
154
+ nargs="?",
155
+ const=True,
156
+ default=False,
157
+ help="Auto-reload for development",
158
+ )
159
+
160
+ # Connect command (connect to a remote server)
161
+ connect = subparsers.add_parser("connect", help="Connect to a remote configuration server")
162
+ connect.add_argument("--remote", help="Remote server URL")
163
+ connect.add_argument("--app-name", default="default", help="Application name for remote server")
164
+ connect.add_argument("--api-key", help="API key for remote server")
165
+ connect.add_argument("--format", "-f", choices=["json", "yaml", "raw"], default="raw")
166
+
167
+ # Get command
168
+ get = subparsers.add_parser("get", help="Get configuration value")
169
+ get.add_argument("key", nargs="?", help="Configuration key (optional)")
170
+ get.add_argument("--config", "-c", default="config.yaml", help="Configuration file")
171
+ get.add_argument("--format", "-f", choices=["json", "yaml", "raw"], default="raw")
172
+ get.add_argument("--remote", help="Remote server URL")
173
+ get.add_argument("--app-name", default="default", help="Application name for remote server")
174
+ get.add_argument("--api-key", help="API key for remote server")
175
+ get.add_argument(
176
+ "--show-revision",
177
+ action="store_true",
178
+ help="Include the remote app revision in JSON/YAML output",
179
+ )
180
+
181
+ # Set command
182
+ set_parser = subparsers.add_parser("set", help="Set configuration value")
183
+ set_parser.add_argument("key", help="Configuration key")
184
+ set_parser.add_argument("value", help="Configuration value")
185
+ set_parser.add_argument("--config", "-c", default="config.yaml", help="Configuration file")
186
+ set_parser.add_argument("--schema", help="Schema file for validation")
187
+ set_parser.add_argument("--remote", help="Remote server URL")
188
+ set_parser.add_argument(
189
+ "--app-name", default="default", help="Application name for remote server"
190
+ )
191
+ set_parser.add_argument("--api-key", help="API key for remote server")
192
+ set_parser.add_argument(
193
+ "--revision",
194
+ type=int,
195
+ help="Expected remote app revision for conflict-safe writes",
196
+ )
197
+
198
+ # Delete command
199
+ delete = subparsers.add_parser("delete", help="Delete configuration value")
200
+ delete.add_argument("key", help="Configuration key")
201
+ delete.add_argument("--config", "-c", default="config.yaml", help="Configuration file")
202
+ delete.add_argument("--schema", help="Schema file for validation")
203
+ delete.add_argument("--remote", help="Remote server URL")
204
+ delete.add_argument("--app-name", default="default", help="Application name for remote server")
205
+ delete.add_argument("--api-key", help="API key for remote server")
206
+ delete.add_argument(
207
+ "--revision",
208
+ type=int,
209
+ help="Expected remote app revision for conflict-safe deletes",
210
+ )
211
+
212
+ # Validate command
213
+ validate = subparsers.add_parser("validate", help="Validate configuration")
214
+ validate.add_argument("--config", "-c", default="config.yaml", help="Configuration file")
215
+ validate.add_argument("--schema", required=True, help="Schema file")
216
+ validate.add_argument("--remote", help="Remote server URL")
217
+ validate.add_argument(
218
+ "--app-name",
219
+ default="default",
220
+ help="Application name for remote server",
221
+ )
222
+ validate.add_argument("--api-key", help="API key for remote server")
223
+
224
+ # Init command
225
+ init = subparsers.add_parser("init", help="Initialize new configuration")
226
+ init.add_argument("config", help="Name of the configuration file to create")
227
+ init.add_argument(
228
+ "--template",
229
+ default="default",
230
+ help=(
231
+ "Configuration template file to use "
232
+ "[empty, web-app, api-service, microservice, default]"
233
+ ),
234
+ )
235
+
236
+ return parser
237
+
238
+
239
+ def create_config(
240
+ config_path: Optional[str] = None,
241
+ schema: Optional[str] = None,
242
+ read_only: bool = False,
243
+ remote_url: Optional[str] = None,
244
+ remote_app_name: Optional[str] = None,
245
+ api_key: Optional[str] = None,
246
+ event: Optional[bool] = False,
247
+ ) -> Nacho:
248
+ """
249
+ Create a Nacho instance from CLI arguments.
250
+ """
251
+ if remote_url:
252
+ if not HAS_REMOTE_DEPS:
253
+ raise ImportError("Remote features require: pip install nacho-python[remote]")
254
+ from nacho.storage.remote import RemoteStorageBackend
255
+
256
+ storage = RemoteStorageBackend(
257
+ url=remote_url,
258
+ app_name=remote_app_name or "default",
259
+ api_key=api_key,
260
+ )
261
+ else:
262
+ storage = config_path or "config.yaml"
263
+
264
+ schema_path = Path(schema) if schema else None
265
+ return Nacho(
266
+ storage=storage,
267
+ schema=schema_path,
268
+ read_only=read_only,
269
+ events=bool(event),
270
+ )
271
+
272
+
273
+ def format_output(value: Any, format_type: str) -> str:
274
+ """
275
+ Format output according to specified format.
276
+ """
277
+ if format_type == "json":
278
+ return json.dumps(value, indent=2)
279
+ elif format_type == "yaml":
280
+
281
+ return yaml.dump(value, default_flow_style=False)
282
+ else: # raw
283
+ return str(value) if not isinstance(value, (dict, list)) else json.dumps(value, indent=2)
284
+
285
+
286
+ def remote_headers(api_key: Optional[str]) -> dict[str, str]:
287
+ headers = {"Content-Type": "application/json"}
288
+ if api_key:
289
+ headers["Authorization"] = f"Bearer {api_key}"
290
+ return headers
291
+
292
+
293
+ def remote_config_url(remote: str, app_name: str, key: Optional[str] = None) -> str:
294
+ base = remote.rstrip("/")
295
+ app = quote(app_name, safe="")
296
+ if key is None:
297
+ return f"{base}/api/apps/{app}/config"
298
+ return f"{base}/api/apps/{app}/config/{quote(key, safe='.')}"
299
+
300
+
301
+ def remote_request_error(response: Any) -> str:
302
+ try:
303
+ payload = response.json()
304
+ except ValueError:
305
+ payload = response.text
306
+ if isinstance(payload, dict) and "detail" in payload:
307
+ return str(payload["detail"])
308
+ return str(payload)
309
+
310
+
311
+ def remote_get(
312
+ remote: str,
313
+ app_name: str,
314
+ api_key: Optional[str],
315
+ key: Optional[str] = None,
316
+ ) -> tuple[Any, Optional[int]]:
317
+ if not HAS_REMOTE_DEPS:
318
+ raise ImportError("Remote features require: pip install nacho-python[remote]")
319
+ import requests
320
+
321
+ response = requests.get(
322
+ remote_config_url(remote, app_name, key),
323
+ headers=remote_headers(api_key),
324
+ timeout=10,
325
+ )
326
+ if response.status_code >= 400:
327
+ raise RuntimeError(remote_request_error(response))
328
+ revision = response.headers.get("X-Nacho-Revision")
329
+ payload = response.json()
330
+ if key is not None:
331
+ return payload.get("value"), None
332
+ return payload, int(revision) if revision and revision.isdigit() else None
333
+
334
+
335
+ def remote_set(
336
+ remote: str,
337
+ app_name: str,
338
+ api_key: Optional[str],
339
+ key: str,
340
+ value: Any,
341
+ revision: Optional[int] = None,
342
+ ) -> int:
343
+ if not HAS_REMOTE_DEPS:
344
+ print("Remote connection requires: pip install nacho-python[remote]")
345
+ return 1
346
+ import requests
347
+
348
+ payload = {"value": value, "type": "raw"}
349
+ if revision is not None:
350
+ payload["revision"] = revision
351
+ response = requests.put(
352
+ remote_config_url(remote, app_name, key),
353
+ json=payload,
354
+ headers=remote_headers(api_key),
355
+ timeout=10,
356
+ )
357
+ if response.status_code >= 400:
358
+ print(f"Error: {remote_request_error(response)}")
359
+ return 1
360
+ body = response.json()
361
+ print(f"Set {key} = {value} (revision {body.get('revision')})")
362
+ return 0
363
+
364
+
365
+ def remote_delete(
366
+ remote: str,
367
+ app_name: str,
368
+ api_key: Optional[str],
369
+ key: str,
370
+ revision: Optional[int] = None,
371
+ ) -> int:
372
+ if not HAS_REMOTE_DEPS:
373
+ print("Remote connection requires: pip install nacho-python[remote]")
374
+ return 1
375
+ import requests
376
+
377
+ params = {"revision": revision} if revision is not None else None
378
+ response = requests.delete(
379
+ remote_config_url(remote, app_name, key),
380
+ params=params,
381
+ headers=remote_headers(api_key),
382
+ timeout=10,
383
+ )
384
+ if response.status_code >= 400:
385
+ print(f"Error: {remote_request_error(response)}")
386
+ return 1
387
+ body = response.json()
388
+ print(f"Deleted {key} (revision {body.get('revision')})")
389
+ return 0
390
+
391
+
392
+ def cmd_server(args: argparse.Namespace) -> int:
393
+ """
394
+ Handle server command.
395
+ """
396
+ if not HAS_SERVER_DEPS:
397
+ print("Server features require: pip install nacho-python[server]")
398
+ return 1
399
+
400
+ print(banner())
401
+
402
+ apps = None
403
+ config: Optional[Nacho] = None
404
+ app_name = args.app_name or "default"
405
+ if args.config:
406
+ config = create_config(
407
+ args.config,
408
+ schema=args.schema,
409
+ api_key=args.api_key,
410
+ read_only=args.read_only,
411
+ event=args.event,
412
+ )
413
+ apps = {app_name: config}
414
+
415
+ orchestrator = NachoOrchestrator(
416
+ apps=apps,
417
+ api_key=args.api_key,
418
+ read_only=args.read_only,
419
+ data_dir=args.data_dir,
420
+ logger=LOGGER,
421
+ )
422
+ orchestrator.run(host=args.host, port=args.port, reload=args.reload)
423
+ return 0
424
+
425
+
426
+ def cmd_connect(args: argparse.Namespace) -> int:
427
+ """
428
+ Connect to a remote configuration server.
429
+ """
430
+
431
+ if not HAS_REMOTE_DEPS:
432
+ print("Remote connection requires: pip install nacho-python[remote]")
433
+ return 1
434
+
435
+ if not args.remote:
436
+ print("Remote URL is required for connection")
437
+ return 1
438
+
439
+ config = create_config(
440
+ remote_url=args.remote, remote_app_name=args.app_name, api_key=args.api_key
441
+ )
442
+
443
+ try:
444
+ config_data = config.get_all()
445
+ print(format_output(config_data, args.format or "json"))
446
+ return 0
447
+ except Exception as e:
448
+ print(f"Error: {e}")
449
+ return 1
450
+
451
+
452
+ def cmd_get(args: argparse.Namespace) -> int:
453
+ """
454
+ Handle get command.
455
+ """
456
+ try:
457
+ if args.remote:
458
+ value, revision = remote_get(
459
+ args.remote,
460
+ args.app_name,
461
+ args.api_key,
462
+ args.key,
463
+ )
464
+ if getattr(args, "show_revision", False):
465
+ value = {"revision": revision, "data": value}
466
+ print(format_output(value, args.format))
467
+ return 0
468
+
469
+ config = create_config(
470
+ args.config,
471
+ remote_url=args.remote,
472
+ remote_app_name=args.app_name,
473
+ api_key=args.api_key,
474
+ )
475
+ if args.key:
476
+ value = config.get(args.key)
477
+ else:
478
+ value = config.get_all()
479
+ print(format_output(value, args.format))
480
+ return 0
481
+ except Exception as e:
482
+ print(f"Error: {e}")
483
+ return 1
484
+
485
+
486
+ def cmd_set(args: argparse.Namespace) -> int:
487
+ """
488
+ Handle set command.
489
+ """
490
+ try:
491
+ parsed_value = parse_value(args.value)
492
+ if args.remote:
493
+ return remote_set(
494
+ args.remote,
495
+ args.app_name,
496
+ args.api_key,
497
+ args.key,
498
+ parsed_value,
499
+ getattr(args, "revision", None),
500
+ )
501
+
502
+ config = create_config(
503
+ args.config,
504
+ schema=args.schema,
505
+ remote_url=args.remote,
506
+ remote_app_name=args.app_name,
507
+ api_key=args.api_key,
508
+ )
509
+ config.set(args.key, parsed_value)
510
+
511
+ config.save()
512
+ print(f"Set {args.key} = {parsed_value}")
513
+ return 0
514
+ except Exception as e:
515
+ print(f"Error: {e}")
516
+ return 1
517
+
518
+
519
+ def cmd_delete(args: argparse.Namespace) -> int:
520
+ """
521
+ Handle delete command.
522
+ """
523
+ try:
524
+ if args.remote:
525
+ return remote_delete(
526
+ args.remote,
527
+ args.app_name,
528
+ args.api_key,
529
+ args.key,
530
+ getattr(args, "revision", None),
531
+ )
532
+
533
+ config = create_config(
534
+ args.config,
535
+ schema=args.schema,
536
+ remote_url=args.remote,
537
+ remote_app_name=args.app_name,
538
+ api_key=args.api_key,
539
+ )
540
+ if config.delete(args.key):
541
+ config.save()
542
+ print(f"Deleted {args.key}")
543
+ else:
544
+ print(f"Key '{args.key}' not found")
545
+ return 0
546
+ except Exception as e:
547
+ print(f"Error: {e}")
548
+ return 1
549
+
550
+
551
+ def cmd_validate(args: argparse.Namespace) -> int:
552
+ """
553
+ Handle validate command.
554
+ """
555
+ if not HAS_SCHEMA_DEPS:
556
+ print("Schema validation requires: pip install nacho-python[schema]")
557
+ return 1
558
+
559
+ try:
560
+ config = create_config(
561
+ args.config,
562
+ schema=args.schema,
563
+ remote_url=args.remote,
564
+ remote_app_name=args.app_name,
565
+ api_key=args.api_key,
566
+ )
567
+ errors = config.validate()
568
+ if errors:
569
+ print("Validation failed:")
570
+ for error in errors:
571
+ print(f" - {error}")
572
+ return 1
573
+ else:
574
+ print("Validation successful")
575
+ return 0
576
+ except Exception as e:
577
+ print(f"Error: {e}")
578
+ return 1
579
+
580
+
581
+ def cmd_init(args: argparse.Namespace) -> int:
582
+ """
583
+ Handle init command.
584
+ """
585
+ try:
586
+ config_path = Path(args.config)
587
+
588
+ if config_path.exists():
589
+ print(f"Configuration file already exists: {config_path}")
590
+ return 1
591
+
592
+ if args.template not in BUILT_IN_TEMPLATES:
593
+ print(
594
+ f"Unknown template '{args.template}'; using 'default'. "
595
+ f"Available: {', '.join(sorted(BUILT_IN_TEMPLATES))}"
596
+ )
597
+ template = BUILT_IN_TEMPLATES.get(args.template, BUILT_IN_TEMPLATES["default"])
598
+ save_file(config_path, template.get("data", {}))
599
+ print(f"Created configuration file: {config_path}")
600
+ return 0
601
+ except Exception as e:
602
+ print(f"Error: {e}")
603
+ return 1
604
+
605
+
606
+ def main_cli() -> int:
607
+ """
608
+ Main CLI entry point.
609
+ """
610
+ parser = create_parser()
611
+
612
+ args = parser.parse_args()
613
+ logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING)
614
+
615
+ if not args.command:
616
+ parser.print_help()
617
+ return 1
618
+
619
+ # Command dispatch
620
+ commands = {
621
+ "server": cmd_server,
622
+ "connect": cmd_connect,
623
+ "get": cmd_get,
624
+ "set": cmd_set,
625
+ "delete": cmd_delete,
626
+ "validate": cmd_validate,
627
+ "init": cmd_init,
628
+ }
629
+
630
+ if args.command in commands:
631
+ return commands[args.command](args)
632
+ else:
633
+ print(f"Unknown command: {args.command}")
634
+ return 1
635
+
636
+
637
+ if __name__ == "__main__":
638
+ sys.exit(main_cli())