tojson.rs 2.3 KB

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