jumbl 0.2.1.dev1__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.
jumbl/_utils.py ADDED
@@ -0,0 +1,46 @@
1
+ # jumbl/_utils.py
2
+ from typing import Any
3
+
4
+
5
+ def unquote(s):
6
+ if (s.startswith('"') and s.endswith('"')) or (
7
+ s.startswith("'") and s.endswith("'")
8
+ ):
9
+ return s[1:-1]
10
+ return s
11
+
12
+
13
+ def resolve_scoped_variable(var_name, data):
14
+ """Resolve a dotted variable name in the configuration AST."""
15
+ parts = var_name.split(".")
16
+ current = data
17
+ for part in parts:
18
+ if isinstance(current, dict):
19
+ current = current.get(part)
20
+ else:
21
+ return None
22
+ return current
23
+
24
+
25
+ # ────────────────────────────────────────────────────────────────
26
+ # ⑥ strip surrounding quotes from plain strings
27
+ def _strip_quotes(obj: Any) -> Any:
28
+ if isinstance(obj, dict):
29
+ return {
30
+ k: _strip_quotes(v) for k, v in obj.items() if k != "__comments__"
31
+ }
32
+ if isinstance(obj, list):
33
+ return [_strip_quotes(v) for v in obj]
34
+ if isinstance(obj, str) and obj.startswith(('"""', "'''")):
35
+ if obj.endswith(obj[:3]):
36
+ return obj[3:-3].strip("\n")
37
+ if (
38
+ isinstance(obj, str)
39
+ and len(obj) >= 2
40
+ and (
41
+ (obj.startswith('"') and obj.endswith('"'))
42
+ or (obj.startswith("'") and obj.endswith("'"))
43
+ )
44
+ ):
45
+ return obj[1:-1]
46
+ return obj
jumbl/api.py ADDED
@@ -0,0 +1,236 @@
1
+ # jumbl/api.py
2
+ import os
3
+ import json
4
+ from typing import IO, Any, Dict
5
+ from lark import UnexpectedToken, UnexpectedCharacters, UnexpectedEOF
6
+
7
+ from ._lark_parser import parser # Assuming lark_parser.py defines parser
8
+ from ._transformer import ConfigTransformer
9
+ from ._config import Config
10
+
11
+ # -------------------------------------
12
+ # 1) File Extension Helper
13
+ # -------------------------------------
14
+
15
+
16
+ def check_extension(filename: str) -> None:
17
+ """
18
+ Ensure the filename has a supported extension (.jml or .jaml).
19
+
20
+ :param filename: Name of the file.
21
+ :raises ValueError: If the extension is not supported.
22
+ """
23
+ ext = os.path.splitext(filename)[1].lower()
24
+ if ext not in (".jml", ".jaml"):
25
+ raise ValueError("Unsupported file extension. Allowed: .jml or .jaml")
26
+
27
+
28
+ # -------------------------------------
29
+ # 2) Non-Round-Trip API
30
+ # -------------------------------------
31
+
32
+
33
+ def dumps(obj: Dict[str, Any]) -> str:
34
+ """
35
+ Serialize a plain Python dict into a minimal JML string (non-round-trip).
36
+ Discards comments, merges, or advanced formatting.
37
+
38
+ :param obj: Dictionary to serialize.
39
+ :return: JML-formatted string.
40
+ """
41
+
42
+ def literal(value):
43
+ if value is None:
44
+ return "null"
45
+ if isinstance(value, bool):
46
+ return "true" if value else "false"
47
+ if isinstance(value, str):
48
+ return json.dumps(value, ensure_ascii=False)
49
+ if isinstance(value, dict):
50
+ return (
51
+ "{ "
52
+ + ", ".join(f"{k} = {literal(v)}" for k, v in value.items())
53
+ + " }"
54
+ )
55
+ if isinstance(value, (list, tuple)):
56
+ return "[" + ", ".join(literal(v) for v in value) + "]"
57
+ if isinstance(value, (int, float)):
58
+ return repr(value)
59
+ raise TypeError(f"Unsupported JAML value: {type(value).__name__}")
60
+
61
+ lines = []
62
+
63
+ def section(values, prefix=""):
64
+ for key, value in values.items():
65
+ if not isinstance(value, dict):
66
+ lines.append(f"{key} = {literal(value)}")
67
+ for key, value in values.items():
68
+ if isinstance(value, dict):
69
+ name = f"{prefix}.{key}" if prefix else key
70
+ lines.extend(["", f"[{name}]"])
71
+ section(value, name)
72
+
73
+ section(obj)
74
+ return "\n".join(lines).lstrip("\n")
75
+
76
+
77
+ def dump(obj: Dict[str, Any], fp: IO[str]) -> None:
78
+ """
79
+ Serialize a plain dict into JML and write to a file-like object
80
+ (non-round-trip).
81
+
82
+ :param obj: Dictionary to serialize.
83
+ :param fp: File-like object to write to.
84
+ """
85
+ fp.write(dumps(obj))
86
+
87
+
88
+ def loads(s: str) -> Dict[str, Any]:
89
+ """
90
+ Parse a JML string into a plain Python dictionary.
91
+
92
+ :param s: JML string to parse.
93
+ :return: Parsed dictionary.
94
+ :raises SyntaxError: If parsing fails.
95
+ """
96
+ try:
97
+ parse_tree = parser.parse(s)
98
+ print("[DEBUG API] loads parse_tree:\n", parse_tree)
99
+ except UnexpectedToken as e:
100
+ raise SyntaxError(
101
+ f"Unexpected token at line {e.line}, column {e.column}: {e}"
102
+ ) from e
103
+ except UnexpectedCharacters as e:
104
+ raise SyntaxError(
105
+ f"Unexpected character at line {e.line}, column {e.column}: {e}"
106
+ ) from e
107
+ except UnexpectedEOF as e:
108
+ raise SyntaxError("Unexpected end of input") from e
109
+
110
+ transformer = ConfigTransformer()
111
+ transformer._context = type("Context", (), {"text": s})
112
+ config = transformer.transform(parse_tree)
113
+ return config.resolve() # Resolve and return plain dictionary
114
+
115
+
116
+ def load(fp: IO[str]) -> Dict[str, Any]:
117
+ """
118
+ Parse JML content from a file-like object into a plain dictionary.
119
+
120
+ :param fp: File-like object to read from.
121
+ :return: Parsed dictionary.
122
+ """
123
+ return loads(fp.read())
124
+
125
+
126
+ # -------------------------------------
127
+ # 3) Round-Trip API
128
+ # -------------------------------------
129
+
130
+
131
+ def round_trip_dumps(config: Config) -> str:
132
+ """
133
+ Serialize a Config object back to a JML-formatted string, preserving
134
+ layout,
135
+ comments, merges, etc., as supported by the unparser.
136
+
137
+ :param config: Config object from round_trip_loads/load.
138
+ :return: JML-formatted string.
139
+ """
140
+ dumped = config.dumps()
141
+ print("[DEBUG API] round_trip_dumps:\n", dumped)
142
+ return dumped
143
+
144
+
145
+ def round_trip_dump(config: Config, fp: IO[str]) -> None:
146
+ """
147
+ Serialize a Config object into JML, writing to a file-like object
148
+ (round-trip).
149
+
150
+ :param config: Config object to serialize.
151
+ :param fp: File-like object to write to.
152
+ """
153
+ fp.write(round_trip_dumps(config))
154
+
155
+
156
+ def round_trip_loads(s: str) -> Config:
157
+ """
158
+ Parse a JML string into a Config object, preserving round-trip data.
159
+
160
+ :param s: JML string to parse.
161
+ :return: Config object.
162
+ :raises SyntaxError: If parsing fails.
163
+ """
164
+ try:
165
+ parse_tree = parser.parse(s)
166
+ print("[DEBUG API] round_trip_loads parse_tree:\n", parse_tree)
167
+ except UnexpectedToken as e:
168
+ raise SyntaxError(
169
+ f"Unexpected token at line {e.line}, column {e.column}: {e}"
170
+ ) from e
171
+ except UnexpectedCharacters as e:
172
+ raise SyntaxError(
173
+ f"Unexpected character at line {e.line}, column {e.column}: {e}"
174
+ ) from e
175
+ except UnexpectedEOF as e:
176
+ raise SyntaxError("Unexpected end of input") from e
177
+
178
+ transformer = ConfigTransformer()
179
+ transformer._context = type("Context", (), {"text": s})
180
+ config = transformer.transform(parse_tree)
181
+ print("[DEBUG API] round_trip_loads config:\n", config)
182
+ return config
183
+
184
+
185
+ def round_trip_load(fp: IO[str]) -> Config:
186
+ """
187
+ Parse JML content from a file-like object into a Config object, preserving
188
+ round-trip data.
189
+
190
+ :param fp: File-like object to read from.
191
+ :return: Config object.
192
+ """
193
+ return round_trip_loads(fp.read())
194
+
195
+
196
+ # -------------------------------------
197
+ # 4) Resolve API
198
+ # -------------------------------------
199
+
200
+
201
+ def resolve(config: Config) -> Config:
202
+ """
203
+ Evaluate all purely static expressions in the Config object, leaving ${...}
204
+ placeholders for the render step.
205
+
206
+ :param config: Config object from round_trip_loads/load.
207
+ :return: Config object with static expressions resolved.
208
+ """
209
+ config.resolve()
210
+ print("[DEBUG API] resolve config:\n", config._data)
211
+ return config
212
+
213
+
214
+ # -------------------------------------
215
+ # 5) Render API
216
+ # -------------------------------------
217
+
218
+
219
+ def render(config: Config, context: Dict[str, Any] = None) -> Dict[str, Any]:
220
+ """
221
+ Substitute deferred ${...} placeholders in the Config object using the
222
+ provided context.
223
+
224
+ :param config: Config object from round_trip_loads/load, preferably
225
+ resolved.
226
+ :param context: Dictionary with context variables (default: empty).
227
+ :return: Rendered dictionary with all placeholders substituted.
228
+ """
229
+ context = context or {}
230
+ if isinstance(config, str):
231
+ from ._legacy import render_source
232
+
233
+ return render_source(config, context, loads(config))
234
+ rendered = config.render(context)
235
+ print("[DEBUG API] render output:\n", rendered)
236
+ return rendered