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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use super::*;

struct GraphQLHelper {
    repo_path: std::path::PathBuf,
    ref_prefix: String,
    headref: String,
}

impl GraphQLHelper {
    fn josh_helper(
        &self,
        hash: &std::collections::BTreeMap<&str, handlebars::PathAndJson>,
        template_name: &str,
    ) -> JoshResult<serde_json::Value> {
        let path = if let Some(f) = hash.get("file") {
            f.render()
        } else {
            return Err(josh_error("missing pattern"));
        };

        let path = std::path::PathBuf::from(template_name)
            .join("..")
            .join(path);
        let path = normalize_path(&path);

        let transaction = cache::Transaction::open(&self.repo_path, Some(&self.ref_prefix))?;

        let reference = transaction.repo().find_reference(&self.headref)?;
        let tree = reference.peel_to_tree()?;

        let blob = tree
            .get_path(&path)?
            .to_object(transaction.repo())?
            .peel_to_blob()
            .map(|x| x.content().to_vec())
            .unwrap_or_default();
        let query = String::from_utf8(blob)?;

        let mut variables = juniper::Variables::new();

        for (k, v) in hash.iter() {
            variables.insert(k.to_string(), juniper::InputValue::scalar(v.render()));
        }

        let transaction = cache::Transaction::open(&self.repo_path, None)?;
        let (res, _errors) = juniper::execute_sync(
            &query,
            None,
            &graphql::commit_schema(reference.target().ok_or(josh_error("missing target"))?),
            &variables,
            &graphql::context(transaction),
        )?;

        let j = serde_json::to_string(&res)?;
        let j: serde_json::Value = serde_json::from_str(&j)?;

        let j = if let Some(at) = hash.get("at") {
            j.pointer(&at.render()).unwrap_or(&json!({})).to_owned()
        } else {
            j
        };

        Ok(j)
    }
}

impl handlebars::HelperDef for GraphQLHelper {
    fn call_inner<'reg: 'rc, 'rc>(
        &self,
        h: &handlebars::Helper,
        _: &handlebars::Handlebars,
        _: &handlebars::Context,
        rc: &mut handlebars::RenderContext,
    ) -> Result<handlebars::ScopedJson<'reg, 'rc>, handlebars::RenderError> {
        return Ok(handlebars::ScopedJson::Derived(
            self.josh_helper(
                h.hash(),
                rc.get_current_template_name().unwrap_or(&"/".to_owned()),
            )
            .map_err(|_| handlebars::RenderError::new("josh"))?,
        ));
    }
}

mod helpers {
    handlebars_helper!(concat_helper: |x: str, y: str| format!("{}{}", x, y) );
}

pub fn render(
    repo: &git2::Repository,
    ref_prefix: &str,
    headref: &str,
    query_and_params: &str,
) -> JoshResult<Option<String>> {
    let mut parameters = query_and_params.split('&');
    let query = parameters
        .next()
        .ok_or(josh_error(&format!("invalid query {:?}", query_and_params)))?;
    let mut split = query.splitn(2, '=');
    let cmd = split
        .next()
        .ok_or(josh_error(&format!("invalid query {:?}", query_and_params)))?;
    let path = split
        .next()
        .ok_or(josh_error(&format!("invalid query {:?}", query_and_params)))?;
    let reference = repo.find_reference(headref)?;
    let tree = reference.peel_to_tree()?;

    let obj = ok_or!(
        tree.get_path(&std::path::PathBuf::from(path))?
            .to_object(repo),
        {
            return Ok(None);
        }
    );

    let mut params = std::collections::BTreeMap::new();
    for p in parameters {
        let mut split = p.splitn(2, '=');
        let name = split
            .next()
            .ok_or(josh_error(&format!("invalid query {:?}", query_and_params)))?;
        let value = split
            .next()
            .ok_or(josh_error(&format!("invalid query {:?}", query_and_params)))?;
        params.insert(name.to_string(), value.to_string());
    }

    let template = if let Ok(blob) = obj.peel_to_blob() {
        let template = std::str::from_utf8(blob.content())?;
        if cmd == "get" {
            return Ok(Some(template.to_string()));
        }
        if cmd == "graphql" {
            let mut variables = juniper::Variables::new();

            for (k, v) in params {
                variables.insert(k.to_string(), juniper::InputValue::scalar(v));
            }
            let transaction = cache::Transaction::open(repo.path(), None)?;
            let (res, _errors) = juniper::execute_sync(
                &template.to_string(),
                None,
                &graphql::commit_schema(reference.target().ok_or(josh_error("missing target"))?),
                &variables,
                &graphql::context(transaction),
            )?;

            let j = serde_json::to_string_pretty(&res)?;
            return Ok(Some(j));
        }
        if cmd == "render" {
            template.to_string()
        } else {
            return Err(josh_error("no such cmd"));
        }
    } else {
        return Ok(Some("".to_string()));
    };

    std::mem::drop(obj);
    std::mem::drop(tree);

    let mut handlebars = handlebars::Handlebars::new();
    handlebars.register_template_string(path, template)?;
    handlebars.register_helper("concat", Box::new(helpers::concat_helper));
    handlebars.register_helper(
        "graphql",
        Box::new(GraphQLHelper {
            repo_path: repo.path().to_owned(),
            ref_prefix: ref_prefix.to_owned(),
            headref: headref.to_string(),
        }),
    );
    handlebars.set_strict_mode(true);

    match handlebars.render(path, &json!(params)) {
        Ok(res) => Ok(Some(res)),
        Err(res) => return Err(josh_error(&format!("{}", res))),
    }
}