#![forbid(unsafe_code)]
use std::io::{Read as _, Write};
use std::process::ExitCode;
const USAGE: &str = "\
oxml — query, validate and inspect XML
USAGE:
oxml <COMMAND> [OPTIONS] [FILE]
COMMANDS:
query <XPATH> Evaluate an XPath expression
validate <XSD> Validate against an XML Schema
stats Summarise the document
check Report whether the document is well-formed
OPTIONS:
-t, --text Print matched nodes' text rather than a summary
-c, --count Print only the number of matches
-n, --ns P=URI Bind a namespace prefix for `query`, repeatable
-h, --help Show this message
-V, --version Show the version
FILE defaults to standard input, so oxml composes with pipes:
curl -s https://example.com/feed.xml | oxml query '//item/title' -t
EXIT STATUS:
0 success, and for `validate` the document conforms
1 the document is invalid, or no nodes matched
2 a usage or I/O error
";
pub fn run(
args: &[String],
out: &mut dyn Write,
err: &mut dyn Write,
) -> Result<ExitCode, String> {
if args.is_empty() || has_flag(args, "-h", "--help") {
let _ = write!(out, "{USAGE}");
return Ok(ExitCode::SUCCESS);
}
if has_flag(args, "-V", "--version") {
let _ = writeln!(out, "oxml {}", env!("CARGO_PKG_VERSION"));
return Ok(ExitCode::SUCCESS);
}
let namespaces = parse_namespace_bindings(args)?;
let positional = positional_args(args);
let command =
required(&positional, 0, "no command given; try `oxml --help`")?;
dispatch(command, &positional, args, &namespaces, out, err)
}
fn dispatch(
command: &str,
positional: &[&String],
args: &[String],
namespaces: &[(String, String)],
out: &mut dyn Write,
err: &mut dyn Write,
) -> Result<ExitCode, String> {
match command {
"query" => query_command(positional, args, namespaces, out),
"validate" => validate_command(positional, out, err),
"stats" => cmd_stats(&input_at(positional, 1)?, out),
"check" => Ok(cmd_check(&input_at(positional, 1)?, out, err)),
other => Err(format!("unknown command `{other}`; try `oxml --help`")),
}
}
fn query_command(
positional: &[&String],
args: &[String],
namespaces: &[(String, String)],
out: &mut dyn Write,
) -> Result<ExitCode, String> {
let expr = required(positional, 1, "query needs an XPath expression")?;
let source = input_at(positional, 2)?;
let text_only = has_flag(args, "-t", "--text");
let count_only = has_flag(args, "-c", "--count");
cmd_query(&source, expr, text_only, count_only, namespaces, out)
}
fn validate_command(
positional: &[&String],
out: &mut dyn Write,
err: &mut dyn Write,
) -> Result<ExitCode, String> {
let xsd_path = required(positional, 1, "validate needs a path to an .xsd")?;
let source = input_at(positional, 2)?;
cmd_validate(&source, xsd_path, out, err)
}
fn has_flag(args: &[String], short: &str, long: &str) -> bool {
args.iter().any(|a| a == short || a == long)
}
fn required<'a>(
positional: &[&'a String],
index: usize,
missing: &str,
) -> Result<&'a str, String> {
positional
.get(index)
.map(|s| s.as_str())
.ok_or_else(|| missing.to_owned())
}
fn input_at(positional: &[&String], index: usize) -> Result<String, String> {
read_input(positional.get(index).map(|s| s.as_str()))
}
fn read_input(path: Option<&str>) -> Result<String, String> {
if let Some(p) = path {
let file = std::fs::File::open(p)
.map_err(|e| format!("cannot read {p}: {e}"))?;
read_bounded(file, p)
} else {
read_bounded(std::io::stdin().lock(), "stdin")
}
}
fn read_bounded(
input: impl std::io::Read,
label: &str,
) -> Result<String, String> {
const MAX_INPUT_BYTES: usize = 8 * 1024 * 1024;
let mut buf = String::new();
let _ = input
.take((MAX_INPUT_BYTES + 1) as u64)
.read_to_string(&mut buf)
.map_err(|e| format!("cannot read {label}: {e}"))?;
if buf.len() > MAX_INPUT_BYTES {
return Err(format!("{label} exceeds the 8 MiB input limit"));
}
Ok(buf)
}
fn parse_or_report(source: &str) -> Result<oxml::Document, String> {
oxml::parse_with(source, oxml::Limits::strict()).map_err(|e| {
let (line, col) = e.line_column(source);
format!("{line}:{col}: {e}")
})
}
fn positional_args(args: &[String]) -> Vec<&String> {
let mut out: Vec<&String> = Vec::new();
let mut skip_next = false;
for arg in args {
if skip_next {
skip_next = false;
continue;
}
if arg == "-n" || arg == "--ns" {
skip_next = true;
continue;
}
if !arg.starts_with('-') {
out.push(arg);
}
}
out
}
fn explain_xpath_error(error: &oxml::XPathError) -> String {
if error.message.contains("unbound namespace prefix") {
let prefix = error
.message
.split('`')
.nth(1)
.unwrap_or("PREFIX")
.to_owned();
format!(
"bad XPath: unbound namespace prefix `{prefix}`; \
bind it with --ns {prefix}=URI"
)
} else {
format!("bad XPath: {error}")
}
}
fn parse_namespace_bindings(
args: &[String],
) -> Result<Vec<(String, String)>, String> {
let mut out: Vec<(String, String)> = Vec::new();
let mut expecting = false;
for arg in args {
if expecting {
expecting = false;
let Some((prefix, uri)) = arg.split_once('=') else {
return Err(format!(
"`{arg}` is not a namespace binding; write PREFIX=URI"
));
};
if prefix.is_empty() {
return Err("a namespace binding needs a prefix".to_owned());
}
if prefix == "xml" {
return Err(
"`xml` is bound by the specification and may not be \
rebound"
.to_owned(),
);
}
out.retain(|(p, _)| p != prefix);
out.push((prefix.to_owned(), uri.to_owned()));
} else if arg == "-n" || arg == "--ns" {
expecting = true;
}
}
if expecting {
return Err("`--ns` needs a PREFIX=URI argument".to_owned());
}
Ok(out)
}
fn evaluate_query(
source: &str,
expr: &str,
namespaces: &[(String, String)],
) -> Result<(oxml::Document, oxml::xpath::Value), String> {
let doc = parse_or_report(source)?;
let bindings: Vec<(&str, &str)> = namespaces
.iter()
.map(|(prefix, uri)| (prefix.as_str(), uri.as_str()))
.collect();
let xpath = oxml::XPath::compile_with_namespaces_and_limits(
expr,
&bindings,
&oxml::Limits::strict(),
)
.map_err(|e| explain_xpath_error(&e))?;
let context = oxml::xpath::EvalContext::new()
.with_limits(oxml::xpath::EvalLimits::default());
let value = xpath
.evaluate_with(&doc, &context)
.map_err(|e| e.to_string())?;
Ok((doc, value))
}
fn cmd_query(
source: &str,
expr: &str,
text_only: bool,
count_only: bool,
namespaces: &[(String, String)],
out: &mut dyn Write,
) -> Result<ExitCode, String> {
let (doc, value) = evaluate_query(source, expr, namespaces)?;
let Some(nodes) = value.nodes() else {
let _ = writeln!(out, "{}", value.to_str(&doc));
return Ok(ExitCode::SUCCESS);
};
if count_only {
let _ = writeln!(out, "{}", nodes.len());
return Ok(if nodes.is_empty() {
ExitCode::from(1)
} else {
ExitCode::SUCCESS
});
}
for &node in nodes {
let line = if text_only {
doc.text(node)
} else {
describe(&doc, node)
};
writeln!(out, "{line}").map_err(|e| e.to_string())?;
}
Ok(if nodes.is_empty() {
ExitCode::from(1)
} else {
ExitCode::SUCCESS
})
}
fn describe(doc: &oxml::Document, node: oxml::NodeId) -> String {
match doc.kind(node) {
Some(oxml::NodeKind::Element { .. }) => {
let Some(name) = doc.element_name(node) else {
return String::new();
};
let attrs: Vec<String> = doc
.attributes(node)
.iter()
.map(|a| {
let name =
doc.name(a.name).map_or("?", |n| n.local.as_str());
format!(" {name}=\"{}\"", a.value)
})
.collect();
let text = doc.text(node);
let preview = text.trim();
if preview.is_empty() {
format!("<{}{}/>", name.local, attrs.concat())
} else {
format!(
"<{}{}>{}</{}>",
name.local,
attrs.concat(),
truncate(preview, 60),
name.local
)
}
}
Some(oxml::NodeKind::Attr(a)) => {
let name = doc.name(a.name).map_or("?", |n| n.local.as_str());
format!("{name}=\"{}\"", a.value)
}
Some(oxml::NodeKind::Text(t)) => truncate(t.trim(), 80),
Some(oxml::NodeKind::Comment(c)) => {
format!("<!--{}-->", truncate(c.trim(), 60))
}
_ => String::new(),
}
}
fn truncate(s: &str, max: usize) -> String {
if s.chars().count() <= max {
return s.to_owned();
}
let head: String = s.chars().take(max).collect();
format!("{head}…")
}
fn cmd_validate(
source: &str,
xsd_path: &str,
out: &mut dyn Write,
err: &mut dyn Write,
) -> Result<ExitCode, String> {
let xsd = read_input(Some(xsd_path))?;
let schema = xmlschema::parse_schema(&xsd)
.map_err(|e| format!("bad schema: {e}"))?;
let doc = parse_or_report(source)?;
let report = xmlschema::validate(&doc, &schema);
if report.is_valid() {
let _ = writeln!(out, "valid");
return Ok(ExitCode::SUCCESS);
}
let _ = writeln!(err, "{} violation(s):", report.violations.len());
for v in &report.violations {
let _ = writeln!(err, " {} — {}", v.path, v.message);
}
Ok(ExitCode::from(1))
}
fn cmd_stats(source: &str, out: &mut dyn Write) -> Result<ExitCode, String> {
let doc = parse_or_report(source)?;
let mut elements = 0usize;
let mut attributes = 0usize;
let mut text = 0usize;
let mut comments = 0usize;
let mut namespaces = 0usize;
let mut others = 0usize;
let mut depth_max = 0usize;
for id in doc.descendants() {
match doc.kind(id) {
Some(oxml::NodeKind::Element { .. }) => {
elements += 1;
let mut d = 0usize;
let mut cur = Some(id);
while let Some(n) = cur {
cur = doc.parent(n);
d += 1;
}
depth_max = depth_max.max(d);
}
Some(oxml::NodeKind::Attr(_)) => attributes += 1,
Some(oxml::NodeKind::Text(_)) => text += 1,
Some(oxml::NodeKind::Comment(_)) => comments += 1,
Some(oxml::NodeKind::Namespace { .. }) => namespaces += 1,
_ => others += 1,
}
}
let _ = writeln!(out, "nodes {}", doc.len());
let _ = writeln!(out, "elements {elements}");
let _ = writeln!(out, "attributes {attributes}");
let _ = writeln!(out, "text {text}");
let _ = writeln!(out, "comments {comments}");
let _ = writeln!(out, "namespaces {namespaces}");
let _ = writeln!(out, "other {others}");
let _ = writeln!(out, "max depth {depth_max}");
debug_assert_eq!(
elements + attributes + text + comments + namespaces + others,
doc.len(),
"the breakdown must account for every node"
);
Ok(ExitCode::SUCCESS)
}
fn cmd_check(
source: &str,
out: &mut dyn Write,
err: &mut dyn Write,
) -> ExitCode {
match oxml::parse_with(source, oxml::Limits::strict()) {
Ok(doc) => {
let _ = writeln!(out, "well-formed ({} nodes)", doc.len());
ExitCode::SUCCESS
}
Err(e) => {
let (line, col) = e.line_column(source);
let _ = writeln!(err, "not well-formed at {line}:{col}: {e}");
ExitCode::from(1)
}
}
}
#[cfg(test)]
mod tests;