-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathminify.rs
More file actions
81 lines (67 loc) · 2.05 KB
/
minify.rs
File metadata and controls
81 lines (67 loc) · 2.05 KB
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
use crate::tokenizer::{Kind, Token, TokenStream};
use combine::StreamOnce;
use thiserror::Error;
/// Error minifying query
#[derive(Error, Debug)]
#[error("query minify error: {}", _0)]
pub struct MinifyError(String);
pub fn minify_query(source: String) -> Result<String, MinifyError> {
let mut bits: Vec<&str> = Vec::new();
let mut stream = TokenStream::new(source.as_str());
let mut prev_was_punctuator = false;
loop {
match stream.uncons() {
Ok(x) => {
let token: Token = x;
let is_non_punctuator = token.kind != Kind::Punctuator;
if prev_was_punctuator && is_non_punctuator {
bits.push(" ");
}
bits.push(token.value);
prev_was_punctuator = is_non_punctuator;
}
Err(ref e) if e == &combine::easy::Error::end_of_input() => break,
Err(e) => return Err(MinifyError(e.to_string())),
}
}
Ok(bits.join(""))
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
#[test]
fn strip_ignored_characters() {
let source = "
query SomeQuery($foo: String!, $bar: String) {
someField(foo: $foo, bar: $bar) {
a
b {
... on B {
c
d
}
}
}
}
";
let minified = super::minify_query(source.to_string()).expect("minification failed");
assert_eq!(
&minified,
"query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{...on B{c d}}}}"
);
}
#[test]
fn unexpected_token() {
let source = "
query foo {
bar;
}
";
let minified = super::minify_query(source.to_string());
assert!(minified.is_err());
assert_eq!(
minified.unwrap_err().to_string(),
"query minify error: Unexpected unexpected character ';'"
);
}
}