nkparser 0.1.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.
- nkparser/__init__.py +68 -0
- nkparser/__main__.py +8 -0
- nkparser/builder.py +231 -0
- nkparser/cli.py +419 -0
- nkparser/errors.py +37 -0
- nkparser/lexer.py +299 -0
- nkparser/models.py +526 -0
- nkparser/parser.py +462 -0
- nkparser/py.typed +0 -0
- nkparser/query.py +135 -0
- nkparser/serializer.py +72 -0
- nkparser/tokens.py +33 -0
- nkparser/validator.py +140 -0
- nkparser/visualization.py +245 -0
- nkparser-0.1.0.dist-info/METADATA +104 -0
- nkparser-0.1.0.dist-info/RECORD +18 -0
- nkparser-0.1.0.dist-info/WHEEL +4 -0
- nkparser-0.1.0.dist-info/entry_points.txt +2 -0
nkparser/cli.py
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
"""Command-line interface for nkparser.
|
|
2
|
+
|
|
3
|
+
Subcommands
|
|
4
|
+
-----------
|
|
5
|
+
info Print a summary of a .nk file (version, node counts, diagnostics).
|
|
6
|
+
validate List all diagnostics (errors and warnings) found in a .nk file.
|
|
7
|
+
tree Print a hierarchical text tree of the node graph.
|
|
8
|
+
dot Export the node graph to a Graphviz DOT file.
|
|
9
|
+
nodes List all nodes, optionally filtered by class or name.
|
|
10
|
+
show Dump the raw (or modified) .nk text — useful for debugging.
|
|
11
|
+
|
|
12
|
+
Usage examples
|
|
13
|
+
--------------
|
|
14
|
+
nkparse info comp.nk
|
|
15
|
+
nkparse validate comp.nk
|
|
16
|
+
nkparse tree comp.nk --knobs
|
|
17
|
+
nkparse dot comp.nk -o graph.dot
|
|
18
|
+
nkparse nodes comp.nk --class Merge2
|
|
19
|
+
nkparse nodes comp.nk --name "^Grade"
|
|
20
|
+
nkparse show comp.nk
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import sys
|
|
26
|
+
import json
|
|
27
|
+
import argparse
|
|
28
|
+
from typing import Any
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from . import __version__
|
|
32
|
+
from .models import Node, Script, DiagnosticSeverity
|
|
33
|
+
from .visualization import TextTree, DotExporter
|
|
34
|
+
|
|
35
|
+
# ---------------------------------------------------------------------------
|
|
36
|
+
# Helpers
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _load(path: str) -> Script:
|
|
41
|
+
p = Path(path)
|
|
42
|
+
if not p.exists():
|
|
43
|
+
print(f"error: file not found: {path}", file=sys.stderr)
|
|
44
|
+
sys.exit(1)
|
|
45
|
+
if p.suffix.lower() != ".nk":
|
|
46
|
+
print(
|
|
47
|
+
f"warning: file does not have .nk extension: {path}", file=sys.stderr)
|
|
48
|
+
return Script.from_file(p)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _severity_symbol(sev: DiagnosticSeverity) -> str:
|
|
52
|
+
return {"error": "✖", "warning": "⚠", "info": "ℹ"}.get(sev.value, "?")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _exit_code(script: Script) -> int:
|
|
56
|
+
return 1 if script.has_errors else 0
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ---------------------------------------------------------------------------
|
|
60
|
+
# Subcommands
|
|
61
|
+
# ---------------------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def cmd_info(args: argparse.Namespace) -> int:
|
|
65
|
+
script = _load(args.file)
|
|
66
|
+
nodes = list(script.all_nodes())
|
|
67
|
+
|
|
68
|
+
from collections import Counter
|
|
69
|
+
class_counts = Counter(n.node_class for n in nodes)
|
|
70
|
+
top = class_counts.most_common(5)
|
|
71
|
+
|
|
72
|
+
errors = script.errors()
|
|
73
|
+
warnings = script.warnings()
|
|
74
|
+
|
|
75
|
+
if getattr(args, "format", "text") == "json":
|
|
76
|
+
out = {
|
|
77
|
+
"file": args.file,
|
|
78
|
+
"version": script.nuke_version,
|
|
79
|
+
"node_count": len(nodes),
|
|
80
|
+
"top_classes": [{"class": cls, "count": n} for cls, n in top],
|
|
81
|
+
"diagnostics": {"errors": len(errors), "warnings": len(warnings)},
|
|
82
|
+
}
|
|
83
|
+
print(json.dumps(out, indent=2))
|
|
84
|
+
return _exit_code(script)
|
|
85
|
+
|
|
86
|
+
print(f"File : {args.file}")
|
|
87
|
+
print(f"Version : {script.nuke_version or '(none)'}")
|
|
88
|
+
print(f"Nodes : {len(nodes)}")
|
|
89
|
+
print(
|
|
90
|
+
f"Variables : {len(script._variables)} set / {len(script._variable_refs)} push")
|
|
91
|
+
print(f"Diagnostics: {len(errors)} error(s) {len(warnings)} warning(s)")
|
|
92
|
+
print()
|
|
93
|
+
print("Top node classes:")
|
|
94
|
+
for cls, n in top:
|
|
95
|
+
print(f" {cls:<22} {n}")
|
|
96
|
+
if len(class_counts) > 5:
|
|
97
|
+
print(f" ... and {len(class_counts) - 5} more class(es)")
|
|
98
|
+
|
|
99
|
+
if errors:
|
|
100
|
+
print()
|
|
101
|
+
print("Errors:")
|
|
102
|
+
for d in errors:
|
|
103
|
+
print(
|
|
104
|
+
f" {_severity_symbol(d.severity)} [{d.code}] line {d.line}: {d.message}")
|
|
105
|
+
|
|
106
|
+
return _exit_code(script)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def cmd_validate(args: argparse.Namespace) -> int:
|
|
110
|
+
script = _load(args.file)
|
|
111
|
+
|
|
112
|
+
errors = script.errors()
|
|
113
|
+
warnings = script.warnings()
|
|
114
|
+
|
|
115
|
+
if getattr(args, "format", "text") == "json":
|
|
116
|
+
out = {
|
|
117
|
+
"file": args.file,
|
|
118
|
+
"diagnostics": [
|
|
119
|
+
{
|
|
120
|
+
"severity": d.severity.value,
|
|
121
|
+
"code": d.code,
|
|
122
|
+
"message": d.message,
|
|
123
|
+
"line": d.line,
|
|
124
|
+
"col": d.col,
|
|
125
|
+
}
|
|
126
|
+
for d in script.diagnostics
|
|
127
|
+
],
|
|
128
|
+
"summary": {"errors": len(errors), "warnings": len(warnings)},
|
|
129
|
+
}
|
|
130
|
+
print(json.dumps(out, indent=2))
|
|
131
|
+
return _exit_code(script)
|
|
132
|
+
|
|
133
|
+
if not script.diagnostics:
|
|
134
|
+
print(f"No issues found in {args.file}")
|
|
135
|
+
return 0
|
|
136
|
+
|
|
137
|
+
for d in script.diagnostics:
|
|
138
|
+
sym = _severity_symbol(d.severity)
|
|
139
|
+
print(f"{sym} [{d.code}] line {d.line}: {d.message}")
|
|
140
|
+
|
|
141
|
+
print()
|
|
142
|
+
print(f"{len(errors)} error(s) {len(warnings)} warning(s)")
|
|
143
|
+
return _exit_code(script)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def cmd_tree(args: argparse.Namespace) -> int:
|
|
147
|
+
script = _load(args.file)
|
|
148
|
+
output = TextTree(script).render(
|
|
149
|
+
show_knobs=args.knobs,
|
|
150
|
+
max_depth=args.depth,
|
|
151
|
+
)
|
|
152
|
+
print(output)
|
|
153
|
+
return _exit_code(script)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def cmd_dot(args: argparse.Namespace) -> int:
|
|
157
|
+
script = _load(args.file)
|
|
158
|
+
exporter = DotExporter(script)
|
|
159
|
+
|
|
160
|
+
output_path: str | None = args.output
|
|
161
|
+
dot = exporter.export(
|
|
162
|
+
output_path,
|
|
163
|
+
render=args.render,
|
|
164
|
+
render_format=args.format,
|
|
165
|
+
dot_command=args.dot_command,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
if not output_path:
|
|
169
|
+
print(dot)
|
|
170
|
+
else:
|
|
171
|
+
print(f"DOT graph written to: {output_path}")
|
|
172
|
+
if args.render:
|
|
173
|
+
rendered = DotExporter._rendered_path(output_path, args.format)
|
|
174
|
+
if rendered.exists():
|
|
175
|
+
print(f"Rendered image: {rendered}")
|
|
176
|
+
|
|
177
|
+
return _exit_code(script)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def cmd_nodes(args: argparse.Namespace) -> int:
|
|
181
|
+
script = _load(args.file)
|
|
182
|
+
q = script.query()
|
|
183
|
+
|
|
184
|
+
if args.cls:
|
|
185
|
+
q = q.of_class(*args.cls.split(","))
|
|
186
|
+
if args.name:
|
|
187
|
+
q = q.named(args.name)
|
|
188
|
+
|
|
189
|
+
nodes = q.all()
|
|
190
|
+
|
|
191
|
+
if not nodes:
|
|
192
|
+
if getattr(args, "format", "text") == "json":
|
|
193
|
+
print(json.dumps(
|
|
194
|
+
{"file": args.file, "nodes": [], "count": 0}, indent=2))
|
|
195
|
+
else:
|
|
196
|
+
print("No nodes match the filter.")
|
|
197
|
+
return 0
|
|
198
|
+
|
|
199
|
+
# Determine extra knob columns
|
|
200
|
+
_FIXED = {"name", "xpos", "ypos"}
|
|
201
|
+
extra_cols: list[str] = []
|
|
202
|
+
if args.attrs is not None:
|
|
203
|
+
if args.attrs == "*":
|
|
204
|
+
# Collect all knob names in first-seen order, excluding fixed cols
|
|
205
|
+
seen: dict[str, None] = {}
|
|
206
|
+
for node in nodes:
|
|
207
|
+
for k in node.knobs:
|
|
208
|
+
if k.name not in _FIXED and k.name not in seen:
|
|
209
|
+
seen[k.name] = None
|
|
210
|
+
extra_cols = list(seen)
|
|
211
|
+
else:
|
|
212
|
+
extra_cols = [c.strip()
|
|
213
|
+
for c in args.attrs.split(",") if c.strip()]
|
|
214
|
+
|
|
215
|
+
# Build column widths
|
|
216
|
+
_MAX_W = 30
|
|
217
|
+
col_w = {"#": 5, "Class": 22, "Name": 30, "xpos": 8, "ypos": 8}
|
|
218
|
+
for col in extra_cols:
|
|
219
|
+
# Width = max of header length and longest value (capped)
|
|
220
|
+
max_val = max(
|
|
221
|
+
(len(node.get(col)) for node in nodes if node.knob(col)),
|
|
222
|
+
default=0,
|
|
223
|
+
)
|
|
224
|
+
col_w[col] = min(_MAX_W, max(len(col), max_val))
|
|
225
|
+
|
|
226
|
+
if getattr(args, "format", "text") == "json":
|
|
227
|
+
def _node_dict(node: Node) -> dict[str, Any]:
|
|
228
|
+
d: dict[str, Any] = {
|
|
229
|
+
"class": node.node_class,
|
|
230
|
+
"name": node.name,
|
|
231
|
+
"xpos": int(node.xpos) if node.xpos is not None else None,
|
|
232
|
+
"ypos": int(node.ypos) if node.ypos is not None else None,
|
|
233
|
+
}
|
|
234
|
+
if extra_cols:
|
|
235
|
+
d["knobs"] = {c: node.get(c)
|
|
236
|
+
for c in extra_cols if node.knob(c)}
|
|
237
|
+
return d
|
|
238
|
+
|
|
239
|
+
out: dict[str, Any] = {
|
|
240
|
+
"file": args.file,
|
|
241
|
+
"nodes": [_node_dict(n) for n in nodes],
|
|
242
|
+
"count": len(nodes),
|
|
243
|
+
}
|
|
244
|
+
print(json.dumps(out, indent=2))
|
|
245
|
+
return _exit_code(script)
|
|
246
|
+
|
|
247
|
+
parts = [
|
|
248
|
+
f"{{:<{col_w['#']}}}",
|
|
249
|
+
f"{{:<{col_w['Class']}}}",
|
|
250
|
+
f"{{:<{col_w['Name']}}}",
|
|
251
|
+
f"{{:<{col_w['xpos']}}}",
|
|
252
|
+
f"{{:<{col_w['ypos']}}}",
|
|
253
|
+
] + [f"{{:<{col_w[c]}}}" for c in extra_cols]
|
|
254
|
+
fmt = " ".join(parts)
|
|
255
|
+
|
|
256
|
+
headers = ["#", "Class", "Name", "xpos", "ypos"] + extra_cols
|
|
257
|
+
print(fmt.format(*headers))
|
|
258
|
+
total_width = sum(col_w[h] for h in headers) + 2 * (len(headers) - 1)
|
|
259
|
+
print("-" * max(total_width, 80))
|
|
260
|
+
|
|
261
|
+
for i, node in enumerate(nodes, 1):
|
|
262
|
+
xp = str(int(node.xpos)) if node.xpos is not None else ""
|
|
263
|
+
yp = str(int(node.ypos)) if node.ypos is not None else ""
|
|
264
|
+
extra_vals = [node.get(c)[:col_w[c]] for c in extra_cols]
|
|
265
|
+
row = [str(i), node.node_class[:col_w["Class"]],
|
|
266
|
+
node.name[:col_w["Name"]], xp, yp]
|
|
267
|
+
print(fmt.format(*(row + extra_vals)))
|
|
268
|
+
|
|
269
|
+
print()
|
|
270
|
+
print(f"{len(nodes)} node(s)")
|
|
271
|
+
return _exit_code(script)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def cmd_show(args: argparse.Namespace) -> int:
|
|
275
|
+
script = _load(args.file)
|
|
276
|
+
print(script.to_nk(), end="")
|
|
277
|
+
return _exit_code(script)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# ---------------------------------------------------------------------------
|
|
281
|
+
# Argument parser
|
|
282
|
+
# ---------------------------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
286
|
+
parser = argparse.ArgumentParser(
|
|
287
|
+
description="Parse, inspect, and validate Foundry Nuke .nk script files.",
|
|
288
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
289
|
+
epilog="""
|
|
290
|
+
examples:
|
|
291
|
+
nkparse info comp.nk
|
|
292
|
+
nkparse info comp.nk --format json
|
|
293
|
+
nkparse validate comp.nk
|
|
294
|
+
nkparse validate comp.nk --format json
|
|
295
|
+
nkparse tree comp.nk --knobs
|
|
296
|
+
nkparse dot comp.nk -o graph.dot --render
|
|
297
|
+
nkparse nodes comp.nk --class Read
|
|
298
|
+
nkparse nodes comp.nk --name "^Merge"
|
|
299
|
+
nkparse nodes comp.nk --class Grade --attrs
|
|
300
|
+
nkparse nodes comp.nk --class Grade --attrs white,multiply --format json
|
|
301
|
+
nkparse show comp.nk
|
|
302
|
+
""",
|
|
303
|
+
)
|
|
304
|
+
parser.add_argument("--version", action="version",
|
|
305
|
+
version=f"nkparser {__version__}")
|
|
306
|
+
|
|
307
|
+
sub = parser.add_subparsers(dest="command", metavar="command")
|
|
308
|
+
|
|
309
|
+
# info
|
|
310
|
+
p_info = sub.add_parser("info", help="Print a summary of the script")
|
|
311
|
+
p_info.add_argument("file", metavar="FILE", help=".nk file to inspect")
|
|
312
|
+
p_info.add_argument(
|
|
313
|
+
"--format", choices=["text", "json"], default="text", help="Output format (default: text)"
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
# validate
|
|
317
|
+
p_val = sub.add_parser(
|
|
318
|
+
"validate", help="List all diagnostics (errors and warnings)")
|
|
319
|
+
p_val.add_argument("file", metavar="FILE", help=".nk file to validate")
|
|
320
|
+
p_val.add_argument(
|
|
321
|
+
"--format", choices=["text", "json"], default="text", help="Output format (default: text)"
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
# tree
|
|
325
|
+
p_tree = sub.add_parser("tree", help="Print the node graph as a text tree")
|
|
326
|
+
p_tree.add_argument("file", metavar="FILE", help=".nk file")
|
|
327
|
+
p_tree.add_argument(
|
|
328
|
+
"--knobs", "-k", action="store_true", help="Show knob values under each node"
|
|
329
|
+
)
|
|
330
|
+
p_tree.add_argument(
|
|
331
|
+
"--depth", "-d", type=int, default=99, metavar="N", help="Maximum tree depth (default: 99)"
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
# dot
|
|
335
|
+
p_dot = sub.add_parser(
|
|
336
|
+
"dot", help="Export the node graph to Graphviz DOT format")
|
|
337
|
+
p_dot.add_argument("file", metavar="FILE", help=".nk file")
|
|
338
|
+
p_dot.add_argument("-o", "--output", metavar="OUT",
|
|
339
|
+
help="Write DOT to file (default: stdout)")
|
|
340
|
+
p_dot.add_argument(
|
|
341
|
+
"--render",
|
|
342
|
+
action="store_true",
|
|
343
|
+
help="Render to image (requires the graphviz Python package)",
|
|
344
|
+
)
|
|
345
|
+
p_dot.add_argument(
|
|
346
|
+
"--format",
|
|
347
|
+
default="png",
|
|
348
|
+
metavar="FMT",
|
|
349
|
+
help="Render format: png, svg, pdf (default: png)",
|
|
350
|
+
)
|
|
351
|
+
p_dot.add_argument(
|
|
352
|
+
"--dot-command",
|
|
353
|
+
metavar="PATH",
|
|
354
|
+
help="Graphviz dot executable to use for --render (default: NKPARSER_DOT or dot)",
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
# nodes
|
|
358
|
+
p_nodes = sub.add_parser("nodes", help="List nodes, optionally filtered")
|
|
359
|
+
p_nodes.add_argument("file", metavar="FILE", help=".nk file")
|
|
360
|
+
p_nodes.add_argument(
|
|
361
|
+
"--class",
|
|
362
|
+
dest="cls",
|
|
363
|
+
metavar="CLASS",
|
|
364
|
+
help="Filter by node class (comma-separated for multiple, e.g. Read,Write)",
|
|
365
|
+
)
|
|
366
|
+
p_nodes.add_argument(
|
|
367
|
+
"--name", metavar="PATTERN", help="Filter by name regex (e.g. '^Grade')"
|
|
368
|
+
)
|
|
369
|
+
p_nodes.add_argument(
|
|
370
|
+
"--attrs",
|
|
371
|
+
metavar="KNOBS",
|
|
372
|
+
nargs="?",
|
|
373
|
+
const="*",
|
|
374
|
+
default=None,
|
|
375
|
+
help=(
|
|
376
|
+
"Show extra knob columns. Omit value for all knobs (--attrs), "
|
|
377
|
+
"or pass a comma-separated list (--attrs white,multiply)"
|
|
378
|
+
),
|
|
379
|
+
)
|
|
380
|
+
p_nodes.add_argument(
|
|
381
|
+
"--format", choices=["text", "json"], default="text", help="Output format (default: text)"
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
# show
|
|
385
|
+
p_show = sub.add_parser(
|
|
386
|
+
"show", help="Print the serialized .nk text (round-trip output)")
|
|
387
|
+
p_show.add_argument("file", metavar="FILE", help=".nk file")
|
|
388
|
+
|
|
389
|
+
return parser
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
# ---------------------------------------------------------------------------
|
|
393
|
+
# Entry point
|
|
394
|
+
# ---------------------------------------------------------------------------
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def main() -> None:
|
|
398
|
+
parser = build_parser()
|
|
399
|
+
args = parser.parse_args()
|
|
400
|
+
|
|
401
|
+
dispatch = {
|
|
402
|
+
"info": cmd_info,
|
|
403
|
+
"validate": cmd_validate,
|
|
404
|
+
"tree": cmd_tree,
|
|
405
|
+
"dot": cmd_dot,
|
|
406
|
+
"nodes": cmd_nodes,
|
|
407
|
+
"show": cmd_show,
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
fn = dispatch.get(args.command)
|
|
411
|
+
if fn is None:
|
|
412
|
+
parser.print_help()
|
|
413
|
+
sys.exit(1)
|
|
414
|
+
|
|
415
|
+
sys.exit(fn(args))
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
if __name__ == "__main__":
|
|
419
|
+
main()
|
nkparser/errors.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Exception hierarchy for nkparser."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class NkParserError(Exception):
|
|
7
|
+
"""Base for all nkparser errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class LexError(NkParserError):
|
|
11
|
+
"""Raised when the lexer encounters an unrecognised character sequence."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, message: str, line: int, col: int, source: str = "") -> None:
|
|
14
|
+
self.line = line
|
|
15
|
+
self.col = col
|
|
16
|
+
self.source = source
|
|
17
|
+
super().__init__(f"[{line}:{col}] {message}" +
|
|
18
|
+
(f"\n {source}" if source else ""))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ParseError(NkParserError):
|
|
22
|
+
"""Raised when the parser encounters unexpected tokens."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, message: str, line: int, col: int, source: str = "") -> None:
|
|
25
|
+
self.line = line
|
|
26
|
+
self.col = col
|
|
27
|
+
self.source = source
|
|
28
|
+
super().__init__(f"[{line}:{col}] {message}" +
|
|
29
|
+
(f"\n {source}" if source else ""))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ValidationError(NkParserError):
|
|
33
|
+
"""Raised for script-level structural violations (also collected into Script.diagnostics)."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class SerializationError(NkParserError):
|
|
37
|
+
"""Raised when the serializer cannot produce valid .nk output."""
|