aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: a35ad7d86d573f32e5c6c960286a544fab3d1ffa (plain)
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
110
111
112
113
114
115
116
117
118
mod barbfile;
mod executor;

use jq_rs;
use jsonformat::{format_json, Indentation};
use std::slice::Iter;

use barbfile::BarbFile;
use executor::{Context, Executor};

use clap::Parser;

use std::env;
use std::fs;
use std::str::FromStr;

#[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>,
    files: Vec<String>,
}

impl Args {
    pub fn print_headers(&self) -> bool {
        self.headers || self.all_headers || !self.body
    }

    pub fn print_body(&self) -> bool {
        !self.headers || self.body
    }

    pub fn raw_body(&self) -> bool {
        self.raw
    }

    pub fn req_headers(&self) -> bool {
        self.all_headers
    }

    pub fn files_iter(&self) -> Iter<String>
    {
        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> {
    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 response = executor.execute(&bfile, args.req_headers())?;

    if args.print_headers() {
        println!("{} {}", response.status(), response.status_text());
        for header_name in response.headers_names() {
            println!(
                "{}: {}",
                header_name,
                // Header is guaranteed to exist 
                response.header(header_name.as_str()).unwrap()
            );
        }
    }

    if args.print_body() {
        let body = apply_filters(args, &bfile, response.into_string().unwrap())?;
        println!(
            "{}",
            match args.raw_body() {
                true => body,
                false => format_json(
                    body.as_str(),
                    Indentation::Default
                ),
            }
        );
    }

    Ok(())
}

fn main() {
    let args = Args::parse();

    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)
        }
    }
}