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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
//! ## Overview
//!
//! [jq] is a command line tool which allows users to write small filter/transform
//! programs with a special DSL to extract data from json.
//!
//! This crate provides bindings to the C API internals to give us programmatic
//! access to this tool.
//!
//! For example, given a blob of json data, we can extract the values from
//! the `id` field of a series of objects.
//!
//! ```
//! let data = r#"{
//!     "colors": [
//!         {"id": 12, "name": "cyan"},
//!         {"id": 34, "name": "magenta"},
//!         {"id": 56, "name": "yellow"},
//!         {"id": 78, "name": "black"}
//!     ]
//! }"#;
//!
//! let output = json_query::run("[.colors[].id]", data).unwrap();
//! assert_eq!("[12,34,56,78]", &output);
//! ```
//!
//! For times where you want to run the same jq program against multiple inputs, `compile()`
//! returns a handle to the compiled jq program.
//!
//! ```
//! let tv_shows = r#"[
//!     {"title": "Twilight Zone"},
//!     {"title": "X-Files"},
//!     {"title": "The Outer Limits"}
//! ]"#;
//!
//! let movies = r#"[
//!     {"title": "The Omen"},
//!     {"title": "Amityville Horror"},
//!     {"title": "The Thing"}
//! ]"#;
//!
//! let mut program = json_query::compile("[.[].title] | sort").unwrap();
//!
//! assert_eq!(
//!     r#"["The Outer Limits","Twilight Zone","X-Files"]"#,
//!     &program.run(tv_shows).unwrap()
//! );
//!
//! assert_eq!(
//!     r#"["Amityville Horror","The Omen","The Thing"]"#,
//!     &program.run(movies).unwrap()
//! );
//! ```
//!
//! The output from these jq programs are returned as a string (just as is
//! the case if you were using [jq] from the command-line), so be prepared to
//! parse the output as needed after this step.
//!
//! Pairing this crate with something like [serde_json] might make a lot of
//! sense.
//!
//! See the [jq site][jq] for details on the jq program syntax.
//!
//! ## Linking to `libjq`
//!
//! When the `bundled` feature is enabled (on by default) `libjq` is provided and
//! linked statically by [jq-sys] and [jq-src]
//! which require having autotools and gcc in `PATH` to build.
//!
//! If you disable the `bundled` feature, you will need to ensure your crate
//! links to `libjq` in order for the bindings to work.
//! For this you may need to add a `build.rs` script if you don't have one already.
//!
//! [jq]: https://stedolan.github.io/jq/
//! [serde_json]: https://github.com/serde-rs/json
//! [jq-sys]: https://github.com/onelson/jq-sys
//! [jq-src]: https://github.com/onelson/jq-src
//!
extern crate jq_sys;

#[cfg(test)]
#[macro_use]
extern crate serde_json;

use jq::JqState;
use std::ffi::CString;

mod jq {
    use jq_sys::{
        self, jq_next, jv_copy, jv_dump_string, jv_invalid_get_msg, jv_parser_next, jv_string_value,
    };
    use std::ffi::{CStr, CString};
    use std::os::raw::c_char;

    pub type JqValue = ::jq_sys::jv;
    pub type JqState = ::jq_sys::jq_state;

    mod jv {
        use super::JqValue;
        use jq_sys;

        pub fn value_is_valid(value: JqValue) -> bool {
            unsafe { jq_sys::jv_get_kind(value) != jq_sys::jv_kind_JV_KIND_INVALID }
        }

        pub fn invalid_has_msg(value: JqValue) -> bool {
            unsafe { jq_sys::jv_invalid_has_msg(value) == 1 }
        }
    }

    pub fn init() -> *mut JqState {
        unsafe { jq_sys::jq_init() }
    }

    pub fn teardown(state: *mut *mut JqState) {
        unsafe { jq_sys::jq_teardown(state) }
    }

    pub fn load_string(state: *mut *mut JqState, buf: CString) -> Result<String, String> {
        unsafe {
            let parser = jq_sys::jv_parser_new(0);
            let len = buf.as_bytes().len() as i32;
            jq_sys::jv_parser_set_buf(parser, buf.as_ptr(), len, 0);
            let res = parse(state, parser);
            jq_sys::jv_parser_free(parser);
            res
        }
    }

    /// Takes a pointer to a nul term string, and attempts to convert it to a String.
    unsafe fn get_string_value(value: *const c_char) -> Result<String, ::std::str::Utf8Error> {
        let s = CStr::from_ptr(value).to_str()?;
        Ok(s.to_owned())
    }

    /// Frees a jv and extracts any error info as it does so.
    ///
    /// `Err` with the reason if the thing was trash.
    unsafe fn check(value: JqValue) -> Result<(), String> {
        if jv::invalid_has_msg(jv_copy(value)) {
            let msg = jv_invalid_get_msg(value);
            let reason = format!(
                "parse error: {}",
                get_string_value(jv_string_value(msg)).unwrap_or_else(|_| "unknown".into())
            );
            let ret = Err(reason);
            jq_sys::jv_free(msg);
            return ret;
        } else {
            jq_sys::jv_free(value);
        }
        Ok(())
    }

    /// Renders the data from the parser and pushes it into the buffer.
    unsafe fn dump(
        state: *mut *mut JqState,
        initial_value: JqValue,
        buf: &mut String,
    ) -> Result<(), String> {
        let mut value = initial_value;
        while jv::value_is_valid(value) {
            let dumped = jv_dump_string(value, 0);
            match get_string_value(jv_string_value(dumped)) {
                Ok(s) => buf.push_str(&s),
                Err(e) => return Err(format!("parse error: {}", e)),
            };
            value = jq_next(*state);
        }
        check(value)
    }

