Skip to main content

convert_format/
convert_format.rs

1//! Convert contract documents between JSON and XML.
2//!
3//! Both formats deserialize into the same data model, so conversion is a
4//! transcode with no schema knowledge involved.
5//!
6//! ```bash
7//! cargo run --release --example convert_format -- in.json out.xml
8//! cargo run --release --example convert_format -- in.xml  out.json
9//! ```
10
11use std::process::ExitCode;
12
13use rustyqlib::core::serialization::{parse_value, render_value, Format};
14
15fn main() -> ExitCode {
16    let args: Vec<String> = std::env::args().collect();
17    if args.len() != 3 {
18        eprintln!("usage: convert_format <input.(json|xml)> <output.(json|xml)>");
19        return ExitCode::FAILURE;
20    }
21    let (input, output) = (&args[1], &args[2]);
22
23    let text = match std::fs::read_to_string(input) {
24        Ok(t) => t,
25        Err(e) => {
26            eprintln!("cannot read {input}: {e}");
27            return ExitCode::FAILURE;
28        }
29    };
30
31    let in_format = Format::from_path(input).unwrap_or_else(|| Format::detect(&text));
32    let out_format = match Format::from_path(output) {
33        Some(f) => f,
34        None => {
35            eprintln!("cannot infer output format from {output}: use a .json or .xml extension");
36            return ExitCode::FAILURE;
37        }
38    };
39
40    let value = match parse_value(&text, in_format) {
41        Ok(v) => v,
42        Err(e) => {
43            eprintln!("cannot parse {input} as {in_format:?}: {e}");
44            return ExitCode::FAILURE;
45        }
46    };
47
48    // "contracts" is the document element for contract files; it is only
49    // used when writing XML
50    let rendered = render_value(&value, out_format, "contracts");
51    if let Err(e) = std::fs::write(output, rendered) {
52        eprintln!("cannot write {output}: {e}");
53        return ExitCode::FAILURE;
54    }
55    println!("{input} ({in_format:?}) -> {output} ({out_format:?})");
56    ExitCode::SUCCESS
57}