|
1 | | -"""End-to-end example: parse a Ktav document, inspect, serialize back.""" |
| 1 | +"""End-to-end demo: parse a Ktav document, pull out typed fields, walk |
| 2 | +the dynamic shape, then build a fresh document in Python and render it |
| 3 | +back to Ktav text. |
| 4 | +
|
| 5 | +Run from the repo root: |
| 6 | +
|
| 7 | + pip install -e . # or `pip install ktav` |
| 8 | + python examples/basic.py |
| 9 | +""" |
2 | 10 |
|
3 | 11 | import ktav |
4 | 12 |
|
5 | | -SAMPLE = """ |
6 | | -# a small service config |
| 13 | +SRC = """ |
| 14 | +service: web |
7 | 15 | port:i 8080 |
8 | | -name: frontend |
| 16 | +ratio:f 0.75 |
| 17 | +tls: true |
| 18 | +tags: [ |
| 19 | + prod |
| 20 | + eu-west-1 |
| 21 | +] |
| 22 | +db.host: primary.internal |
| 23 | +db.timeout:i 30 |
| 24 | +""" |
9 | 25 |
|
10 | | -upstreams: [ |
11 | | - { |
12 | | - host: a.example |
13 | | - port:i 1080 |
14 | | - } |
15 | | - { |
16 | | - host: b.example |
17 | | - port:i 1080 |
| 26 | + |
| 27 | +def main() -> None: |
| 28 | + cfg = ktav.loads(SRC) |
| 29 | + |
| 30 | + # ── 1. Read typed fields straight off the dict. ──────────────────── |
| 31 | + service: str = cfg["service"] |
| 32 | + port: int = cfg["port"] |
| 33 | + ratio: float = cfg["ratio"] |
| 34 | + tls: bool = cfg["tls"] |
| 35 | + tags: list[str] = cfg["tags"] |
| 36 | + db_host: str = cfg["db"]["host"] |
| 37 | + db_timeout: int = cfg["db"]["timeout"] |
| 38 | + |
| 39 | + print(f"service={service} port={port} tls={tls} ratio={ratio:.2f}") |
| 40 | + print(f"tags={tags}") |
| 41 | + print(f"db: {db_host} (timeout={db_timeout}s)\n") |
| 42 | + |
| 43 | + # ── 2. Walk the document, dispatching on the runtime type. ───────── |
| 44 | + print("shape:") |
| 45 | + for k, v in cfg.items(): |
| 46 | + print(f" {k:<12} -> {describe(v)}") |
| 47 | + |
| 48 | + # ── 3. Build a config in code, render it as Ktav text. ───────────── |
| 49 | + doc = { |
| 50 | + "name": "frontend", |
| 51 | + "port": 8443, |
| 52 | + "tls": True, |
| 53 | + "ratio": 0.95, |
| 54 | + "upstreams": [ |
| 55 | + upstream("a.example", 1080), |
| 56 | + upstream("b.example", 1080), |
| 57 | + upstream("c.example", 1080), |
| 58 | + ], |
| 59 | + "notes": None, |
18 | 60 | } |
19 | | -] |
| 61 | + rendered = ktav.dumps(doc) |
| 62 | + print("\n--- rendered ---") |
| 63 | + print(rendered, end="") |
20 | 64 |
|
21 | | -# Regex needs the literal-string marker so `[` is not parsed as an array. |
22 | | -ip_allowlist:: [::1] |
23 | 65 |
|
24 | | -timeouts: { |
25 | | - connect:f 1.5 |
26 | | - read:f 30.0 |
27 | | -} |
28 | | -""" |
| 66 | +def describe(v: object) -> str: |
| 67 | + if v is None: |
| 68 | + return "null" |
| 69 | + if isinstance(v, bool): # bool first — `True` is also an `int`! |
| 70 | + return f"bool={v}" |
| 71 | + if isinstance(v, int): |
| 72 | + return f"int={v}" |
| 73 | + if isinstance(v, float): |
| 74 | + return f"float={v}" |
| 75 | + if isinstance(v, str): |
| 76 | + return f"str={v!r}" |
| 77 | + if isinstance(v, list): |
| 78 | + return f"array({len(v)})" |
| 79 | + if isinstance(v, dict): |
| 80 | + return f"object({len(v)})" |
| 81 | + return type(v).__name__ |
29 | 82 |
|
30 | 83 |
|
31 | | -def main() -> None: |
32 | | - cfg = ktav.loads(SAMPLE) |
33 | | - |
34 | | - print("ktav version:", ktav.__version__) |
35 | | - print("spec version:", ktav.__spec_version__) |
36 | | - print() |
37 | | - print(f"Service {cfg['name']!r} on port {cfg['port']}") |
38 | | - print(f" upstreams: {len(cfg['upstreams'])}") |
39 | | - for u in cfg["upstreams"]: |
40 | | - print(f" - {u['host']}:{u['port']}") |
41 | | - print(f" allowlist: {cfg['ip_allowlist']!r}") |
42 | | - print(f" connect timeout: {cfg['timeouts']['connect']}s") |
43 | | - |
44 | | - # Round-trip. |
45 | | - back = ktav.dumps(cfg) |
46 | | - assert ktav.loads(back) == cfg |
47 | | - print() |
48 | | - print("--- re-serialised ---") |
49 | | - print(back) |
| 84 | +def upstream(host: str, port: int) -> dict: |
| 85 | + return {"host": host, "port": port} |
50 | 86 |
|
51 | 87 |
|
52 | 88 | if __name__ == "__main__": |
|
0 commit comments