Skip to main content

tabnas_jsonic_cli/
cli.rs

1/* Copyright (c) 2020-2026 Richard Rodger, Oliver Sturm, and other
2contributors, MIT License */
3
4//! The command itself: argument parsing, option, meta and plugin wiring,
5//! source merging and serialization. The port of `ts/src/jsonic-cli.ts`
6//! and of `go/cli/run.go`.
7
8use std::collections::BTreeMap;
9use std::io::{Read, Write};
10use std::sync::{Arc, Mutex};
11
12use indexmap::IndexMap;
13use serde_json::{json, Value as Json};
14use tabnas::{Plugin, Tabnas, Value};
15
16use crate::args::{engine_options, handle_props, parse_args, sub_object};
17use crate::help::HELP;
18use crate::merge::deep;
19use crate::registry::{lookup, plugins};
20use crate::stringify::{json_option, parse_replacer, parse_space, stringify};
21
22/// Run the command over `argv`, whose first entry is the program name, as
23/// [`std::env::args`] yields it. Standard input is read only when it is
24/// needed, and every line the command prints goes to `stdout`; a failure
25/// is reported on `stderr`. The return value is the process exit code.
26///
27/// The streams are parameters so the suite can drive the command in
28/// process, which is the seam `run(argv, console)` gives the TypeScript
29/// CLI and `Run(argv, stdin, out, extra)` gives the Go one.
30///
31/// ```
32/// let argv: Vec<String> = ["jsonic", "a:1"].iter().map(|s| s.to_string()).collect();
33/// let mut out: Vec<u8> = Vec::new();
34/// let code = tabnas_jsonic_cli::run(
35///     &argv,
36///     &mut std::io::empty(),
37///     &mut out,
38///     &mut std::io::sink(),
39/// );
40/// assert_eq!(code, 0);
41/// assert_eq!(String::from_utf8(out).unwrap(), "{\"a\":1}\n");
42/// ```
43pub fn run(
44    argv: &[String],
45    stdin: &mut dyn Read,
46    stdout: &mut dyn Write,
47    stderr: &mut dyn Write,
48) -> i32 {
49    run_with_plugins(argv, stdin, stdout, stderr, &BTreeMap::new())
50}
51
52/// [`run`], with `extra` plugins available to `-p` / `--plugin` for this
53/// run alone. A same-named entry wins over the registry, which is how the
54/// suite injects fixture plugins without touching the process-wide
55/// registry.
56pub fn run_with_plugins(
57    argv: &[String],
58    stdin: &mut dyn Read,
59    stdout: &mut dyn Write,
60    stderr: &mut dyn Write,
61    extra: &BTreeMap<String, Plugin>,
62) -> i32 {
63    let mut registry = plugins();
64    for (name, plugin) in extra {
65        registry.insert(name.clone(), plugin.clone());
66    }
67    let mut sink = WriteSink { out: stdout };
68    match run_inner(argv, stdin, &mut sink, stderr, &registry) {
69        Ok(code) => code,
70        Err(error) => report_io(stderr, &error),
71    }
72}
73
74/// An input or output failure that reached the top: say what it was, then
75/// exit nonzero.
76///
77/// Discarding it left a nonzero exit code with an EMPTY standard error,
78/// which is the one shape this command never uses for a failure, so a
79/// caller had no way to tell a failed read from a run that printed
80/// nothing. The canonical command reports the same thing and in the same
81/// shape: a standard input that errors rejects `run()`, and
82/// `ts/bin/jsonic` prints `e.message` alone, on one line.
83fn report_io(stderr: &mut dyn Write, error: &std::io::Error) -> i32 {
84    // A failed write to standard output cannot be reported on a stream
85    // that may be just as broken, so this last write is allowed to fail.
86    let _ = writeln!(stderr, "{error}");
87    1
88}
89
90/// What one captured run produced. The counterpart of the `lines` a Go
91/// `logger` records and of `cn.d.log` in the TypeScript suite: one entry
92/// per printed call, so an entry that spans several physical lines (the
93/// help text, the grammar description, indented JSON) stays one entry.
94#[derive(Debug, Default, Clone, PartialEq, Eq)]
95pub struct Captured {
96    /// The process exit code.
97    pub code: i32,
98    /// What went to standard output, one entry per printed call.
99    pub lines: Vec<String>,
100    /// What went to standard error.
101    pub stderr: String,
102}
103
104impl Captured {
105    /// The first printed entry, or the empty string when nothing was
106    /// printed.
107    pub fn first(&self) -> &str {
108        self.lines.first().map_or("", String::as_str)
109    }
110
111    /// The last printed entry: the JSON result, after any debug trace.
112    pub fn last(&self) -> &str {
113        self.lines.last().map_or("", String::as_str)
114    }
115}
116
117/// Run the command and collect what it printed instead of writing it to a
118/// stream, so a caller can inspect the individual printed entries.
119///
120/// ```
121/// let argv: Vec<String> = ["jsonic", "-n", "a:1"].iter().map(|s| s.to_string()).collect();
122/// let out = tabnas_jsonic_cli::capture(&argv, &mut std::io::empty(), &Default::default());
123/// assert_eq!(out.code, 0);
124/// assert_eq!(out.lines, vec!["{\n  \"a\": 1\n}".to_string()]);
125/// ```
126pub fn capture(
127    argv: &[String],
128    stdin: &mut dyn Read,
129    extra: &BTreeMap<String, Plugin>,
130) -> Captured {
131    let mut registry = plugins();
132    for (name, plugin) in extra {
133        registry.insert(name.clone(), plugin.clone());
134    }
135    let mut sink = CaptureSink::default();
136    let mut stderr: Vec<u8> = Vec::new();
137    let code = match run_inner(argv, stdin, &mut sink, &mut stderr, &registry) {
138        Ok(code) => code,
139        Err(error) => report_io(&mut stderr, &error),
140    };
141    Captured {
142        code,
143        lines: sink.lines,
144        stderr: String::from_utf8_lossy(&stderr).into_owned(),
145    }
146}
147
148/// Where the command's printed entries go. One call is one entry, which
149/// is the unit the shared fixtures compare and the unit a `console.log`
150/// is in the canonical command.
151trait Sink {
152    fn line(&mut self, text: &str) -> std::io::Result<()>;
153}
154
155/// A sink that writes each entry to a stream, newline terminated.
156struct WriteSink<'a> {
157    out: &'a mut dyn Write,
158}
159
160impl Sink for WriteSink<'_> {
161    fn line(&mut self, text: &str) -> std::io::Result<()> {
162        writeln!(self.out, "{text}")
163    }
164}
165
166/// A sink that keeps each entry.
167#[derive(Default)]
168struct CaptureSink {
169    lines: Vec<String>,
170}
171
172impl Sink for CaptureSink {
173    fn line(&mut self, text: &str) -> std::io::Result<()> {
174        self.lines.push(text.to_string());
175        Ok(())
176    }
177}
178
179fn run_inner(
180    argv: &[String],
181    stdin: &mut dyn Read,
182    log: &mut dyn Sink,
183    stderr: &mut dyn Write,
184    registry: &BTreeMap<String, Plugin>,
185) -> std::io::Result<i32> {
186    let args = parse_args(argv);
187
188    if args.help {
189        log.line(HELP)?;
190        return Ok(0);
191    }
192
193    let option_bag = match handle_props(&args.options) {
194        Ok(bag) => bag,
195        Err(message) => return fail(stderr, &message),
196    };
197    let meta_bag = match handle_props(&args.meta) {
198        Ok(bag) => bag,
199        Err(message) => return fail(stderr, &message),
200    };
201
202    // Resolve every `-p` reference before building anything, so an
203    // unknown one fails without side effects. `-d` adds the debug plugin
204    // ahead of them, as the TypeScript CLI seeds `plugins.debug` before
205    // merging `handle_plugins`.
206    //
207    // The collection is KEYED BY REFERENCE, which is what makes a repeated
208    // `-p` reference install once. TypeScript keeps its plugins in an
209    // object (`out[name] = require(name)`), so `-p x -p x` leaves one
210    // entry and `jsonic.use` runs once; a list would install the plugin
211    // twice, which duplicates whatever it registers. Measured under Node
212    // against `ts/src/jsonic-cli.ts`: a counting plugin passed twice
213    // reports one install, and `-p a -p b -p a` installs `a` before `b`,
214    // so the position kept is the FIRST occurrence's.
215    //
216    // The first occurrence's PLUGIN is kept with it. TypeScript's later
217    // assignment overwrites the value, but the module cache answers the
218    // same reference with the same module, so which one survives is not
219    // observable there. It is observable here for `-d -p debug`, where
220    // `-d`'s tracing plugin would be replaced by the registry's quiet
221    // one, and the canonical command still traces (`-d` also pushes
222    // `log=-1`, which no `-p` undoes).
223    let mut wanted: IndexMap<String, Plugin> = IndexMap::new();
224    if args.debug {
225        wanted.insert("debug".to_string(), debug_plugin());
226    }
227    for name in &args.plugins {
228        let Some(plugin) = lookup(registry, name) else {
229            return fail(stderr, &format!("Plugin not found: {name}"));
230        };
231        wanted.entry(name.clone()).or_insert_with(|| plugin.clone());
232    }
233
234    let mut parser = match build_parser(&engine_options(&option_bag)) {
235        Ok(parser) => parser,
236        Err(message) => return fail(stderr, &message),
237    };
238
239    // Trace and configuration output goes through the engine's debug
240    // sink, the Rust counterpart of the TypeScript CLI's
241    // `options.debug.get_console = () => console`. It is collected rather
242    // than written straight out, because the sink is a shared callback
243    // and cannot hold the caller's `&mut` stream; flushing it after each
244    // parse keeps the order the canonical command prints in.
245    let traced: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
246    let sink = Arc::clone(&traced);
247    parser.options.debug.output = Some(Arc::new(move |line: &str| {
248        if let Ok(mut lines) = sink.lock() {
249            lines.push(line.to_string());
250        }
251    }));
252
253    // The plugin's options are NOT passed at the call site. The engine
254    // merges `options.plugin[<plugin name>]` into the bag a plugin is
255    // installed with, and the `-o plugin.<name>...` settings are already
256    // in the option document, so a plugin receives them under its own
257    // name. That is the TypeScript behaviour: `jsonic.use` keys the
258    // option sub-bag by the plugin function's name, which is how
259    // `-p ../test/pa-qa.js -o plugin.paqa.q=3` finds its option.
260    //
261    // The describe header is keyed by the REFERENCE, not by the plugin's
262    // name, because that is what TypeScript keys it by: `handle_plugins`
263    // stores each loaded plugin under the `-p` string it was named with,
264    // and `null != plugins.debug` is then true for `-p debug` and false
265    // for `-p @tabnas/debug`. Go keys it the same way.
266    let mut has_debug = false;
267    for (name, plugin) in wanted {
268        has_debug |= name == "debug";
269        if let Err(error) = parser.use_plugin(plugin, None) {
270            return fail(stderr, &error.0);
271        }
272    }
273
274    if has_debug {
275        log.line(&format!(
276            "{}\n=== PARSE ===",
277            tabnas_debug::describe(&parser)
278        ))?;
279    }
280
281    let meta = Value::from_json(&meta_bag);
282
283    // Sources merge last-wins by precedence: `--file` results first, then
284    // standard input, then the positional sources. Each is deep-merged
285    // into the seed, and a source that parses to nothing leaves the seed
286    // alone, which is the TypeScript `util.deep(data, {val: undefined})`
287    // no-op.
288    let mut data = Value::Null;
289
290    for path in &args.files {
291        // An empty `--file` is skipped rather than read.
292        if path.is_empty() {
293            continue;
294        }
295        let source = match std::fs::read(path) {
296            Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
297            Err(error) => return fail(stderr, &format!("{path}: {error}")),
298        };
299        match parse_source(&parser, &source, &meta, &traced, log)? {
300            Ok(value) => data = deep(data, value),
301            Err(message) => return fail(stderr, &message),
302        }
303    }
304
305    // Standard input is read whenever there is no positional source, and
306    // whenever `-` was given, exactly as the canonical command does.
307    if args.sources.is_empty() || args.stdin {
308        // A pipe or device that fails mid-read is reported, not
309        // discarded: the exit code alone, with nothing on standard error,
310        // leaves the caller unable to tell a failed read from a source
311        // that parsed to nothing. The canonical command prints the
312        // error's message and nothing else.
313        let source = match read_stdin(stdin) {
314            Ok(text) => text,
315            Err(error) => return fail(stderr, &error.to_string()),
316        };
317        match parse_source(&parser, &source, &meta, &traced, log)? {
318            Ok(value) => data = deep(data, value),
319            Err(message) => return fail(stderr, &message),
320        }
321    }
322
323    for source in &args.sources {
324        match parse_source(&parser, source, &meta, &traced, log)? {
325            Ok(value) => data = deep(data, value),
326            Err(message) => return fail(stderr, &message),
327        }
328    }
329
330    // `replacer = Jsonic(options.JSON.replacer)` and
331    // `space = Jsonic(options.JSON.space)`, run here rather than earlier
332    // because that is where the canonical command runs them: a string
333    // that does not parse fails AFTER the sources have been parsed and
334    // any debug trace printed.
335    let json_bag = sub_object(&option_bag, "JSON");
336    let replacer = match json_option(json_bag, "replacer") {
337        Ok(value) => parse_replacer(value.as_ref()),
338        Err(message) => return fail(stderr, &message),
339    };
340    let space = match json_option(json_bag, "space") {
341        Ok(value) => parse_space(value.as_ref()),
342        Err(message) => return fail(stderr, &message),
343    };
344
345    log.line(&stringify(&data, replacer.as_deref(), &space))?;
346    Ok(0)
347}
348
349/// Parse one source, flushing whatever the trace wrote while it ran.
350fn parse_source(
351    parser: &Tabnas,
352    source: &str,
353    meta: &Value,
354    traced: &Arc<Mutex<Vec<String>>>,
355    log: &mut dyn Sink,
356) -> std::io::Result<Result<Value, String>> {
357    let outcome = parser.parse_with_meta(source, meta.clone());
358    if let Ok(mut lines) = traced.lock() {
359        for line in lines.drain(..) {
360            log.line(&line)?;
361        }
362    }
363    Ok(outcome.map_err(|error| error.to_string()))
364}
365
366/// Report `message` on `stderr` and exit nonzero.
367fn fail(stderr: &mut dyn Write, message: &str) -> std::io::Result<i32> {
368    writeln!(stderr, "{message}")?;
369    Ok(1)
370}
371
372/// Build the parser for `engine_options`, a `serde_json` object of the
373/// `-o` settings that are not CLI-only.
374///
375/// The order matters and is the canonical one: jsonic's own option
376/// defaults, then the caller's options, and only then the grammar, which
377/// is built against the finished option set. That is what makes an option
378/// deciding which alternates exist (`map.child`, `list.child`,
379/// `list.pair`) take effect, as `Jsonic.make(options)` does in
380/// TypeScript. The options are resolved on a throwaway instance first
381/// because the engine applies an option DOCUMENT to a parser, while
382/// [`tabnas_jsonic::make_with`] wants the finished typed options.
383fn build_parser(engine_options: &Json) -> Result<Tabnas, String> {
384    let empty = engine_options
385        .as_object()
386        .is_none_or(serde_json::Map::is_empty);
387    if empty {
388        return Ok(tabnas_jsonic::make());
389    }
390
391    let document = json!({ "options": engine_options });
392    let mut probe = tabnas_jsonic::make();
393    probe
394        .grammar_json(&document.to_string())
395        .map_err(|error| error.0)?;
396    let resolved = probe.config();
397    Ok(tabnas_jsonic::make_with(move |options| *options = resolved))
398}
399
400/// The debug plugin `-d` installs: tracing on, and no `USE:` dump, since
401/// the command prints the description itself.
402///
403/// Tracing is unconditional, as it is in TypeScript, where `-d` pushes
404/// `log=-1` onto the metadata bag and the engine log is what traces.
405/// Nothing a `-o` can say turns that off there, so nothing does here. A
406/// `-p debug` with no `-d` gets the registry's entry instead, which is
407/// quiet, and that is the TypeScript behaviour too: without `log=-1` the
408/// plugin describes the grammar and traces nothing.
409fn debug_plugin() -> Plugin {
410    tabnas_debug::plugin(
411        tabnas_debug::DebugOptions::quiet().with_trace(tabnas_debug::TraceKinds::all()),
412    )
413}
414
415/// Read standard input as text.
416///
417/// The bytes are untrusted, so an invalid sequence folds to U+FFFD rather
418/// than failing: the canonical command reads the stream as UTF-8 and the
419/// engine replaces what it cannot decode.
420fn read_stdin(stdin: &mut dyn Read) -> std::io::Result<String> {
421    let mut bytes = Vec::new();
422    stdin.read_to_end(&mut bytes)?;
423    Ok(String::from_utf8_lossy(&bytes).into_owned())
424}