tojson.rs 2.0 KB

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