aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: f5abb692dcfe2b39a9a06aa14f9712efbb64a577 (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
mod barbfile;
mod executor;

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

fn run_file(args: &Args, executor: &mut Executor, file_name: &String) {
    let bfile = BarbFile::from_str(
        fs::read_to_string(file_name.as_str())
            .expect("Failed to read file")
            .as_str(),
    )
    .expect("Failed to parse file");
    let response = executor.execute(bfile).unwrap();

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

    if args.print_body() {
        println!(
            "{}",
            match args.raw_body() {
                true => String::from(response.into_string().unwrap().as_str()),
                false => format_json(
                    response.into_string().unwrap().as_str(),
                    Indentation::Default
                ),
            }
        );
    }
}

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

    let mut executor = Executor::new(Context::new(env::vars()));

    for file in args.files_iter() {
        run_file(&args, &mut executor, &file);
    }
}