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

use jsonformat::{format_json, Indentation};

use barbfile::BarbFile;

use clap::Parser;

use std::collections::HashMap;
use std::env;
use std::fs;
use std::str::FromStr;
use ureq;

struct Context {
    vars: HashMap<String, String>,
}

impl Context {
    pub fn new() -> Context {
        Context {
            vars: HashMap::new(),
        }
    }

    pub fn get_var(&self, name: String) -> Option<String> {
        self.vars
            .get(&name)
            .map(|val| val.clone())
            .or_else(|| env::var(name).ok())
    }

    pub fn execute(&self, bfile: BarbFile) -> Result<ureq::Response, String> {
        let req = ureq::request(bfile.method_as_string().as_str(), &bfile.url());

        match bfile.method().takes_body() {
            true => match bfile.body() {
                Some(body) => req.send_string(body.as_str()),
                None => req.call(),
            },
            false => req.call(),
        }
        .map_err(|_| String::from("Error"))
    }
}

#[derive(Parser, Debug)]
#[clap(version)]
struct Args {
    #[clap(short, long)]
    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.body
    }

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

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

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

    let context = Context::new();
    let bfile = BarbFile::from_str(
        fs::read_to_string("test.barb")
            .expect("Failed to read file")
            .as_str(),
    )
    .expect("Failed to parse file");
    let response = context.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
                ),
            }
        );
    }
}