1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
mod barbfile;
mod executor;
mod output;
use jq_rs;
use std::slice::Iter;
use barbfile::BarbFile;
use executor::{Context, Executor};
use output::BarbOutput;
use clap::Parser;
use std::env;
use std::fs;
use std::str::FromStr;
use dotenv::dotenv;
#[derive(Parser, Debug)]
#[clap(version)]
struct Args {
#[clap(short, long)]
headers: bool,
#[clap(short, long)]
all_headers: bool,
#[clap(short, long)]
body: bool,
#[clap(short, long)]
raw: bool,
#[clap(short, long)]
filter: Option<String>,
#[clap(short, long)]
path: Option<String>,
#[clap(short, long)]
no_color: bool,
files: Vec<String>,
}
impl Args {
pub fn files_iter(&self) -> Iter<String> {
self.files.iter()
}
pub fn jq_filter(&self) -> &Option<String> {
&self.filter
}
pub fn output(&self) -> BarbOutput {
BarbOutput::new(
!self.body,
self.all_headers,
self.headers || self.all_headers || !self.body,
!self.headers || self.body,
self.raw,
!self.no_color,
)
}
}
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> {
let bfile = BarbFile::from_str(
fs::read_to_string(file_name.as_str())
.map_err(|_| format!("Failed to read file '{}'", file_name))?
.as_str(),
)
.map_err(|_| format!("Failed to parse file '{}'", file_name))?;
let output = args.output();
let response = executor.execute(&bfile, &output)?;
output.status(response.status(), response.status_text());
for header_name in response.headers_names() {
output.resp_hdr(
header_name.to_string(),
response.header(header_name.as_str()).unwrap(),
);
}
output.end_resp_hdr();
output.body(apply_filters(
args,
&bfile,
response.into_string().unwrap(),
)?);
Ok(())
}
fn main() {
let args = Args::parse();
dotenv().ok();
let mut executor = Executor::new(Context::new(env::vars()));
for file in args.files_iter() {
match run_file(&args, &mut executor, file) {
Ok(()) => (),
Err(err) => println!("{}", err),
}
}
}
|