#![doc(html_root_url = "https://docs.rs/jen/1.7.1")]
use clap::{value_parser, Arg, ArgAction, Command};
use serde_json::Value;
use jen::error::Error;
use jen::generator::Generator;
use std::io::{self, Write};
fn main() {
if let Err(ref err) = run() {
eprintln!("{}", err);
}
}
fn run() -> Result<(), Error> {
let args = build_cli().get_matches();
let limit = args.get_one::<usize>("limit");
let textual = args.get_flag("textual");
let template = args
.get_one::<String>("template")
.expect("template argument should be provided")
.to_owned();
let mut counter = 0;
let stdout = io::stdout();
let mut stdout = stdout.lock();
for document in Generator::from_path(template)? {
let output = (!textual)
.then_some(&document)
.and_then(|document| serde_json::from_str(document).ok())
.and_then(|contents: Value| serde_json::to_vec(&contents).ok())
.unwrap_or_else(|| document.into_bytes());
let result = stdout
.write_all(&output)
.and_then(|_| stdout.write_all(b"\n"));
if let Err(ref err) = result {
if err.kind() == io::ErrorKind::BrokenPipe {
return Ok(());
}
result?;
}
counter += 1;
if let Some(limit) = limit {
if &counter >= limit {
break;
}
}
}
Ok(())
}
fn build_cli() -> Command {
Command::new("")
.name(env!("CARGO_PKG_NAME"))
.about(env!("CARGO_PKG_DESCRIPTION"))
.version(env!("CARGO_PKG_VERSION"))
.args(&[
Arg::new("limit")
.help("An upper limit of documents to generate")
.short('l')
.long("limit")
.num_args(1)
.value_parser(value_parser!(usize)),
Arg::new("textual")
.help("Treat the input as textual, without JSON detection")
.short('t')
.long("textual")
.action(ArgAction::SetTrue),
Arg::new("template")
.help("Template to control generation format")
.required(true),
])
.arg_required_else_help(true)
.hide_possible_values(true)
}