HumboldtJoker commited on
Commit
00a42d3
·
verified ·
1 Parent(s): d0be2cc

Clean up nested duplicate: v2/v2/engine/config.py

Browse files
Files changed (1) hide show
  1. v2/v2/engine/config.py +0 -129
v2/v2/engine/config.py DELETED
@@ -1,129 +0,0 @@
1
- """Config loader for kintsugi_config.yaml.
2
-
3
- Uses PyYAML when available. Falls back to a strict-subset parser so the
4
- deployment target needs nothing beyond the stdlib. The subset covers
5
- exactly what kintsugi_config.yaml uses: nested mappings by indentation,
6
- `- item` lists, scalars (str/int/float/bool/null), quoted strings, and
7
- `#` comments. No anchors, no multi-line strings, no flow collections.
8
- """
9
-
10
- from pathlib import Path
11
- from typing import Any
12
-
13
- DEFAULT_CONFIG_PATH = Path(__file__).parent.parent / "kintsugi_config.yaml"
14
-
15
-
16
- def load_config(path: Path | str = DEFAULT_CONFIG_PATH) -> dict:
17
- text = Path(path).read_text()
18
- try:
19
- import yaml
20
- return yaml.safe_load(text)
21
- except ImportError:
22
- return _parse_subset(text)
23
-
24
-
25
- def _scalar(raw: str) -> Any:
26
- raw = raw.strip()
27
- if raw.startswith('"') and raw.endswith('"') and len(raw) >= 2:
28
- return raw[1:-1]
29
- if raw.startswith("'") and raw.endswith("'") and len(raw) >= 2:
30
- return raw[1:-1]
31
- low = raw.lower()
32
- if low in ("true", "yes"):
33
- return True
34
- if low in ("false", "no"):
35
- return False
36
- if low in ("null", "~", ""):
37
- return None
38
- try:
39
- return int(raw)
40
- except ValueError:
41
- pass
42
- try:
43
- return float(raw)
44
- except ValueError:
45
- pass
46
- return raw
47
-
48
-
49
- def _strip_comment(line: str) -> str:
50
- """Remove a trailing comment, respecting quoted strings."""
51
- in_s = in_d = False
52
- for i, ch in enumerate(line):
53
- if ch == "'" and not in_d:
54
- in_s = not in_s
55
- elif ch == '"' and not in_s:
56
- in_d = not in_d
57
- elif ch == "#" and not in_s and not in_d:
58
- return line[:i]
59
- return line
60
-
61
-
62
- def _parse_subset(text: str) -> dict:
63
- # Tokenize into (indent, content) lines, skipping blanks/comments.
64
- lines: list[tuple[int, str]] = []
65
- for raw in text.splitlines():
66
- stripped = _strip_comment(raw).rstrip()
67
- if not stripped.strip():
68
- continue
69
- indent = len(stripped) - len(stripped.lstrip(" "))
70
- lines.append((indent, stripped.strip()))
71
-
72
- root, _ = _parse_block(lines, 0, 0)
73
- return root
74
-
75
-
76
- def _parse_block(lines: list, pos: int, indent: int) -> tuple[Any, int]:
77
- """Parse a block starting at lines[pos] with the given indent level."""
78
- if pos >= len(lines):
79
- return {}, pos
80
-
81
- if lines[pos][1].startswith("- "):
82
- result_list: list = []
83
- while pos < len(lines) and lines[pos][0] == indent and lines[pos][1].startswith("- "):
84
- item = lines[pos][1][2:].strip()
85
- if ":" in item and not item.startswith(("'", '"')):
86
- # list of single-key mappings: "- key: value"
87
- key, _, val = item.partition(":")
88
- entry = {key.strip(): _scalar(val)}
89
- pos += 1
90
- # absorb continuation keys indented under the dash
91
- while pos < len(lines) and lines[pos][0] > indent and not lines[pos][1].startswith("- "):
92
- k, _, v = lines[pos][1].partition(":")
93
- entry[k.strip()] = _scalar(v)
94
- pos += 1
95
- result_list.append(entry)
96
- else:
97
- result_list.append(_scalar(item))
98
- pos += 1
99
- return result_list, pos
100
-
101
- result: dict = {}
102
- while pos < len(lines):
103
- line_indent, content = lines[pos]
104
- if line_indent < indent:
105
- break
106
- if line_indent > indent:
107
- raise ValueError(f"Unexpected indent in config near: {content!r}")
108
- key, sep, val = content.partition(":")
109
- if not sep:
110
- raise ValueError(f"Expected 'key:' in config near: {content!r}")
111
- key = key.strip()
112
- val = val.strip()
113
- if val:
114
- result[key] = _scalar(val)
115
- pos += 1
116
- else:
117
- pos += 1
118
- if pos < len(lines) and lines[pos][0] > indent:
119
- child, pos = _parse_block(lines, pos, lines[pos][0])
120
- result[key] = child
121
- else:
122
- result[key] = None
123
- return result, pos
124
-
125
-
126
- if __name__ == "__main__":
127
- import json
128
- cfg = _parse_subset(Path(DEFAULT_CONFIG_PATH).read_text())
129
- print(json.dumps(cfg, indent=2))