aboutsummaryrefslogtreecommitdiff
path: root/src/executor.rs
blob: ee17bbf1a7c8b1e94a6ddbad88b8e110ea960673 (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
use crate::barbfile::BarbFile;

use std::collections::HashMap;
use std::env;
use ureq;

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

impl Context {
    pub fn new() -> Context {
        let mut vars = HashMap::new();
        vars.extend(env::vars());
        
        Context {
            vars
        }
    }

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

    fn key_str(&self, key: &String) -> String {
        format!("{{{}}}", key)
    }

    pub fn substitute(&self, string: &String) -> String {
        let mut buffer = string.clone();
        for (key, val) in self.vars.iter() {
            buffer = buffer.replace(self.key_str(key).as_str(), val);
        }

        buffer
    }
}

pub struct Executor {
    context: Context
}

impl Executor {
    pub fn new() -> Executor {
        Executor {
            context: Context::new()
        }
    }
    
    pub fn execute(&mut self, bfile: BarbFile) -> Result<ureq::Response, String> {
        let req = ureq::request(
            bfile.method_as_string().as_str(),
            self.context.substitute(&bfile.url()).as_str()
        );

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