Skip to main content

run_a_command/
run_a_command.rs

1//! Drive the CLI the way `main` does, but in-process.
2//!
3//! `oxml_cli::run` takes its output streams as parameters precisely so
4//! a caller can read back what the command produced without spawning a
5//! subprocess. This example is that caller.
6
7use std::process::ExitCode;
8
9fn main() {
10    let document = std::env::temp_dir().join("oxml-cli-example.xml");
11    std::fs::write(&document, "<catalogue><book>Dune</book></catalogue>")
12        .expect("writing the example document");
13
14    let args = vec![
15        "query".to_owned(),
16        "//book".to_owned(),
17        document.to_string_lossy().into_owned(),
18        "--text".to_owned(),
19    ];
20
21    let mut out = Vec::new();
22    let mut err = Vec::new();
23    let code = oxml_cli::run(&args, &mut out, &mut err)
24        .expect("the command should run");
25
26    print!("{}", String::from_utf8_lossy(&out));
27    assert_eq!(
28        String::from_utf8_lossy(&out).trim(),
29        "Dune",
30        "querying //book --text should print the element's text"
31    );
32    assert!(matches!(code, c if c == ExitCode::SUCCESS));
33
34    std::fs::remove_file(&document).expect("removing the example document");
35}