diff options
Diffstat (limited to 'src/main.rs')
-rw-r--r-- | src/main.rs | 26 |
1 files changed, 22 insertions, 4 deletions
diff --git a/src/main.rs b/src/main.rs index f3891ad..a35ad7d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ mod barbfile; mod executor; +use jq_rs; use jsonformat::{format_json, Indentation}; use std::slice::Iter; @@ -24,6 +25,8 @@ struct Args { body: bool, #[clap(short, long)] raw: bool, + #[clap(short, long)] + filter: Option<String>, files: Vec<String>, } @@ -48,6 +51,20 @@ impl Args { { self.files.iter() } + + pub fn jq_filter(&self) -> &Option<String> + { + &self.filter + } +} + +fn apply_filters(args: &Args, bfile: &BarbFile, body: String) -> Result<String, String> { + if let Some(filter) = args.jq_filter() { + return Ok(jq_rs::run(filter.as_str(), body.as_str()).map_err(|x| x.to_string())?); + } else if let Some(filter) = bfile.filter() { + return Ok(jq_rs::run(filter.as_str(), body.as_str()).map_err(|x| x.to_string())?); + } + Ok(String::from(body)) } fn run_file(args: &Args, executor: &mut Executor, file_name: &String) -> Result<(), String> { @@ -56,7 +73,7 @@ fn run_file(args: &Args, executor: &mut Executor, file_name: &String) -> Result< .map_err(|_| format!("Failed to read file '{}'", file_name))? .as_str(), ).map_err(|_| format!("Failed to parse file '{}'", file_name))?; - let response = executor.execute(bfile, args.req_headers())?; + let response = executor.execute(&bfile, args.req_headers())?; if args.print_headers() { println!("{} {}", response.status(), response.status_text()); @@ -71,12 +88,13 @@ fn run_file(args: &Args, executor: &mut Executor, file_name: &String) -> Result< } if args.print_body() { + let body = apply_filters(args, &bfile, response.into_string().unwrap())?; println!( "{}", match args.raw_body() { - true => String::from(response.into_string().unwrap().as_str()), + true => body, false => format_json( - response.into_string().unwrap().as_str(), + body.as_str(), Indentation::Default ), } @@ -92,7 +110,7 @@ fn main() { let mut executor = Executor::new(Context::new(env::vars())); for file in args.files_iter() { - match run_file(&args, &mut executor, &file) { + match run_file(&args, &mut executor, file) { Ok(()) => (), Err(err) => println!("{}", err) } |