Skip to main content

rewrite/
rewrite.rs

1//! Reads a DATEX II v3 document, XML or JSON, and writes it again, to show what the strict writers
2//! make of it: as XML, as DATEX II 3.7 JSON (`--json`) or for the Mobilithek (`--mobilithek`).
3//!
4//! ```text
5//! cargo run --release --example rewrite -- in.xml > out.xml
6//! cargo run --release --example rewrite -- --json in.xml > out.json
7//! ```
8
9use std::io::{BufReader, BufWriter, Write};
10
11use datex2::v3::{self, json};
12
13fn main() -> Result<(), Box<dyn std::error::Error>> {
14    let mut args: Vec<String> = std::env::args().skip(1).collect();
15    let format = match args.first().map(String::as_str) {
16        Some(f @ ("--json" | "--mobilithek")) => {
17            let f = f.to_owned();
18            args.remove(0);
19            f
20        }
21        _ => String::new(),
22    };
23    let path = args
24        .first()
25        .ok_or("usage: rewrite [--json | --mobilithek] <file>")?;
26    let input = BufReader::new(std::fs::File::open(path)?);
27    let doc = if path.ends_with(".json") {
28        json::read(input)?
29    } else {
30        v3::read(input)?
31    };
32    let mut out = BufWriter::new(std::io::stdout().lock());
33    for publication in &doc.publications {
34        match format.as_str() {
35            "--json" => json::write(&mut out, publication)?,
36            "--mobilithek" => json::mobilithek::write(&mut out, publication)?,
37            _ => v3::write(&mut out, publication)?,
38        }
39    }
40    out.flush()?;
41    Ok(())
42}