    /// Unwind the parser and return the rendered result.
    ///
    /// When this results in `Err`, the String value should contain a message about
    /// what failed.
    unsafe fn parse(
        state: *mut *mut JqState,
        parser: *mut jq_sys::jv_parser,
    ) -> Result<String, String> {
        let mut buf = String::new();
        let mut value = jv_parser_next(parser);
        while jv::value_is_valid(value) {
            jq_sys::jq_start(*state, value, 0);
            if let Err(reason) = dump(state, jq_next(*state), &mut buf) {
                // outer loop item needs freeing during early return
                jq_sys::jv_free(value);
                return Err(reason);
            }
            value = jv_parser_next(parser);
        }
        check(value)?;
        Ok(buf)
    }

    pub fn compile_program(state: *mut *mut JqState, program: CString) -> Result<(), String> {
        unsafe {
            if jq_sys::jq_compile(*state, program.as_ptr()) == 0 {
                Err("syntax error: JQ Program failed to compile.".into())
            } else {
                Ok(())
            }
        }
    }
}

/// Run a jq program on a blob of json data.
///
/// In the case of failure to run the program, feedback from the jq api will be
/// available in the supplied `String` value.
/// Failures can occur for a variety of reasons, but mostly you'll see them as
/// a result of bad jq program syntax, or invalid json data.
pub fn run(program: &str, data: &str) -> Result<String, String> {
    let mut state = jq::init();
    let buf = CString::new(data).map_err(|_| "unable to convert data to c string.".to_string())?;
    let prog =
        CString::new(program).map_err(|_| "unable to convert data to c string.".to_string())?;

    jq::compile_program(&mut state, prog)?;
    let res = jq::load_string(&mut state, buf);
    jq::teardown(&mut state);
    res
}

/// A pre-compiled jq program which can be run against different inputs.
pub struct JqProgram {
    state: *mut JqState,
}

impl JqProgram {
    /// Runs a json string input against a pre-compiled jq program.
    pub fn run(&mut self, data: &str) -> Result<String, String> {
        let buf =
            CString::new(data).map_err(|_| "unable to convert data to c string.".to_string())?;
        let res = jq::load_string(&mut self.state, buf);
        res
    }
}

impl Drop for JqProgram {
    fn drop(&mut self) {
        jq::teardown(&mut self.state);
    }
}

/// Compile a jq program then reuse it, running several inputs against it.
pub fn compile(program: &str) -> Result<JqProgram, String> {
    let mut state = jq::init();
    let prog =
        CString::new(program).map_err(|_| "unable to convert data to c string.".to_string())?;

    jq::compile_program(&mut state, prog)?;
    Ok(JqProgram { state })
}

#[cfg(test)]
mod test {
    use super::{compile, run};
    use serde_json;

    #[test]
    fn reuse_compiled_program() {
        let query = r#"if . == 0 then "zero" elif . == 1 then "one" else "many" end"#;
        let mut prog = compile(&query).unwrap();
        assert_eq!(prog.run("2").unwrap(), r#""many""#);
        assert_eq!(prog.run("1").unwrap(), r#""one""#);
        assert_eq!(prog.run("0").unwrap(), r#""zero""#);
    }

    #[test]
    fn jq_state_is_not_global() {
        let input = r#"{"id": 123, "name": "foo"}"#;
        let query1 = r#".name"#;
        let query2 = r#".id"#;

        // Basically this test is just to check that the state pointers returned by
        // `jq::init()` are completely independent and don't share any global state.
        let mut prog1 = compile(&query1).unwrap();
        let mut prog2 = compile(&query2).unwrap();

        assert_eq!(prog1.run(input).unwrap(), r#""foo""#);
        assert_eq!(prog2.run(input).unwrap(), r#"123"#);
        assert_eq!(prog1.run(input).unwrap(), r#""foo""#);
        assert_eq!(prog2.run(input).unwrap(), r#"123"#);
    }

    fn get_movies() -> serde_json::Value {
        json!({
            "movies": [
                { "title": "Coraline", "year": 2009 },
                { "title": "ParaNorman", "year": 2012 },
                { "title": "Boxtrolls", "year": 2014 },
                { "title": "Kubo and the Two Strings", "year": 2016 },
                { "title": "Missing Link", "year": 2019 }
            ]
        })
    }

    #[test]
    fn identity_nothing() {
        assert_eq!(run(".", ""), Ok("".to_string()));
    }

    #[test]
    fn identity_empty() {
        assert_eq!(run(".", "{}"), Ok("{}".to_string()));
    }

    #[test]
    fn extract_dates() {
        let data = get_movies();
        let query = "[.movies[].year]";
        let output = run(query, &data.to_string()).unwrap();
        let parsed: Vec<i64> = serde_json::from_str(&output).unwrap();
        assert_eq!(vec![2009, 2012, 2014, 2016, 2019], parsed);
    }

    #[test]
    fn extract_name() {
        let res = run(".name", r#"{"name": "test"}"#);
        assert_eq!(res, Ok(r#""test""#.to_string()));
    }

    #[test]
    fn compile_error() {
        let res = run(". aa12312me  dsaafsdfsd", "{\"name\": \"test\"}");
        assert!(res.is_err());
    }

    #[test]
    fn parse_error() {
        let res = run(".", "{1233 invalid json ahoy : est\"}");
        assert!(res.is_err());
    }

    #[test]
    fn just_open_brace() {
        let res = run(".", "{");
        assert!(res.is_err());
    }

    #[test]
    fn just_close_brace() {
        let res = run(".", "}");
        assert!(res.is_err());
    }

    #[test]
    fn total_garbage() {
        let data = r#"
        {
            moreLike: "an object literal but also bad"
            loveToDangleComma: true,
        }"#;

        let res = run(".", data);
        assert!(res.is_err());
    }
}