tojson.rs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. extern crate clap;
  2. extern crate rrecutils;
  3. extern crate serde_json;
  4. mod common;
  5. use std::fmt;
  6. use serde_json::Value;
  7. use serde_json::map::Map;
  8. fn record_to_json(rec: &rrecutils::Record) -> Value {
  9. let mut m = Map::new();
  10. for tup in rec.fields.iter() {
  11. let k = tup.0.clone();
  12. let v = tup.1.clone();
  13. m.insert(k, Value::String(v));
  14. }
  15. Value::Object(m)
  16. }
  17. fn unwrap_err<L, R: fmt::Debug>(value: Result<L, R>) -> L {
  18. match value {
  19. Ok(v) => v,
  20. Err(err) => {
  21. println!("{:?}", err);
  22. std::process::exit(99)
  23. }
  24. }
  25. }
  26. fn main() {
  27. let matches = clap::App::new("rr-to-json")
  28. .version(common::VERSION)
  29. .author(common::AUTHOR)
  30. .about("Display the Rust AST for a Recutils file")
  31. .arg(clap::Arg::with_name("pretty")
  32. .short("p")
  33. .long("pretty")
  34. .help("Pretty-print the resulting JSON"))
  35. .arg(clap::Arg::with_name("input")
  36. .short("i")
  37. .long("input")
  38. .value_name("FILE")
  39. .help("The input recfile (or - for stdin)"))
  40. .arg(clap::Arg::with_name("output")
  41. .short("o")
  42. .long("output")
  43. .value_name("FILE")
  44. .help("The desired output location (or - for stdout)"))
  45. .get_matches();
  46. let input = unwrap_err(common::input_from_spec(
  47. matches.value_of("input")));
  48. let mut output = unwrap_err(common::output_from_spec(
  49. matches.value_of("output")));
  50. let json = Value::Array(
  51. unwrap_err(rrecutils::Recfile::parse(input))
  52. .records
  53. .iter()
  54. .map(|x| record_to_json(x))
  55. .collect());
  56. let serialized = if matches.is_present("pretty") {
  57. unwrap_err(serde_json::to_string_pretty(&json))
  58. } else {
  59. json.to_string()
  60. };
  61. unwrap_err(writeln!(output, "{}", serialized));
  62. }