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
use std::collections::HashMap;
use std::iter::FromIterator;
use errors::Result;
use serde_json::value::{to_value, Value};
use serde_json::{to_string, to_string_pretty};
use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, Utc};
use context::ValueRender;
pub fn length(value: Value, _: HashMap<String, Value>) -> Result<Value> {
match value {
Value::Array(arr) => Ok(to_value(&arr.len()).unwrap()),
Value::String(s) => Ok(to_value(&s.chars().count()).unwrap()),
_ => Ok(to_value(0).unwrap()),
}
}
pub fn reverse(value: Value, _: HashMap<String, Value>) -> Result<Value> {
match value {
Value::Array(mut arr) => {
arr.reverse();
Ok(to_value(&arr)?)
}
Value::String(s) => Ok(to_value(&String::from_iter(s.chars().rev()))?),
_ => bail!(
"Filter `reverse` received an incorrect type for arg `value`: \
got `{}` but expected Array|String",
value.to_string()
),
}
}
pub fn json_encode(value: Value, args: HashMap<String, Value>) -> Result<Value> {
let pretty = args.get("pretty").and_then(|v| v.as_bool()).unwrap_or(false);
if pretty {
Ok(Value::String(to_string_pretty(&value)?))
} else {
Ok(Value::String(to_string(&value)?))
}
}
pub fn date(value: Value, mut args: HashMap<String, Value>) -> Result<Value> {
let format = match args.remove("format") {
Some(val) => try_get_value!("date", "format", String, val),
None => "%Y-%m-%d".to_string(),
};
let formatted = match value {
Value::Number(n) => match n.as_i64() {
Some(i) => NaiveDateTime::from_timestamp(i, 0).format(&format),
None => bail!("Filter `date` was invoked on a float: {}", n),
},
Value::String(s) => {
if s.contains('T') {
match s.parse::<DateTime<FixedOffset>>() {
Ok(val) => val.format(&format),
Err(_) => match s.parse::<NaiveDateTime>() {
Ok(val) => val.format(&format),
Err(_) => {
bail!("Error parsing `{:?}` as rfc3339 date or naive datetime", s)
}
},
}
} else {
match NaiveDate::parse_from_str(&s, "%Y-%m-%d") {
Ok(val) => DateTime::<Utc>::from_utc(val.and_hms(0, 0, 0), Utc).format(&format),
Err(_) => bail!("Error parsing `{:?}` as YYYY-MM-DD date", s),
}
}
}
_ => bail!(
"Filter `date` received an incorrect type for arg `value`: \
got `{:?}` but expected i64|u64|String",
value
),
};
Ok(to_value(&formatted.to_string())?)
}
pub fn as_str(value: Value, _: HashMap<String, Value>) -> Result<Value> {
Ok(to_value(&value.render())?)
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{DateTime, Local};
use serde_json;
use serde_json::value::to_value;
use std::collections::HashMap;
#[test]
fn as_str_object() {
let map: HashMap<String, String> = HashMap::new();
let result = as_str(to_value(&map).unwrap(), HashMap::new());
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value(&"[object]").unwrap());
}
#[test]
fn as_str_vec() {
let result = as_str(to_value(&vec![1, 2, 3, 4]).unwrap(), HashMap::new());
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value(&"[1, 2, 3, 4]").unwrap());
}
#[test]
fn length_vec() {
let result = length(to_value(&vec![1, 2, 3, 4]).unwrap(), HashMap::new());
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value(&4).unwrap());
}
#[test]
fn length_str() {
let result = length(to_value(&"Hello World").unwrap(), HashMap::new());
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value(&11).unwrap());
}
#[test]
fn length_str_nonascii() {
let result = length(to_value(&"日本語").unwrap(), HashMap::new());
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value(&3).unwrap());
}
#[test]
fn length_num() {
let result = length(to_value(&15).unwrap(), HashMap::new());
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value(&0).unwrap());
}
#[test]
fn reverse_vec() {
let result = reverse(to_value(&vec![1, 2, 3, 4]).unwrap(), HashMap::new());
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value(&vec![4, 3, 2, 1]).unwrap());
}
#[test]
fn reverse_str() {
let result = reverse(to_value(&"Hello World").unwrap(), HashMap::new());
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value(&"dlroW olleH").unwrap());
}
#[test]
fn reverse_num() {
let result = reverse(to_value(&1.23).unwrap(), HashMap::new());
assert!(result.is_err());
assert_eq!(
result.err().unwrap().description(),
"Filter `reverse` received an incorrect type for arg `value`: got `1.23` but expected Array|String"
);
}
#[test]
fn date_default() {
let args = HashMap::new();
let result = date(to_value(1482720453).unwrap(), args);
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value("2016-12-26").unwrap());
}
#[test]
fn date_custom_format() {
let mut args = HashMap::new();
args.insert("format".to_string(), to_value("%Y-%m-%d %H:%M").unwrap());
let result = date(to_value(1482720453).unwrap(), args);
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value("2016-12-26 02:47").unwrap());
}
#[test]
fn date_rfc3339() {
let args = HashMap::new();
let dt: DateTime<Local> = Local::now();
let result = date(to_value(dt.to_rfc3339()).unwrap(), args);
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value(dt.format("%Y-%m-%d").to_string()).unwrap());
}
#[test]
fn date_rfc3339_preserves_timezone() {
let mut args = HashMap::new();
args.insert("format".to_string(), to_value("%Y-%m-%d %z").unwrap());
let result = date(to_value("1996-12-19T16:39:57-08:00").unwrap(), args);
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value("1996-12-19 -0800").unwrap());
}
#[test]
fn date_yyyy_mm_dd() {
let mut args = HashMap::new();
args.insert("format".to_string(), to_value("%a, %d %b %Y %H:%M:%S %z").unwrap());
let result = date(to_value("2017-03-05").unwrap(), args);
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value("Sun, 05 Mar 2017 00:00:00 +0000").unwrap());
}
#[test]
fn date_from_naive_datetime() {
let mut args = HashMap::new();
args.insert("format".to_string(), to_value("%a, %d %b %Y %H:%M:%S").unwrap());
let result = date(to_value("2017-03-05T00:00:00.602").unwrap(), args);
println!("{:?}", result);
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value("Sun, 05 Mar 2017 00:00:00").unwrap());
}
#[test]
fn test_json_encode() {
let args = HashMap::new();
let result =
json_encode(serde_json::from_str("{\"key\": [\"value1\", 2, true]}").unwrap(), args);
assert!(result.is_ok());
assert_eq!(result.unwrap(), to_value("{\"key\":[\"value1\",2,true]}").unwrap());
}
#[test]
fn test_json_encode_pretty() {
let mut args = HashMap::new();
args.insert("pretty".to_string(), to_value(true).unwrap());
let result =
json_encode(serde_json::from_str("{\"key\": [\"value1\", 2, true]}").unwrap(), args);
assert!(result.is_ok());
assert_eq!(
result.unwrap(),
to_value("{\n \"key\": [\n \"value1\",\n 2,\n true\n ]\n}").unwrap()
);
}
}