1#![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
45pub 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
79fn 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
97fn 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
111fn 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
122fn has_flag(args: &[String], short: &str, long: &str) -> bool {
124 args.iter().any(|a| a == short || a == long)
125}
126
127fn 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
139fn input_at(positional: &[&String], index: usize) -> Result<String, String> {
141 read_input(positional.get(index).map(|s| s.as_str()))
142}
143
144fn 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
178fn 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
212fn 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 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 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
340fn describe(doc: &oxml::Document, node: oxml::NodeId) -> String {
342 match doc.kind(node) {
343 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 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 _ => others += 1,
449 }
450 }
451
452 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
474fn 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;