1use std::collections::HashMap;
2use std::time::SystemTime;
3
4use gtmpl::gtmpl_fn;
5use gtmpl_value::{FuncError, Value};
6
7gtmpl_fn!(
8 #[doc = r#"Similar to golangs current time.Time. Not fully supported."#]
9 fn now() -> Result<Value, FuncError> {
10 let mut map = HashMap::new();
11 let ts = SystemTime::now()
12 .duration_since(SystemTime::UNIX_EPOCH)
13 .map_err(|e| FuncError::Generic(e.to_string()))?
14 .as_secs();
15 map.insert(String::from("Unix"), Value::from(ts));
16 Ok(map.into())
17 }
18);
19
20#[cfg(test)]
21mod test {
22 use super::*;
23 use gtmpl_value::FromValue;
24
25 #[test]
26 fn test_now_unix() {
27 let ts1 = SystemTime::now()
28 .duration_since(SystemTime::UNIX_EPOCH)
29 .map_err(|e| format!("{}", e))
30 .unwrap()
31 .as_secs();
32 let no_arg: Vec<Value> = vec![];
33 let n = now(&no_arg).unwrap();
34 let h: HashMap<String, u64> = HashMap::from_value(&n).unwrap();
35 let ts2 = *h.get("Unix").unwrap();
36 let ts3 = SystemTime::now()
37 .duration_since(SystemTime::UNIX_EPOCH)
38 .map_err(|e| format!("{}", e))
39 .unwrap()
40 .as_secs();
41 assert!(ts2 >= ts1);
42 assert!(ts3 >= ts2);
43 }
44}