rosettakit 0.2.0__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.
- rosettakit/__init__.py +5 -0
- rosettakit/cmdfile.py +388 -0
- rosettakit/diagnostics.py +10 -0
- rosettakit/errors.py +32 -0
- rosettakit/py.typed +0 -0
- rosettakit/tcl.py +499 -0
- rosettakit-0.2.0.dist-info/METADATA +121 -0
- rosettakit-0.2.0.dist-info/RECORD +10 -0
- rosettakit-0.2.0.dist-info/WHEEL +4 -0
- rosettakit-0.2.0.dist-info/licenses/LICENSE +201 -0
rosettakit/__init__.py
ADDED
rosettakit/cmdfile.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from typing import TypeAlias
|
|
7
|
+
|
|
8
|
+
from rosettakit.diagnostics import Diagnostic
|
|
9
|
+
from rosettakit.errors import BuildError, UnsafeRawError, ValidationError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
CommandFileValue: TypeAlias = object
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ValueType(Enum):
|
|
16
|
+
"""Value category used for command-file validation diagnostics."""
|
|
17
|
+
|
|
18
|
+
SCALAR = "scalar"
|
|
19
|
+
PATH = "path"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ValueQuoting(Enum):
|
|
23
|
+
"""Policy used to validate and render command-file option values."""
|
|
24
|
+
|
|
25
|
+
TCL_WORD = "tcl-word"
|
|
26
|
+
PLAIN_UNQUOTED = "plain-unquoted"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class CommandFileDialect:
|
|
31
|
+
"""Named command-file dialect describing how option values are represented."""
|
|
32
|
+
|
|
33
|
+
name: str
|
|
34
|
+
value_quoting: ValueQuoting
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
TCL_WORD_DIALECT = CommandFileDialect(
|
|
38
|
+
name="tcl-word",
|
|
39
|
+
value_quoting=ValueQuoting.TCL_WORD,
|
|
40
|
+
)
|
|
41
|
+
"""Default command-file dialect using Tcl-word-like quoting for option values."""
|
|
42
|
+
|
|
43
|
+
PLAIN_DIALECT = CommandFileDialect(
|
|
44
|
+
name="plain",
|
|
45
|
+
value_quoting=ValueQuoting.PLAIN_UNQUOTED,
|
|
46
|
+
)
|
|
47
|
+
"""Whitespace-delimited command-file dialect that rejects values needing quoting."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Comment:
|
|
52
|
+
"""A command-file comment node."""
|
|
53
|
+
|
|
54
|
+
text: str
|
|
55
|
+
origin: str | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class BlankLine:
|
|
60
|
+
"""A blank command-file output line."""
|
|
61
|
+
|
|
62
|
+
origin: str | None = None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class Flag:
|
|
67
|
+
"""A command-file flag node rendered without a value."""
|
|
68
|
+
|
|
69
|
+
name: str
|
|
70
|
+
origin: str | None = None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class Option:
|
|
75
|
+
"""A command-file option node rendered with one value."""
|
|
76
|
+
|
|
77
|
+
name: str
|
|
78
|
+
value: CommandFileValue
|
|
79
|
+
value_type: ValueType
|
|
80
|
+
omit_empty: bool
|
|
81
|
+
origin: str | None = None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class RawLine:
|
|
86
|
+
"""A raw command-file line that requires explicit build opt-in."""
|
|
87
|
+
|
|
88
|
+
text: str
|
|
89
|
+
origin: str | None = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
CommandFileNode: TypeAlias = Comment | BlankLine | Flag | Option | RawLine
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class CommandFile:
|
|
96
|
+
"""Mutable command-file document that preserves insertion order."""
|
|
97
|
+
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
*,
|
|
101
|
+
prefix: str = "-",
|
|
102
|
+
dialect: CommandFileDialect = TCL_WORD_DIALECT,
|
|
103
|
+
) -> None:
|
|
104
|
+
"""Create an empty command-file document.
|
|
105
|
+
|
|
106
|
+
`prefix` is prepended to flags and option names. Use `prefix=""` for
|
|
107
|
+
command-like env files that do not use dashed option names. `dialect`
|
|
108
|
+
controls validation and rendering for option values.
|
|
109
|
+
"""
|
|
110
|
+
self.prefix = prefix
|
|
111
|
+
self.dialect = dialect
|
|
112
|
+
self._nodes: list[CommandFileNode] = []
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def nodes(self) -> tuple[CommandFileNode, ...]:
|
|
116
|
+
"""Return an immutable snapshot of command-file nodes."""
|
|
117
|
+
return tuple(self._nodes)
|
|
118
|
+
|
|
119
|
+
def comment(self, text: str, *, origin: str | None = None) -> None:
|
|
120
|
+
"""Append one or more comment lines.
|
|
121
|
+
|
|
122
|
+
Newline-separated text is emitted as separate comment lines. `origin` is
|
|
123
|
+
attached to diagnostics produced from this node.
|
|
124
|
+
"""
|
|
125
|
+
self._nodes.append(Comment(text, origin))
|
|
126
|
+
|
|
127
|
+
def blank_line(self, *, origin: str | None = None) -> None:
|
|
128
|
+
"""Append a blank line to the command file."""
|
|
129
|
+
self._nodes.append(BlankLine(origin))
|
|
130
|
+
|
|
131
|
+
def flag(self, name: str, *, origin: str | None = None) -> None:
|
|
132
|
+
"""Append a flag line such as `-useOpenSTA`."""
|
|
133
|
+
self._nodes.append(Flag(name, origin))
|
|
134
|
+
|
|
135
|
+
def option(
|
|
136
|
+
self,
|
|
137
|
+
name: str,
|
|
138
|
+
value: CommandFileValue,
|
|
139
|
+
*,
|
|
140
|
+
value_type: ValueType = ValueType.SCALAR,
|
|
141
|
+
omit_empty: bool = False,
|
|
142
|
+
origin: str | None = None,
|
|
143
|
+
) -> None:
|
|
144
|
+
"""Append one option line with a dialect-rendered value.
|
|
145
|
+
|
|
146
|
+
Set `value_type=ValueType.PATH` for filesystem paths so validation can
|
|
147
|
+
report empty paths and path quoting diagnostics. `omit_empty=True`
|
|
148
|
+
suppresses the line when the value is an empty string.
|
|
149
|
+
"""
|
|
150
|
+
self._nodes.append(Option(name, value, value_type, omit_empty, origin))
|
|
151
|
+
|
|
152
|
+
def options(
|
|
153
|
+
self,
|
|
154
|
+
name: str,
|
|
155
|
+
values: Iterable[CommandFileValue],
|
|
156
|
+
*,
|
|
157
|
+
value_type: ValueType = ValueType.SCALAR,
|
|
158
|
+
omit_empty: bool = False,
|
|
159
|
+
origin: str | None = None,
|
|
160
|
+
) -> None:
|
|
161
|
+
"""Append one option line for each value in `values`."""
|
|
162
|
+
for value in values:
|
|
163
|
+
self.option(
|
|
164
|
+
name,
|
|
165
|
+
value,
|
|
166
|
+
value_type=value_type,
|
|
167
|
+
omit_empty=omit_empty,
|
|
168
|
+
origin=origin,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
def raw_line(self, text: str, *, origin: str | None = None) -> None:
|
|
172
|
+
"""Append a raw command-file line that bypasses escaping.
|
|
173
|
+
|
|
174
|
+
Raw lines are an escape hatch for hand-written output. Builds fail on
|
|
175
|
+
raw content unless `allow_unsafe_raw=True` is passed.
|
|
176
|
+
"""
|
|
177
|
+
self._nodes.append(RawLine(text, origin))
|
|
178
|
+
|
|
179
|
+
def validate(self) -> list[Diagnostic]:
|
|
180
|
+
"""Return diagnostics for this command file without rendering text."""
|
|
181
|
+
return CommandFileBuilder().validate(self)
|
|
182
|
+
|
|
183
|
+
def build(self, *, allow_unsafe_raw: bool = False) -> str:
|
|
184
|
+
"""Validate and render this command file as text.
|
|
185
|
+
|
|
186
|
+
Raises `ValidationError` for blocking diagnostics and `UnsafeRawError`
|
|
187
|
+
when raw content is present without `allow_unsafe_raw=True`.
|
|
188
|
+
"""
|
|
189
|
+
return CommandFileBuilder(allow_unsafe_raw=allow_unsafe_raw).build(self)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class CommandFileBuilder:
|
|
193
|
+
"""Renderer and validator for RosettaKit command-file documents."""
|
|
194
|
+
|
|
195
|
+
backend = "command-file"
|
|
196
|
+
|
|
197
|
+
def __init__(self, *, allow_unsafe_raw: bool = False) -> None:
|
|
198
|
+
"""Create a command-file builder with the requested raw-content policy."""
|
|
199
|
+
self.allow_unsafe_raw = allow_unsafe_raw
|
|
200
|
+
|
|
201
|
+
def build(self, document: CommandFile) -> str:
|
|
202
|
+
"""Validate and render a `CommandFile` into text."""
|
|
203
|
+
diagnostics = self.validate(document)
|
|
204
|
+
raw_diagnostics = [item for item in diagnostics if item.code == "unsafe-raw"]
|
|
205
|
+
blocking = [item for item in diagnostics if item.code not in {"unsafe-raw", "quoted-path"}]
|
|
206
|
+
if raw_diagnostics and not self.allow_unsafe_raw:
|
|
207
|
+
raise UnsafeRawError(self.backend, raw_diagnostics)
|
|
208
|
+
if blocking:
|
|
209
|
+
raise ValidationError(self.backend, blocking)
|
|
210
|
+
return "".join(
|
|
211
|
+
self._render_node(document.prefix, document.dialect, node) for node in document.nodes
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def validate(self, document: CommandFile) -> list[Diagnostic]:
|
|
215
|
+
"""Return diagnostics for a `CommandFile` without rendering text."""
|
|
216
|
+
diagnostics: list[Diagnostic] = []
|
|
217
|
+
if not _is_supported_dialect(document.dialect):
|
|
218
|
+
diagnostics.append(
|
|
219
|
+
Diagnostic(
|
|
220
|
+
"unsupported-command-file-dialect",
|
|
221
|
+
f"unsupported command-file dialect: {document.dialect.name}",
|
|
222
|
+
)
|
|
223
|
+
)
|
|
224
|
+
for node in document.nodes:
|
|
225
|
+
diagnostics.extend(self._validate_node(document.dialect, node))
|
|
226
|
+
return diagnostics
|
|
227
|
+
|
|
228
|
+
def _render_node(
|
|
229
|
+
self,
|
|
230
|
+
prefix: str,
|
|
231
|
+
dialect: CommandFileDialect,
|
|
232
|
+
node: CommandFileNode,
|
|
233
|
+
) -> str:
|
|
234
|
+
if isinstance(node, Comment):
|
|
235
|
+
return "".join(f"# {line}\n" for line in _comment_lines(node.text))
|
|
236
|
+
if isinstance(node, BlankLine):
|
|
237
|
+
return "\n"
|
|
238
|
+
if isinstance(node, Flag):
|
|
239
|
+
return f"{prefix}{node.name}\n"
|
|
240
|
+
if isinstance(node, Option):
|
|
241
|
+
if node.omit_empty and node.value == "":
|
|
242
|
+
return ""
|
|
243
|
+
return f"{prefix}{node.name} {self._render_option_value(dialect, node.value)}\n"
|
|
244
|
+
if isinstance(node, RawLine):
|
|
245
|
+
return f"{node.text}\n"
|
|
246
|
+
raise BuildError(f"unsupported command-file node: {node!r}")
|
|
247
|
+
|
|
248
|
+
def _render_option_value(self, dialect: CommandFileDialect, value: object) -> str:
|
|
249
|
+
text = str(value)
|
|
250
|
+
if dialect.value_quoting is ValueQuoting.TCL_WORD:
|
|
251
|
+
return _quote_word(text)
|
|
252
|
+
if dialect.value_quoting is ValueQuoting.PLAIN_UNQUOTED:
|
|
253
|
+
return text
|
|
254
|
+
raise BuildError(f"unsupported command-file dialect: {dialect.name}")
|
|
255
|
+
|
|
256
|
+
def _validate_node(
|
|
257
|
+
self,
|
|
258
|
+
dialect: CommandFileDialect,
|
|
259
|
+
node: CommandFileNode,
|
|
260
|
+
) -> list[Diagnostic]:
|
|
261
|
+
diagnostics: list[Diagnostic] = []
|
|
262
|
+
if isinstance(node, Flag):
|
|
263
|
+
if not node.name:
|
|
264
|
+
diagnostics.append(
|
|
265
|
+
Diagnostic("empty-option-name", "flag name is required", node.origin)
|
|
266
|
+
)
|
|
267
|
+
elif isinstance(node, Option):
|
|
268
|
+
diagnostics.extend(self._validate_option(dialect, node))
|
|
269
|
+
elif isinstance(node, RawLine):
|
|
270
|
+
diagnostics.append(
|
|
271
|
+
Diagnostic(
|
|
272
|
+
"unsafe-raw",
|
|
273
|
+
"raw command-file line requires explicit opt-in",
|
|
274
|
+
node.origin,
|
|
275
|
+
)
|
|
276
|
+
)
|
|
277
|
+
elif isinstance(node, (Comment, BlankLine)):
|
|
278
|
+
pass
|
|
279
|
+
else:
|
|
280
|
+
diagnostics.append(
|
|
281
|
+
Diagnostic(
|
|
282
|
+
"unsupported-node",
|
|
283
|
+
f"unsupported command-file node {type(node).__name__}",
|
|
284
|
+
)
|
|
285
|
+
)
|
|
286
|
+
return diagnostics
|
|
287
|
+
|
|
288
|
+
def _validate_option(
|
|
289
|
+
self,
|
|
290
|
+
dialect: CommandFileDialect,
|
|
291
|
+
node: Option,
|
|
292
|
+
) -> list[Diagnostic]:
|
|
293
|
+
diagnostics: list[Diagnostic] = []
|
|
294
|
+
text = str(node.value)
|
|
295
|
+
if not node.name:
|
|
296
|
+
diagnostics.append(
|
|
297
|
+
Diagnostic("empty-option-name", "option name is required", node.origin)
|
|
298
|
+
)
|
|
299
|
+
if _has_line_break(text):
|
|
300
|
+
diagnostics.append(
|
|
301
|
+
Diagnostic(
|
|
302
|
+
"line-break-in-value",
|
|
303
|
+
"command-file values cannot contain line breaks",
|
|
304
|
+
node.origin,
|
|
305
|
+
)
|
|
306
|
+
)
|
|
307
|
+
if node.value_type is ValueType.PATH and node.value == "" and not node.omit_empty:
|
|
308
|
+
diagnostics.append(Diagnostic("empty-path", "path value is required", node.origin))
|
|
309
|
+
if dialect.value_quoting is ValueQuoting.TCL_WORD:
|
|
310
|
+
diagnostics.extend(_validate_tcl_word_option(node, text))
|
|
311
|
+
elif dialect.value_quoting is ValueQuoting.PLAIN_UNQUOTED:
|
|
312
|
+
diagnostics.extend(_validate_plain_option(node, text))
|
|
313
|
+
return diagnostics
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _quote_word(text: str) -> str:
|
|
317
|
+
if text == "":
|
|
318
|
+
return "{}"
|
|
319
|
+
if not _needs_quoting(text):
|
|
320
|
+
return text
|
|
321
|
+
if "{" not in text and "}" not in text and "\n" not in text and "\r" not in text:
|
|
322
|
+
return "{" + text + "}"
|
|
323
|
+
return "".join(_escape_word_char(char) for char in text)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _needs_quoting(text: str) -> bool:
|
|
327
|
+
return text == "" or any(char.isspace() or char in "{}[]$;\\\"" for char in text)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _escape_word_char(char: str) -> str:
|
|
331
|
+
replacements = {
|
|
332
|
+
" ": "\\ ",
|
|
333
|
+
"\t": "\\t",
|
|
334
|
+
"\r": "\\r",
|
|
335
|
+
"\n": "\\n",
|
|
336
|
+
"\\": "\\\\",
|
|
337
|
+
"{": "\\{",
|
|
338
|
+
"}": "\\}",
|
|
339
|
+
"[": "\\[",
|
|
340
|
+
"]": "\\]",
|
|
341
|
+
"$": "\\$",
|
|
342
|
+
";": "\\;",
|
|
343
|
+
'"': '\\"',
|
|
344
|
+
}
|
|
345
|
+
return replacements.get(char, char)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _has_line_break(text: str) -> bool:
|
|
349
|
+
return "\n" in text or "\r" in text
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _comment_lines(text: str) -> list[str]:
|
|
353
|
+
return text.splitlines() or [""]
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _validate_tcl_word_option(node: Option, text: str) -> list[Diagnostic]:
|
|
357
|
+
if node.value_type is ValueType.PATH and text != "" and _needs_quoting(text):
|
|
358
|
+
return [Diagnostic("quoted-path", "path requires command-file quoting", node.origin)]
|
|
359
|
+
return []
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _validate_plain_option(node: Option, text: str) -> list[Diagnostic]:
|
|
363
|
+
if node.omit_empty and node.value == "":
|
|
364
|
+
return []
|
|
365
|
+
if node.value_type is ValueType.SCALAR and text == "":
|
|
366
|
+
return [
|
|
367
|
+
Diagnostic(
|
|
368
|
+
"empty-unquoted-value",
|
|
369
|
+
"empty values cannot be represented as plain whitespace-delimited tokens",
|
|
370
|
+
node.origin,
|
|
371
|
+
)
|
|
372
|
+
]
|
|
373
|
+
if text != "" and not _has_line_break(text) and _needs_quoting(text):
|
|
374
|
+
return [
|
|
375
|
+
Diagnostic(
|
|
376
|
+
"unquoted-value-needs-quoting",
|
|
377
|
+
"plain command-file values cannot contain whitespace or quoting characters",
|
|
378
|
+
node.origin,
|
|
379
|
+
)
|
|
380
|
+
]
|
|
381
|
+
return []
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _is_supported_dialect(dialect: CommandFileDialect) -> bool:
|
|
385
|
+
return dialect.value_quoting in {
|
|
386
|
+
ValueQuoting.TCL_WORD,
|
|
387
|
+
ValueQuoting.PLAIN_UNQUOTED,
|
|
388
|
+
}
|
rosettakit/errors.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
|
|
5
|
+
from rosettakit.diagnostics import Diagnostic
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ScriptDslError(Exception):
|
|
9
|
+
"""Base class for RosettaKit script DSL errors."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ValidationError(ScriptDslError):
|
|
13
|
+
def __init__(self, backend: str, diagnostics: Sequence[Diagnostic]) -> None:
|
|
14
|
+
self.backend = backend
|
|
15
|
+
self.diagnostics = tuple(diagnostics)
|
|
16
|
+
details = "; ".join(_format_diagnostic(item) for item in self.diagnostics)
|
|
17
|
+
super().__init__(f"{backend} validation failed: {details}")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class BuildError(ScriptDslError):
|
|
21
|
+
"""Raised when a builder cannot render a document."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class UnsafeRawError(ValidationError):
|
|
25
|
+
def __init__(self, backend: str, diagnostics: Sequence[Diagnostic]) -> None:
|
|
26
|
+
super().__init__(backend, diagnostics)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _format_diagnostic(diagnostic: Diagnostic) -> str:
|
|
30
|
+
if diagnostic.origin:
|
|
31
|
+
return f"{diagnostic.code} at {diagnostic.origin}: {diagnostic.message}"
|
|
32
|
+
return f"{diagnostic.code}: {diagnostic.message}"
|
rosettakit/py.typed
ADDED
|
File without changes
|
rosettakit/tcl.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable, Iterator
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import TypeAlias
|
|
7
|
+
|
|
8
|
+
from rosettakit.diagnostics import Diagnostic
|
|
9
|
+
from rosettakit.errors import BuildError, UnsafeRawError, ValidationError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
TclInputValue: TypeAlias = object
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Scalar:
|
|
17
|
+
"""A scalar Tcl value rendered as one safely quoted word."""
|
|
18
|
+
|
|
19
|
+
value: TclInputValue
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class PathValue:
|
|
24
|
+
"""A Tcl value that represents a filesystem path."""
|
|
25
|
+
|
|
26
|
+
value: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class ListValue:
|
|
31
|
+
"""A Tcl list value rendered with the Tcl `list` command."""
|
|
32
|
+
|
|
33
|
+
values: tuple[TclInputValue, ...]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class VarRef:
|
|
38
|
+
"""A reference to a Tcl variable rendered as `$name`."""
|
|
39
|
+
|
|
40
|
+
name: str
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Expr:
|
|
45
|
+
"""A Tcl expression rendered as `[expr {...}]`."""
|
|
46
|
+
|
|
47
|
+
expression: str
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class CommandSubstitution:
|
|
52
|
+
"""A Tcl command substitution rendered as `[command arg ...]`."""
|
|
53
|
+
|
|
54
|
+
command: str
|
|
55
|
+
args: tuple[TclInputValue, ...]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class Raw:
|
|
60
|
+
"""Raw Tcl text that bypasses escaping and requires explicit build opt-in."""
|
|
61
|
+
|
|
62
|
+
text: str
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
TclValue: TypeAlias = Scalar | PathValue | ListValue | VarRef | Expr | CommandSubstitution | Raw
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class Condition:
|
|
70
|
+
"""A rendered Tcl condition plus diagnostics for values used to build it."""
|
|
71
|
+
|
|
72
|
+
text: str
|
|
73
|
+
diagnostics: tuple[Diagnostic, ...] = ()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class Comment:
|
|
78
|
+
"""A Tcl comment node."""
|
|
79
|
+
|
|
80
|
+
text: str
|
|
81
|
+
origin: str | None = None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class BlankLine:
|
|
86
|
+
"""A blank Tcl output line."""
|
|
87
|
+
|
|
88
|
+
origin: str | None = None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class Set:
|
|
93
|
+
"""A Tcl `set` command node."""
|
|
94
|
+
|
|
95
|
+
name: str
|
|
96
|
+
value: TclValue
|
|
97
|
+
scalar_api: bool = True
|
|
98
|
+
origin: str | None = None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class Command:
|
|
103
|
+
"""A generic Tcl command node."""
|
|
104
|
+
|
|
105
|
+
name: str
|
|
106
|
+
args: tuple[TclValue, ...]
|
|
107
|
+
origin: str | None = None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(frozen=True)
|
|
111
|
+
class If:
|
|
112
|
+
"""A Tcl `if` node with a nested body."""
|
|
113
|
+
|
|
114
|
+
condition: Condition
|
|
115
|
+
body: list[TclNode]
|
|
116
|
+
origin: str | None = None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass(frozen=True)
|
|
120
|
+
class RawLine:
|
|
121
|
+
"""A raw Tcl line that bypasses escaping and requires explicit build opt-in."""
|
|
122
|
+
|
|
123
|
+
text: str
|
|
124
|
+
origin: str | None = None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
TclNode: TypeAlias = Comment | BlankLine | Set | Command | If | RawLine
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def word(value: TclInputValue) -> Scalar:
|
|
131
|
+
"""Create a scalar Tcl word that RosettaKit quotes safely when rendered.
|
|
132
|
+
|
|
133
|
+
Use this for single Tcl values passed to `Script.set` or command arguments.
|
|
134
|
+
Non-string Python values are converted with `str(...)` during rendering.
|
|
135
|
+
"""
|
|
136
|
+
return Scalar(value)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def path(value: str) -> PathValue:
|
|
140
|
+
"""Create a filesystem path value for Tcl output.
|
|
141
|
+
|
|
142
|
+
Path values render as one safely quoted Tcl word and participate in path
|
|
143
|
+
diagnostics such as empty-path and quoted-path warnings.
|
|
144
|
+
"""
|
|
145
|
+
return PathValue(value)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def list_value(values: Iterable[TclInputValue]) -> ListValue:
|
|
149
|
+
"""Create a Tcl list value rendered as `[list item ...]`.
|
|
150
|
+
|
|
151
|
+
Prefer `Script.set_list` when assigning a variable to a Tcl list. This helper
|
|
152
|
+
is useful when a list must be passed as a value object.
|
|
153
|
+
"""
|
|
154
|
+
return ListValue(tuple(values))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def var(name: str) -> VarRef:
|
|
158
|
+
"""Reference an existing Tcl variable as `$name`.
|
|
159
|
+
|
|
160
|
+
The variable name is inserted without quoting; empty names are reported by
|
|
161
|
+
validation and rejected during rendering.
|
|
162
|
+
"""
|
|
163
|
+
return VarRef(name)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def expr(expression: str) -> Expr:
|
|
167
|
+
"""Create a Tcl expression substitution rendered as `[expr {...}]`.
|
|
168
|
+
|
|
169
|
+
The expression text is inserted into the braced Tcl expression body. Pass
|
|
170
|
+
trusted expression text rather than unescaped user input.
|
|
171
|
+
"""
|
|
172
|
+
return Expr(expression)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def call(command: str, *args: TclInputValue) -> CommandSubstitution:
|
|
176
|
+
"""Create a Tcl command substitution rendered as `[command arg ...]`.
|
|
177
|
+
|
|
178
|
+
Arguments are rendered through RosettaKit value quoting. The command name is
|
|
179
|
+
used as provided, so keep it controlled by the caller.
|
|
180
|
+
"""
|
|
181
|
+
return CommandSubstitution(command, args)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def raw(text: str) -> Raw:
|
|
185
|
+
"""Create raw Tcl value text that bypasses all escaping.
|
|
186
|
+
|
|
187
|
+
Raw values are an escape hatch for hand-written Tcl snippets. Builds fail on
|
|
188
|
+
raw content unless `allow_unsafe_raw=True` is passed.
|
|
189
|
+
"""
|
|
190
|
+
return Raw(text)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def file_isdirectory(value: TclInputValue) -> Condition:
|
|
194
|
+
"""Create a Tcl condition for `[file isdirectory value]`.
|
|
195
|
+
|
|
196
|
+
The value is rendered with RosettaKit quoting and any value diagnostics are
|
|
197
|
+
carried into the condition for later validation.
|
|
198
|
+
"""
|
|
199
|
+
diagnostics = tuple(_validate_value(value, origin=None, scalar_api=False))
|
|
200
|
+
return Condition(f"[file isdirectory {TclBuilder().render_value(value)}]", diagnostics)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class Script:
|
|
204
|
+
"""Mutable Tcl script document that preserves insertion order."""
|
|
205
|
+
|
|
206
|
+
def __init__(self) -> None:
|
|
207
|
+
"""Create an empty Tcl script document."""
|
|
208
|
+
self._nodes: list[TclNode] = []
|
|
209
|
+
self._stack: list[list[TclNode]] = [self._nodes]
|
|
210
|
+
|
|
211
|
+
@property
|
|
212
|
+
def nodes(self) -> tuple[TclNode, ...]:
|
|
213
|
+
"""Return an immutable snapshot of top-level Tcl nodes."""
|
|
214
|
+
return tuple(self._nodes)
|
|
215
|
+
|
|
216
|
+
def comment(self, text: str, *, origin: str | None = None) -> None:
|
|
217
|
+
"""Append one or more Tcl comment lines.
|
|
218
|
+
|
|
219
|
+
Newline-separated text is emitted as separate comment lines. `origin` is
|
|
220
|
+
attached to diagnostics produced from this node.
|
|
221
|
+
"""
|
|
222
|
+
self._current().append(Comment(text, origin))
|
|
223
|
+
|
|
224
|
+
def blank_line(self, *, origin: str | None = None) -> None:
|
|
225
|
+
"""Append a blank line to the script."""
|
|
226
|
+
self._current().append(BlankLine(origin))
|
|
227
|
+
|
|
228
|
+
def set(self, name: str, value: TclInputValue, *, origin: str | None = None) -> None:
|
|
229
|
+
"""Append a Tcl `set name value` command.
|
|
230
|
+
|
|
231
|
+
Scalar values are quoted as one Tcl word. Use `set_list` for Tcl lists so
|
|
232
|
+
validation can distinguish list assignment from scalar assignment.
|
|
233
|
+
"""
|
|
234
|
+
self._current().append(Set(name, _coerce_value(value), True, origin))
|
|
235
|
+
|
|
236
|
+
def set_path(self, name: str, value: str, *, origin: str | None = None) -> None:
|
|
237
|
+
"""Append a Tcl `set` command whose value represents a filesystem path."""
|
|
238
|
+
self.set(name, path(value), origin=origin)
|
|
239
|
+
|
|
240
|
+
def set_list(
|
|
241
|
+
self,
|
|
242
|
+
name: str,
|
|
243
|
+
values: Iterable[TclInputValue],
|
|
244
|
+
*,
|
|
245
|
+
origin: str | None = None,
|
|
246
|
+
) -> None:
|
|
247
|
+
"""Append a Tcl `set` command whose value is rendered as a Tcl list."""
|
|
248
|
+
self._current().append(Set(name, list_value(values), False, origin))
|
|
249
|
+
|
|
250
|
+
def set_expr(self, name: str, expression: str, *, origin: str | None = None) -> None:
|
|
251
|
+
"""Append a Tcl `set` command whose value is rendered as `[expr {...}]`."""
|
|
252
|
+
self.set(name, expr(expression), origin=origin)
|
|
253
|
+
|
|
254
|
+
def command(self, name: str, *args: TclInputValue, origin: str | None = None) -> None:
|
|
255
|
+
"""Append a generic Tcl command with safely rendered arguments.
|
|
256
|
+
|
|
257
|
+
The command name is emitted as provided. Each argument is converted to a
|
|
258
|
+
RosettaKit value and rendered as one Tcl word or value expression.
|
|
259
|
+
"""
|
|
260
|
+
self._current().append(Command(name, tuple(_coerce_value(arg) for arg in args), origin))
|
|
261
|
+
|
|
262
|
+
def file_mkdir(self, value: TclInputValue, *, origin: str | None = None) -> None:
|
|
263
|
+
"""Append `file mkdir value` with the directory value safely rendered."""
|
|
264
|
+
self.command("file", "mkdir", value, origin=origin)
|
|
265
|
+
|
|
266
|
+
@contextmanager
|
|
267
|
+
def if_not(self, condition: Condition, *, origin: str | None = None) -> Iterator[Script]:
|
|
268
|
+
"""Append an `if {!(condition)}` block and yield this script for its body."""
|
|
269
|
+
body: list[TclNode] = []
|
|
270
|
+
self._current().append(
|
|
271
|
+
If(Condition(f"!({condition.text})", condition.diagnostics), body, origin)
|
|
272
|
+
)
|
|
273
|
+
self._stack.append(body)
|
|
274
|
+
try:
|
|
275
|
+
yield self
|
|
276
|
+
finally:
|
|
277
|
+
self._stack.pop()
|
|
278
|
+
|
|
279
|
+
def raw_line(self, text: str, *, origin: str | None = None) -> None:
|
|
280
|
+
"""Append a raw Tcl line that bypasses escaping.
|
|
281
|
+
|
|
282
|
+
Raw lines are an escape hatch for hand-written Tcl. Builds fail on raw
|
|
283
|
+
content unless `allow_unsafe_raw=True` is passed.
|
|
284
|
+
"""
|
|
285
|
+
self._current().append(RawLine(text, origin))
|
|
286
|
+
|
|
287
|
+
def validate(self) -> list[Diagnostic]:
|
|
288
|
+
"""Return diagnostics for this script without rendering text."""
|
|
289
|
+
return TclBuilder().validate(self)
|
|
290
|
+
|
|
291
|
+
def build(self, *, allow_unsafe_raw: bool = False) -> str:
|
|
292
|
+
"""Validate and render this script as Tcl text.
|
|
293
|
+
|
|
294
|
+
Raises `ValidationError` for blocking diagnostics and `UnsafeRawError`
|
|
295
|
+
when raw content is present without `allow_unsafe_raw=True`.
|
|
296
|
+
"""
|
|
297
|
+
return TclBuilder(allow_unsafe_raw=allow_unsafe_raw).build(self)
|
|
298
|
+
|
|
299
|
+
def _current(self) -> list[TclNode]:
|
|
300
|
+
return self._stack[-1]
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
class TclBuilder:
|
|
304
|
+
"""Renderer and validator for RosettaKit Tcl scripts."""
|
|
305
|
+
|
|
306
|
+
backend = "tcl"
|
|
307
|
+
|
|
308
|
+
def __init__(self, *, indent: str = " ", allow_unsafe_raw: bool = False) -> None:
|
|
309
|
+
"""Create a Tcl builder with indentation and raw-content policy."""
|
|
310
|
+
self.indent = indent
|
|
311
|
+
self.allow_unsafe_raw = allow_unsafe_raw
|
|
312
|
+
|
|
313
|
+
def build(self, script: Script) -> str:
|
|
314
|
+
"""Validate and render a `Script` into Tcl text."""
|
|
315
|
+
diagnostics = self.validate(script)
|
|
316
|
+
raw_diagnostics = [item for item in diagnostics if item.code == "unsafe-raw"]
|
|
317
|
+
blocking = [item for item in diagnostics if item.code not in {"unsafe-raw", "quoted-path"}]
|
|
318
|
+
if raw_diagnostics and not self.allow_unsafe_raw:
|
|
319
|
+
raise UnsafeRawError(self.backend, raw_diagnostics)
|
|
320
|
+
if blocking:
|
|
321
|
+
raise ValidationError(self.backend, blocking)
|
|
322
|
+
return "".join(self._render_node(node, level=0) for node in script.nodes)
|
|
323
|
+
|
|
324
|
+
def validate(self, script: Script) -> list[Diagnostic]:
|
|
325
|
+
"""Return diagnostics for a `Script` without rendering text."""
|
|
326
|
+
diagnostics: list[Diagnostic] = []
|
|
327
|
+
for node in script.nodes:
|
|
328
|
+
diagnostics.extend(self._validate_node(node))
|
|
329
|
+
return diagnostics
|
|
330
|
+
|
|
331
|
+
def render_value(self, value: TclInputValue) -> str:
|
|
332
|
+
"""Render one Tcl input value as Tcl text."""
|
|
333
|
+
value = _coerce_value(value)
|
|
334
|
+
if isinstance(value, Scalar):
|
|
335
|
+
return _quote_tcl_word(str(value.value))
|
|
336
|
+
if isinstance(value, PathValue):
|
|
337
|
+
return _quote_tcl_word(value.value)
|
|
338
|
+
if isinstance(value, ListValue):
|
|
339
|
+
return "[list " + " ".join(self.render_value(item) for item in value.values) + "]"
|
|
340
|
+
if isinstance(value, VarRef):
|
|
341
|
+
if not value.name:
|
|
342
|
+
raise BuildError("empty Tcl variable reference")
|
|
343
|
+
return f"${value.name}"
|
|
344
|
+
if isinstance(value, Expr):
|
|
345
|
+
return f"[expr {{{value.expression}}}]"
|
|
346
|
+
if isinstance(value, CommandSubstitution):
|
|
347
|
+
words = [value.command, *(self.render_value(arg) for arg in value.args)]
|
|
348
|
+
return "[" + " ".join(words) + "]"
|
|
349
|
+
if isinstance(value, Raw):
|
|
350
|
+
return value.text
|
|
351
|
+
raise BuildError(f"unsupported Tcl value: {value!r}")
|
|
352
|
+
|
|
353
|
+
def _render_node(self, node: TclNode, *, level: int) -> str:
|
|
354
|
+
prefix = self.indent * level
|
|
355
|
+
if isinstance(node, Comment):
|
|
356
|
+
return "".join(
|
|
357
|
+
f"{prefix}# {_escape_comment_line(line)}\n"
|
|
358
|
+
for line in _comment_lines(node.text)
|
|
359
|
+
)
|
|
360
|
+
if isinstance(node, BlankLine):
|
|
361
|
+
return "\n"
|
|
362
|
+
if isinstance(node, Set):
|
|
363
|
+
return f"{prefix}set {node.name} {self.render_value(node.value)}\n"
|
|
364
|
+
if isinstance(node, Command):
|
|
365
|
+
args = " ".join(self.render_value(arg) for arg in node.args)
|
|
366
|
+
line = f"{node.name} {args}" if args else node.name
|
|
367
|
+
return f"{prefix}{line}\n"
|
|
368
|
+
if isinstance(node, If):
|
|
369
|
+
body = "".join(self._render_node(child, level=level + 1) for child in node.body)
|
|
370
|
+
return f"{prefix}if {{{node.condition.text}}} {{\n{body}{prefix}}}\n"
|
|
371
|
+
if isinstance(node, RawLine):
|
|
372
|
+
return f"{prefix}{node.text}\n"
|
|
373
|
+
raise BuildError(f"unsupported Tcl node: {node!r}")
|
|
374
|
+
|
|
375
|
+
def _validate_node(self, node: TclNode) -> list[Diagnostic]:
|
|
376
|
+
diagnostics: list[Diagnostic] = []
|
|
377
|
+
if isinstance(node, Set):
|
|
378
|
+
if not node.name:
|
|
379
|
+
diagnostics.append(
|
|
380
|
+
Diagnostic("empty-variable-name", "variable name is required", node.origin)
|
|
381
|
+
)
|
|
382
|
+
diagnostics.extend(
|
|
383
|
+
_validate_value(node.value, origin=node.origin, scalar_api=node.scalar_api)
|
|
384
|
+
)
|
|
385
|
+
elif isinstance(node, Command):
|
|
386
|
+
if not node.name:
|
|
387
|
+
diagnostics.append(
|
|
388
|
+
Diagnostic("empty-command-name", "command name is required", node.origin)
|
|
389
|
+
)
|
|
390
|
+
for arg in node.args:
|
|
391
|
+
diagnostics.extend(_validate_value(arg, origin=node.origin, scalar_api=False))
|
|
392
|
+
elif isinstance(node, If):
|
|
393
|
+
if not node.condition.text:
|
|
394
|
+
diagnostics.append(
|
|
395
|
+
Diagnostic("empty-condition", "condition is required", node.origin)
|
|
396
|
+
)
|
|
397
|
+
for item in node.condition.diagnostics:
|
|
398
|
+
diagnostics.append(_diagnostic_with_origin(item, node.origin))
|
|
399
|
+
for child in node.body:
|
|
400
|
+
diagnostics.extend(self._validate_node(child))
|
|
401
|
+
elif isinstance(node, RawLine):
|
|
402
|
+
diagnostics.append(
|
|
403
|
+
Diagnostic("unsafe-raw", "raw Tcl line requires explicit opt-in", node.origin)
|
|
404
|
+
)
|
|
405
|
+
elif isinstance(node, (Comment, BlankLine)):
|
|
406
|
+
pass
|
|
407
|
+
else:
|
|
408
|
+
diagnostics.append(
|
|
409
|
+
Diagnostic("unsupported-node", f"unsupported Tcl node {type(node).__name__}")
|
|
410
|
+
)
|
|
411
|
+
return diagnostics
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _coerce_value(value: TclInputValue) -> TclValue:
|
|
415
|
+
if isinstance(value, (Scalar, PathValue, ListValue, VarRef, Expr, CommandSubstitution, Raw)):
|
|
416
|
+
return value
|
|
417
|
+
return Scalar(value)
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _diagnostic_with_origin(diagnostic: Diagnostic, origin: str | None) -> Diagnostic:
|
|
421
|
+
if diagnostic.origin or origin is None:
|
|
422
|
+
return diagnostic
|
|
423
|
+
return Diagnostic(diagnostic.code, diagnostic.message, origin)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _validate_value(
|
|
427
|
+
value: TclInputValue,
|
|
428
|
+
*,
|
|
429
|
+
origin: str | None,
|
|
430
|
+
scalar_api: bool,
|
|
431
|
+
) -> list[Diagnostic]:
|
|
432
|
+
value = _coerce_value(value)
|
|
433
|
+
diagnostics: list[Diagnostic] = []
|
|
434
|
+
if isinstance(value, PathValue):
|
|
435
|
+
if value.value == "":
|
|
436
|
+
diagnostics.append(Diagnostic("empty-path", "path value is required", origin))
|
|
437
|
+
elif _needs_quoting(value.value):
|
|
438
|
+
diagnostics.append(Diagnostic("quoted-path", "path requires Tcl quoting", origin))
|
|
439
|
+
elif isinstance(value, ListValue):
|
|
440
|
+
if scalar_api:
|
|
441
|
+
diagnostics.append(
|
|
442
|
+
Diagnostic("list-through-scalar-api", "use set_list for Tcl list values", origin)
|
|
443
|
+
)
|
|
444
|
+
for item in value.values:
|
|
445
|
+
diagnostics.extend(_validate_value(item, origin=origin, scalar_api=False))
|
|
446
|
+
elif isinstance(value, VarRef) and not value.name:
|
|
447
|
+
diagnostics.append(
|
|
448
|
+
Diagnostic("empty-variable-name", "variable reference name is required", origin)
|
|
449
|
+
)
|
|
450
|
+
elif isinstance(value, CommandSubstitution):
|
|
451
|
+
if not value.command:
|
|
452
|
+
diagnostics.append(Diagnostic("empty-command-name", "command name is required", origin))
|
|
453
|
+
for arg in value.args:
|
|
454
|
+
diagnostics.extend(_validate_value(arg, origin=origin, scalar_api=False))
|
|
455
|
+
elif isinstance(value, Raw):
|
|
456
|
+
diagnostics.append(
|
|
457
|
+
Diagnostic("unsafe-raw", "raw Tcl value requires explicit opt-in", origin)
|
|
458
|
+
)
|
|
459
|
+
return diagnostics
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _quote_tcl_word(text: str) -> str:
|
|
463
|
+
if text == "":
|
|
464
|
+
return "{}"
|
|
465
|
+
if not _needs_quoting(text):
|
|
466
|
+
return text
|
|
467
|
+
if "{" not in text and "}" not in text and "\n" not in text and "\r" not in text:
|
|
468
|
+
return "{" + text + "}"
|
|
469
|
+
return "".join(_escape_unbraced_char(char) for char in text)
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _needs_quoting(text: str) -> bool:
|
|
473
|
+
return text == "" or any(char.isspace() or char in "{}[]$;\\\"" for char in text)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _escape_unbraced_char(char: str) -> str:
|
|
477
|
+
replacements = {
|
|
478
|
+
" ": "\\ ",
|
|
479
|
+
"\t": "\\t",
|
|
480
|
+
"\n": "\\n",
|
|
481
|
+
"\r": "\\r",
|
|
482
|
+
"\\": "\\\\",
|
|
483
|
+
"{": "\\{",
|
|
484
|
+
"}": "\\}",
|
|
485
|
+
"[": "\\[",
|
|
486
|
+
"]": "\\]",
|
|
487
|
+
"$": "\\$",
|
|
488
|
+
";": "\\;",
|
|
489
|
+
'"': '\\"',
|
|
490
|
+
}
|
|
491
|
+
return replacements.get(char, char)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _comment_lines(text: str) -> list[str]:
|
|
495
|
+
return text.splitlines() or [""]
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _escape_comment_line(line: str) -> str:
|
|
499
|
+
return line.replace("\\", "\\\\").replace("{", "\\{").replace("}", "\\}")
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rosettakit
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Typed Python builders for EDA scripts and command files
|
|
5
|
+
Author: Emin
|
|
6
|
+
Author-email: Emin <me@emin.chat>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Project-URL: Homepage, https://github.com/Emin017/RosettaKit
|
|
16
|
+
Project-URL: Repository, https://github.com/Emin017/RosettaKit
|
|
17
|
+
Project-URL: Issues, https://github.com/Emin017/RosettaKit/issues
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# RosettaKit
|
|
21
|
+
|
|
22
|
+
RosettaKit is a small Python library for building typed EDA script documents and
|
|
23
|
+
rendering them into tool-facing text such as Tcl fragments and command files.
|
|
24
|
+
|
|
25
|
+
## API Stability
|
|
26
|
+
|
|
27
|
+
RosettaKit 0.2.0 treats the public node, value, document, and builder APIs as
|
|
28
|
+
stable:
|
|
29
|
+
|
|
30
|
+
- `rosettakit.tcl`: `Script`, `TclBuilder`, `Scalar`, `PathValue`,
|
|
31
|
+
`ListValue`, `VarRef`, `Expr`, `CommandSubstitution`, `Raw`, `Condition`,
|
|
32
|
+
`Comment`, `BlankLine`, `Set`, `Command`, `If`, `RawLine`, and helper
|
|
33
|
+
functions such as `word`, `path`, `list_value`, `var`, `expr`, `call`, `raw`,
|
|
34
|
+
and `file_isdirectory`.
|
|
35
|
+
- `rosettakit.cmdfile`: `CommandFile`, `CommandFileBuilder`, `ValueType`,
|
|
36
|
+
`ValueQuoting`, `CommandFileDialect`, `TCL_WORD_DIALECT`, `PLAIN_DIALECT`,
|
|
37
|
+
`Comment`, `BlankLine`, `Flag`, `Option`, and `RawLine`.
|
|
38
|
+
- `rosettakit.diagnostics.Diagnostic` and the exception hierarchy in
|
|
39
|
+
`rosettakit.errors`.
|
|
40
|
+
|
|
41
|
+
Generated text is part of the compatibility surface. Patch releases should not
|
|
42
|
+
change quoting, indentation, line ordering, or default raw-content policy unless
|
|
43
|
+
the current output is unsafe or invalid.
|
|
44
|
+
|
|
45
|
+
RosettaKit only builds script text. It does not parse Tcl, execute EDA tools,
|
|
46
|
+
manage subprocesses, or model a host workflow.
|
|
47
|
+
|
|
48
|
+
## Tcl API
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from rosettakit import tcl
|
|
52
|
+
|
|
53
|
+
script = tcl.Script()
|
|
54
|
+
script.comment("Auto-generated by RosettaKit")
|
|
55
|
+
script.set("top_design", tcl.word("gcd_core"))
|
|
56
|
+
script.set("clk_freq_mhz", 500)
|
|
57
|
+
script.set_path("final_netlist_file", "build out/gcd final.v")
|
|
58
|
+
script.set_list("lib_list", ["libs/fast corner.lib", "libs/slow.lib"])
|
|
59
|
+
script.set_expr("clk_period_ps", "1000000.0 / $clk_freq_mhz")
|
|
60
|
+
script.set_path("tmp_dir", "build out/tmp")
|
|
61
|
+
script.file_mkdir(tcl.var("tmp_dir"))
|
|
62
|
+
|
|
63
|
+
text = script.build()
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Use `script.validate()` to inspect diagnostics before building. Raw Tcl is an
|
|
67
|
+
explicit escape hatch through `tcl.raw(...)` or `script.raw_line(...)`; builds
|
|
68
|
+
fail on raw content unless `allow_unsafe_raw=True` is passed.
|
|
69
|
+
|
|
70
|
+
## Command File API
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from rosettakit import cmdfile
|
|
74
|
+
|
|
75
|
+
cmd = cmdfile.CommandFile(prefix="-")
|
|
76
|
+
cmd.flag("useOpenSTA")
|
|
77
|
+
cmd.option("top", "gcd_core")
|
|
78
|
+
cmd.option("def", "build out/input.def", value_type=cmdfile.ValueType.PATH)
|
|
79
|
+
cmd.options("lef", ["tech/sky130.lef", "macro lef/sram.lef"], value_type=cmdfile.ValueType.PATH)
|
|
80
|
+
|
|
81
|
+
text = cmd.build()
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Command files preserve insertion order, support flags, single options,
|
|
85
|
+
repeated options, optional omission of empty values, and path-aware quoting.
|
|
86
|
+
`PLAIN_DIALECT` emits unquoted whitespace-delimited option values and rejects
|
|
87
|
+
values that cannot be represented safely in that form.
|
|
88
|
+
|
|
89
|
+
## Examples
|
|
90
|
+
|
|
91
|
+
The first-party examples use only RosettaKit and Python standard-library
|
|
92
|
+
modules:
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
uv run python examples/yosys_global_var.py
|
|
96
|
+
uv run python examples/sizer_cmd_file.py
|
|
97
|
+
uv run python examples/sizer_env_file.py
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
They write generated output under ignored paths:
|
|
101
|
+
|
|
102
|
+
```text
|
|
103
|
+
examples/out/yosys/global_var.tcl
|
|
104
|
+
examples/out/sizer/design.cmd_file
|
|
105
|
+
examples/out/sizer/design.env_file
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
To verify the generated Tcl with a local Tcl shell:
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
uv run python examples/yosys_global_var.py
|
|
112
|
+
tclsh examples/out/yosys/global_var.tcl
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Development
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
uv sync
|
|
119
|
+
uv run pytest
|
|
120
|
+
uv run ruff check
|
|
121
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
rosettakit/__init__.py,sha256=GLZerkEC4XoYM-TwcRwOCCsz5S6Q-zL3fwgb5ulDObE,100
|
|
2
|
+
rosettakit/cmdfile.py,sha256=UIOaS_WE_QWcDZMizAZZOdtB25AJiIbMqOSUQS_odHQ,12570
|
|
3
|
+
rosettakit/diagnostics.py,sha256=86Uy9Th5sQzEc4KenOElfz0t8imiC2hUqxgmDhAH8CY,175
|
|
4
|
+
rosettakit/errors.py,sha256=iedI1i28nGBKvCEgdc5LNCLTu71Bpdj1IwmfU6uxrzI,1041
|
|
5
|
+
rosettakit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
rosettakit/tcl.py,sha256=Khl2MmSn-V5B1VrHCmeNHE_Vu3_IfzR6JfyAnIVD6ZY,17030
|
|
7
|
+
rosettakit-0.2.0.dist-info/licenses/LICENSE,sha256=8KuYVmQGvdTeu0tP1UW3POnWymWvHHUQJM2cdvpc01c,11334
|
|
8
|
+
rosettakit-0.2.0.dist-info/WHEEL,sha256=wXwAVsgVaOZ_pwDFqQm5Rd6PID-Fc74nkLc8X8gHiDo,81
|
|
9
|
+
rosettakit-0.2.0.dist-info/METADATA,sha256=zXyjJxtSlgXt9CcCKHSgIh6grXFyQlJFs4p1TFvsnec,3941
|
|
10
|
+
rosettakit-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Emin
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|