Skip to main content

oxml_cli/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// Copyright (c) 2026 oxml. All rights reserved.
3
4//! `oxml` — query, validate and inspect XML from the command line.
5//!
6//! Argument parsing is hand-rolled rather than pulled from a crate.
7//! The surface is four subcommands and a handful of flags; a
8//! dependency would be more code to audit than it removes, and this
9//! binary is meant to be cheap to trust.
10
11#![forbid(unsafe_code)]
12
13use std::io::{Read as _, Write};
14use std::process::ExitCode;
15
16const USAGE: &str = "\
17oxml — query, validate and inspect XML
18
19USAGE:
20    oxml <COMMAND> [OPTIONS] [FILE]
21
22COMMANDS:
23    query <XPATH>     Evaluate an XPath expression
24    validate <XSD>    Validate against an XML Schema
25    stats             Summarise the document
26    check             Report whether the document is well-formed
27
28OPTIONS:
29    -t, --text        Print matched nodes' text rather than a summary
30    -c, --count       Print only the number of matches
31    -n, --ns P=URI    Bind a namespace prefix for `query`, repeatable
32    -h, --help        Show this message
33    -V, --version     Show the version
34
35FILE defaults to standard input, so oxml composes with pipes:
36
37    curl -s https://example.com/feed.xml | oxml query '//item/title' -t
38
39EXIT STATUS:
40    0   success, and for `validate` the document conforms
41    1   the document is invalid, or no nodes matched
42    2   a usage or I/O error
43";
44
45/// Run the CLI over `args`, writing to `out` and `err`.
46///
47/// Both streams are parameters rather than `println!` so that a test
48/// or a benchmark can drive the real command path and read back what
49/// it produced. Going through the binary instead measures process
50/// spawn and pipe setup alongside the work, and cannot assert on
51/// output without a subprocess.
52///
53/// # Errors
54///
55/// Returns the message the binary prints after `oxml: `, for usage
56/// mistakes and unreadable inputs. A document that is merely invalid
57/// is not an error here -- it is a non-zero [`ExitCode`].
58pub fn run(
59    args: &[String],
60    out: &mut dyn Write,
61    err: &mut dyn Write,
62) -> Result<ExitCode, String> {
63    if args.is_empty() || has_flag(args, "-h", "--help") {
64        let _ = write!(out, "{USAGE}");
65        return Ok(ExitCode::SUCCESS);
66    }
67    if has_flag(args, "-V", "--version") {
68        let _ = writeln!(out, "oxml {}", env!("CARGO_PKG_VERSION"));
69        return Ok(ExitCode::SUCCESS);
70    }
71
72    let namespaces = parse_namespace_bindings(args)?;
73    let positional = positional_args(args);
74    let command =
75        required(&positional, 0, "no command given; try `oxml --help`")?;
76    dispatch(command, &positional, args, &namespaces, out, err)
77}
78
79/// Run one command, given its name and the arguments after it.
80fn dispatch(
81    command: &str,
82    positional: &[&String],
83    args: &[String],
84    namespaces: &[(String, String)],
85    out: &mut dyn Write,
86    err: &mut dyn Write,
87) -> Result<ExitCode, String> {
88    match command {
89        "query" => query_command(positional, args, namespaces, out),
90        "validate" => validate_command(positional, out, err),
91        "stats" => cmd_stats(&input_at(positional, 1)?, out),
92        "check" => Ok(cmd_check(&input_at(positional, 1)?, out, err)),
93        other => Err(format!("unknown command `{other}`; try `oxml --help`")),
94    }
95}
96
97/// `oxml query <xpath> [file]`.
98fn query_command(
99    positional: &[&String],
100    args: &[String],
101    namespaces: &[(String, String)],
102    out: &mut dyn Write,
103) -> Result<ExitCode, String> {
104    let expr = required(positional, 1, "query needs an XPath expression")?;
105    let source = input_at(positional, 2)?;
106    let text_only = has_flag(args, "-t", "--text");
107    let count_only = has_flag(args, "-c", "--count");
108    cmd_query(&source, expr, text_only, count_only, namespaces, out)
109}
110
111/// `oxml validate <xsd> [file]`.
112fn validate_command(
113    positional: &[&String],
114    out: &mut dyn Write,
115    err: &mut dyn Write,
116) -> Result<ExitCode, String> {
117    let xsd_path = required(positional, 1, "validate needs a path to an .xsd")?;
118    let source = input_at(positional, 2)?;
119    cmd_validate(&source, xsd_path, out, err)
120}
121
122/// Whether `args` holds either spelling of a flag.
123fn has_flag(args: &[String], short: &str, long: &str) -> bool {
124    args.iter().any(|a| a == short || a == long)
125}
126
127/// The positional argument at `index`, or `missing` as the error.
128fn required<'a>(
129    positional: &[&'a String],
130    index: usize,
131    missing: &str,
132) -> Result<&'a str, String> {
133    positional
134        .get(index)
135        .map(|s| s.as_str())
136        .ok_or_else(|| missing.to_owned())
137}
138
139/// The input named at `index`, or standard input when there is none.
140fn input_at(positional: &[&String], index: usize) -> Result<String, String> {
141    read_input(positional.get(index).map(|s| s.as_str()))
142}
143
144/// Read from a path, or standard input when none is given.
145fn read_input(path: Option<&str>) -> Result<String, String> {
146    if let Some(p) = path {
147        let file = std::fs::File::open(p)
148            .map_err(|e| format!("cannot read {p}: {e}"))?;
149        read_bounded(file, p)
150    } else {
151        read_bounded(std::io::stdin().lock(), "stdin")
152    }
153}
154
155fn read_bounded(
156    input: impl std::io::Read,
157    label: &str,
158) -> Result<String, String> {
159    const MAX_INPUT_BYTES: usize = 8 * 1024 * 1024;
160    let mut buf = String::new();
161    let _ = input
162        .take((MAX_INPUT_BYTES + 1) as u64)
163        .read_to_string(&mut buf)
164        .map_err(|e| format!("cannot read {label}: {e}"))?;
165    if buf.len() > MAX_INPUT_BYTES {
166        return Err(format!("{label} exceeds the 8 MiB input limit"));
167    }
168    Ok(buf)
169}
170
171fn parse_or_report(source: &str) -> Result<oxml::Document, String> {
172    oxml::parse_with(source, oxml::Limits::strict()).map_err(|e| {
173        let (line, col) = e.line_column(source);
174        format!("{line}:{col}: {e}")
175    })
176}
177
178/// Collect `-n PREFIX=URI` bindings, in order.
179///
180/// From oxml 0.0.4 a prefix in an expression resolves against bindings
181/// supplied with the query rather than against the document, and an
182/// unbound prefix is a compile error. Without a way to pass them,
183/// `//m:item` would have become unanswerable from the command line --
184/// a previously-wrong answer turning into an error with no remedy.
185///
186/// A malformed binding is a *usage* error, exit 2, not a query failure:
187/// the user made a mistake rather than the document.
188/// The positional arguments, with option values removed.
189///
190/// `-n` takes a value, so the argument after it is not positional.
191/// Filtering on a leading `-` alone would have made `urn:example` in
192/// `-n m=urn:example` look like a command.
193fn positional_args(args: &[String]) -> Vec<&String> {
194    let mut out: Vec<&String> = Vec::new();
195    let mut skip_next = false;
196    for arg in args {
197        if skip_next {
198            skip_next = false;
199            continue;
200        }
201        if arg == "-n" || arg == "--ns" {
202            skip_next = true;
203            continue;
204        }
205        if !arg.starts_with('-') {
206            out.push(arg);
207        }
208    }
209    out
210}
211
212/// Turn an `XPath` compile error into something a shell user can act on.
213///
214/// The library's unbound-prefix message names
215/// `XPath::compile_with_namespaces`, which is no help to someone at a
216/// prompt. Everything else is passed through: those messages already
217/// say where in the expression the problem is.
218fn explain_xpath_error(error: &oxml::XPathError) -> String {
219    if error.message.contains("unbound namespace prefix") {
220        let prefix = error
221            .message
222            .split('`')
223            .nth(1)
224            .unwrap_or("PREFIX")
225            .to_owned();
226        format!(
227            "bad XPath: unbound namespace prefix `{prefix}`; \
228             bind it with --ns {prefix}=URI"
229        )
230    } else {
231        format!("bad XPath: {error}")
232    }
233}
234
235fn parse_namespace_bindings(
236    args: &[String],
237) -> Result<Vec<(String, String)>, String> {
238    let mut out: Vec<(String, String)> = Vec::new();
239    let mut expecting = false;
240    for arg in args {
241        if expecting {
242            expecting = false;
243            let Some((prefix, uri)) = arg.split_once('=') else {
244                return Err(format!(
245                    "`{arg}` is not a namespace binding; write PREFIX=URI"
246                ));
247            };
248            if prefix.is_empty() {
249                return Err("a namespace binding needs a prefix".to_owned());
250            }
251            if prefix == "xml" {
252                return Err(
253                    "`xml` is bound by the specification and may not be \
254                     rebound"
255                        .to_owned(),
256                );
257            }
258            // Later bindings win, so a wrapper script can set defaults
259            // a caller overrides.
260            out.retain(|(p, _)| p != prefix);
261            out.push((prefix.to_owned(), uri.to_owned()));
262        } else if arg == "-n" || arg == "--ns" {
263            expecting = true;
264        }
265    }
266    if expecting {
267        return Err("`--ns` needs a PREFIX=URI argument".to_owned());
268    }
269    Ok(out)
270}
271
272fn evaluate_query(
273    source: &str,
274    expr: &str,
275    namespaces: &[(String, String)],
276) -> Result<(oxml::Document, oxml::xpath::Value), String> {
277    let doc = parse_or_report(source)?;
278    let bindings: Vec<(&str, &str)> = namespaces
279        .iter()
280        .map(|(prefix, uri)| (prefix.as_str(), uri.as_str()))
281        .collect();
282    let xpath = oxml::XPath::compile_with_namespaces_and_limits(
283        expr,
284        &bindings,
285        &oxml::Limits::strict(),
286    )
287    .map_err(|e| explain_xpath_error(&e))?;
288    let context = oxml::xpath::EvalContext::new()
289        .with_limits(oxml::xpath::EvalLimits::default());
290    let value = xpath
291        .evaluate_with(&doc, &context)
292        .map_err(|e| e.to_string())?;
293
294    Ok((doc, value))
295}
296
297fn cmd_query(
298    source: &str,
299    expr: &str,
300    text_only: bool,
301    count_only: bool,
302    namespaces: &[(String, String)],
303    out: &mut dyn Write,
304) -> Result<ExitCode, String> {
305    let (doc, value) = evaluate_query(source, expr, namespaces)?;
306
307    let Some(nodes) = value.nodes() else {
308        // A non-node-set result — a count, a string, a boolean — is
309        // printed as-is. `oxml query 'count(//x)'` should behave like
310        // the expression it is.
311        let _ = writeln!(out, "{}", value.to_str(&doc));
312        return Ok(ExitCode::SUCCESS);
313    };
314
315    if count_only {
316        let _ = writeln!(out, "{}", nodes.len());
317        return Ok(if nodes.is_empty() {
318            ExitCode::from(1)
319        } else {
320            ExitCode::SUCCESS
321        });
322    }
323
324    for &node in nodes {
325        let line = if text_only {
326            doc.text(node)
327        } else {
328            describe(&doc, node)
329        };
330        writeln!(out, "{line}").map_err(|e| e.to_string())?;
331    }
332
333    Ok(if nodes.is_empty() {
334        ExitCode::from(1)
335    } else {
336        ExitCode::SUCCESS
337    })
338}
339
340/// A one-line summary of a node, for when `--text` is not enough.
341fn describe(doc: &oxml::Document, node: oxml::NodeId) -> String {
342    match doc.kind(node) {
343        // Resolved through `element_name` rather than destructured from
344        // the variant: the element's name is interned, so the variant
345        // holds a handle rather than the name itself. This accessor is
346        // stable across that change.
347        Some(oxml::NodeKind::Element { .. }) => {
348            let Some(name) = doc.element_name(node) else {
349                return String::new();
350            };
351            let attrs: Vec<String> = doc
352                .attributes(node)
353                .iter()
354                .map(|a| {
355                    let name =
356                        doc.name(a.name).map_or("?", |n| n.local.as_str());
357                    format!(" {name}=\"{}\"", a.value)
358                })
359                .collect();
360            let text = doc.text(node);
361            let preview = text.trim();
362            if preview.is_empty() {
363                format!("<{}{}/>", name.local, attrs.concat())
364            } else {
365                format!(
366                    "<{}{}>{}</{}>",
367                    name.local,
368                    attrs.concat(),
369                    truncate(preview, 60),
370                    name.local
371                )
372            }
373        }
374        Some(oxml::NodeKind::Attr(a)) => {
375            let name = doc.name(a.name).map_or("?", |n| n.local.as_str());
376            format!("{name}=\"{}\"", a.value)
377        }
378        Some(oxml::NodeKind::Text(t)) => truncate(t.trim(), 80),
379        Some(oxml::NodeKind::Comment(c)) => {
380            format!("<!--{}-->", truncate(c.trim(), 60))
381        }
382        _ => String::new(),
383    }
384}
385
386fn truncate(s: &str, max: usize) -> String {
387    if s.chars().count() <= max {
388        return s.to_owned();
389    }
390    let head: String = s.chars().take(max).collect();
391    format!("{head}…")
392}
393
394fn cmd_validate(
395    source: &str,
396    xsd_path: &str,
397    out: &mut dyn Write,
398    err: &mut dyn Write,
399) -> Result<ExitCode, String> {
400    let xsd = read_input(Some(xsd_path))?;
401    let schema = xmlschema::parse_schema(&xsd)
402        .map_err(|e| format!("bad schema: {e}"))?;
403    let doc = parse_or_report(source)?;
404    let report = xmlschema::validate(&doc, &schema);
405
406    if report.is_valid() {
407        let _ = writeln!(out, "valid");
408        return Ok(ExitCode::SUCCESS);
409    }
410    // Violations go to stderr so `oxml validate` can be used in a
411    // pipeline without the diagnostics contaminating the output.
412    let _ = writeln!(err, "{} violation(s):", report.violations.len());
413    for v in &report.violations {
414        let _ = writeln!(err, "  {} — {}", v.path, v.message);
415    }
416    Ok(ExitCode::from(1))
417}
418
419fn cmd_stats(source: &str, out: &mut dyn Write) -> Result<ExitCode, String> {
420    let doc = parse_or_report(source)?;
421    let mut elements = 0usize;
422    let mut attributes = 0usize;
423    let mut text = 0usize;
424    let mut comments = 0usize;
425    let mut namespaces = 0usize;
426    let mut others = 0usize;
427    let mut depth_max = 0usize;
428
429    for id in doc.descendants() {
430        match doc.kind(id) {
431            Some(oxml::NodeKind::Element { .. }) => {
432                elements += 1;
433                let mut d = 0usize;
434                let mut cur = Some(id);
435                while let Some(n) = cur {
436                    cur = doc.parent(n);
437                    d += 1;
438                }
439                depth_max = depth_max.max(d);
440            }
441            Some(oxml::NodeKind::Attr(_)) => attributes += 1,
442            Some(oxml::NodeKind::Text(_)) => text += 1,
443            Some(oxml::NodeKind::Comment(_)) => comments += 1,
444            Some(oxml::NodeKind::Namespace { .. }) => namespaces += 1,
445            // The root, and processing instructions. Reported as a
446            // remainder so the lines below add up to `nodes` -- see
447            // the note there.
448            _ => others += 1,
449        }
450    }
451
452    // Every kind is printed, including the ones a reader would not
453    // think to ask for. The counts previously stopped at comments,
454    // which left `nodes` two larger than the lines beneath it on any
455    // document with a namespace -- an apparent arithmetic error in
456    // the tool, and one that stood in the sample document shipped
457    // with the examples.
458    let _ = writeln!(out, "nodes       {}", doc.len());
459    let _ = writeln!(out, "elements    {elements}");
460    let _ = writeln!(out, "attributes  {attributes}");
461    let _ = writeln!(out, "text        {text}");
462    let _ = writeln!(out, "comments    {comments}");
463    let _ = writeln!(out, "namespaces  {namespaces}");
464    let _ = writeln!(out, "other       {others}");
465    let _ = writeln!(out, "max depth   {depth_max}");
466    debug_assert_eq!(
467        elements + attributes + text + comments + namespaces + others,
468        doc.len(),
469        "the breakdown must account for every node"
470    );
471    Ok(ExitCode::SUCCESS)
472}
473
474/// Infallible: a parse failure is a *result* here, not an error — the
475/// whole point of `check` is to report it and exit non-zero.
476fn cmd_check(
477    source: &str,
478    out: &mut dyn Write,
479    err: &mut dyn Write,
480) -> ExitCode {
481    match oxml::parse_with(source, oxml::Limits::strict()) {
482        Ok(doc) => {
483            let _ = writeln!(out, "well-formed ({} nodes)", doc.len());
484            ExitCode::SUCCESS
485        }
486        Err(e) => {
487            let (line, col) = e.line_column(source);
488            let _ = writeln!(err, "not well-formed at {line}:{col}: {e}");
489            ExitCode::from(1)
490        }
491    }
492}
493
494#[cfg(test)]
495mod tests;