You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

496 lines
16KB

  1. extern crate serde_json;
  2. extern crate toml;
  3. use utils::de::fix_toml_dates;
  4. use utils::fs::{get_file_time, is_path_in_directory, read_file};
  5. use reqwest::{header, Client};
  6. use std::collections::hash_map::DefaultHasher;
  7. use std::fmt;
  8. use std::hash::{Hash, Hasher};
  9. use std::str::FromStr;
  10. use url::Url;
  11. use std::path::PathBuf;
  12. use std::sync::{Arc, Mutex};
  13. use csv::Reader;
  14. use std::collections::HashMap;
  15. use tera::{from_value, to_value, Error, Function as TeraFn, Map, Result, Value};
  16. static GET_DATA_ARGUMENT_ERROR_MESSAGE: &str =
  17. "`load_data`: requires EITHER a `path` or `url` argument";
  18. enum DataSource {
  19. Url(Url),
  20. Path(PathBuf),
  21. }
  22. #[derive(Debug)]
  23. enum OutputFormat {
  24. Toml,
  25. Json,
  26. Csv,
  27. Plain,
  28. }
  29. impl fmt::Display for OutputFormat {
  30. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  31. fmt::Debug::fmt(self, f)
  32. }
  33. }
  34. impl Hash for OutputFormat {
  35. fn hash<H: Hasher>(&self, state: &mut H) {
  36. self.to_string().hash(state);
  37. }
  38. }
  39. impl FromStr for OutputFormat {
  40. type Err = Error;
  41. fn from_str(output_format: &str) -> Result<Self> {
  42. match output_format {
  43. "toml" => Ok(OutputFormat::Toml),
  44. "csv" => Ok(OutputFormat::Csv),
  45. "json" => Ok(OutputFormat::Json),
  46. "plain" => Ok(OutputFormat::Plain),
  47. format => Err(format!("Unknown output format {}", format).into()),
  48. }
  49. }
  50. }
  51. impl OutputFormat {
  52. fn as_accept_header(&self) -> header::HeaderValue {
  53. header::HeaderValue::from_static(match self {
  54. OutputFormat::Json => "application/json",
  55. OutputFormat::Csv => "text/csv",
  56. OutputFormat::Toml => "application/toml",
  57. OutputFormat::Plain => "text/plain",
  58. })
  59. }
  60. }
  61. impl DataSource {
  62. fn from_args(
  63. path_arg: Option<String>,
  64. url_arg: Option<String>,
  65. content_path: &PathBuf,
  66. ) -> Result<Self> {
  67. if path_arg.is_some() && url_arg.is_some() {
  68. return Err(GET_DATA_ARGUMENT_ERROR_MESSAGE.into());
  69. }
  70. if let Some(path) = path_arg {
  71. let full_path = content_path.join(path);
  72. if !full_path.exists() {
  73. return Err(format!("{} doesn't exist", full_path.display()).into());
  74. }
  75. return Ok(DataSource::Path(full_path));
  76. }
  77. if let Some(url) = url_arg {
  78. return Url::parse(&url)
  79. .map(DataSource::Url)
  80. .map_err(|e| format!("Failed to parse {} as url: {}", url, e).into());
  81. }
  82. Err(GET_DATA_ARGUMENT_ERROR_MESSAGE.into())
  83. }
  84. fn get_cache_key(&self, format: &OutputFormat) -> u64 {
  85. let mut hasher = DefaultHasher::new();
  86. format.hash(&mut hasher);
  87. self.hash(&mut hasher);
  88. hasher.finish()
  89. }
  90. }
  91. impl Hash for DataSource {
  92. fn hash<H: Hasher>(&self, state: &mut H) {
  93. match self {
  94. DataSource::Url(url) => url.hash(state),
  95. DataSource::Path(path) => {
  96. path.hash(state);
  97. get_file_time(&path).expect("get file time").hash(state);
  98. }
  99. };
  100. }
  101. }
  102. fn get_data_source_from_args(
  103. content_path: &PathBuf,
  104. args: &HashMap<String, Value>,
  105. ) -> Result<DataSource> {
  106. let path_arg = optional_arg!(String, args.get("path"), GET_DATA_ARGUMENT_ERROR_MESSAGE);
  107. let url_arg = optional_arg!(String, args.get("url"), GET_DATA_ARGUMENT_ERROR_MESSAGE);
  108. DataSource::from_args(path_arg, url_arg, content_path)
  109. }
  110. fn read_data_file(base_path: &PathBuf, full_path: PathBuf) -> Result<String> {
  111. if !is_path_in_directory(&base_path, &full_path)
  112. .map_err(|e| format!("Failed to read data file {}: {}", full_path.display(), e))?
  113. {
  114. return Err(format!(
  115. "{} is not inside the base site directory {}",
  116. full_path.display(),
  117. base_path.display()
  118. )
  119. .into());
  120. }
  121. read_file(&full_path).map_err(|e| {
  122. format!("`load_data`: error {} loading file {}", full_path.to_str().unwrap(), e).into()
  123. })
  124. }
  125. fn get_output_format_from_args(
  126. args: &HashMap<String, Value>,
  127. data_source: &DataSource,
  128. ) -> Result<OutputFormat> {
  129. let format_arg = optional_arg!(
  130. String,
  131. args.get("format"),
  132. "`load_data`: `format` needs to be an argument with a string value, being one of the supported `load_data` file types (csv, json, toml, plain)"
  133. );
  134. if let Some(format) = format_arg {
  135. return OutputFormat::from_str(&format);
  136. }
  137. let from_extension = if let DataSource::Path(path) = data_source {
  138. path.extension().map(|extension| extension.to_str().unwrap()).unwrap_or_else(|| "plain")
  139. } else {
  140. "plain"
  141. };
  142. // Always default to Plain if we don't know what it is
  143. OutputFormat::from_str(from_extension).or_else(|_| Ok(OutputFormat::Plain))
  144. }
  145. /// A Tera function to load data from a file or from a URL
  146. /// Currently the supported formats are json, toml, csv and plain text
  147. #[derive(Debug)]
  148. pub struct LoadData {
  149. base_path: PathBuf,
  150. client: Arc<Mutex<Client>>,
  151. result_cache: Arc<Mutex<HashMap<u64, Value>>>,
  152. }
  153. impl LoadData {
  154. pub fn new(base_path: PathBuf) -> Self {
  155. let client = Arc::new(Mutex::new(Client::builder().build().expect("reqwest client build")));
  156. let result_cache = Arc::new(Mutex::new(HashMap::new()));
  157. Self { base_path, client, result_cache }
  158. }
  159. }
  160. impl TeraFn for LoadData {
  161. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  162. let data_source = get_data_source_from_args(&self.base_path, &args)?;
  163. let file_format = get_output_format_from_args(&args, &data_source)?;
  164. let cache_key = data_source.get_cache_key(&file_format);
  165. let mut cache = self.result_cache.lock().expect("result cache lock");
  166. let response_client = self.client.lock().expect("response client lock");
  167. if let Some(cached_result) = cache.get(&cache_key) {
  168. return Ok(cached_result.clone());
  169. }
  170. let data = match data_source {
  171. DataSource::Path(path) => read_data_file(&self.base_path, path),
  172. DataSource::Url(url) => {
  173. let mut response = response_client
  174. .get(url.as_str())
  175. .header(header::ACCEPT, file_format.as_accept_header())
  176. .send()
  177. .and_then(|res| res.error_for_status())
  178. .map_err(|e| {
  179. format!(
  180. "Failed to request {}: {}",
  181. url,
  182. e.status().expect("response status")
  183. )
  184. })?;
  185. response
  186. .text()
  187. .map_err(|e| format!("Failed to parse response from {}: {:?}", url, e).into())
  188. }
  189. }?;
  190. let result_value: Result<Value> = match file_format {
  191. OutputFormat::Toml => load_toml(data),
  192. OutputFormat::Csv => load_csv(data),
  193. OutputFormat::Json => load_json(data),
  194. OutputFormat::Plain => to_value(data).map_err(|e| e.into()),
  195. };
  196. if let Ok(data_result) = &result_value {
  197. cache.insert(cache_key, data_result.clone());
  198. }
  199. result_value
  200. }
  201. }
  202. /// Parse a JSON string and convert it to a Tera Value
  203. fn load_json(json_data: String) -> Result<Value> {
  204. let json_content: Value =
  205. serde_json::from_str(json_data.as_str()).map_err(|e| format!("{:?}", e))?;
  206. Ok(json_content)
  207. }
  208. /// Parse a TOML string and convert it to a Tera Value
  209. fn load_toml(toml_data: String) -> Result<Value> {
  210. let toml_content: toml::Value = toml::from_str(&toml_data).map_err(|e| format!("{:?}", e))?;
  211. let toml_value = to_value(toml_content).expect("Got invalid JSON that was valid TOML somehow");
  212. match toml_value {
  213. Value::Object(m) => Ok(fix_toml_dates(m)),
  214. _ => unreachable!("Loaded something other than a TOML object"),
  215. }
  216. }
  217. /// Parse a CSV string and convert it to a Tera Value
  218. ///
  219. /// An example csv file `example.csv` could be:
  220. /// ```csv
  221. /// Number, Title
  222. /// 1,Gutenberg
  223. /// 2,Printing
  224. /// ```
  225. /// The json value output would be:
  226. /// ```json
  227. /// {
  228. /// "headers": ["Number", "Title"],
  229. /// "records": [
  230. /// ["1", "Gutenberg"],
  231. /// ["2", "Printing"]
  232. /// ],
  233. /// }
  234. /// ```
  235. fn load_csv(csv_data: String) -> Result<Value> {
  236. let mut reader = Reader::from_reader(csv_data.as_bytes());
  237. let mut csv_map = Map::new();
  238. {
  239. let hdrs = reader.headers().map_err(|e| {
  240. format!("'load_data': {} - unable to read CSV header line (line 1) for CSV file", e)
  241. })?;
  242. let headers_array = hdrs.iter().map(|v| Value::String(v.to_string())).collect();
  243. csv_map.insert(String::from("headers"), Value::Array(headers_array));
  244. }
  245. {
  246. let records = reader.records();
  247. let mut records_array: Vec<Value> = Vec::new();
  248. for result in records {
  249. let record = match result {
  250. Ok(r) => r,
  251. Err(e) => {
  252. return Err(tera::Error::chain(
  253. String::from("Error encountered when parsing csv records"),
  254. e,
  255. ));
  256. }
  257. };
  258. let mut elements_array: Vec<Value> = Vec::new();
  259. for e in record.into_iter() {
  260. elements_array.push(Value::String(String::from(e)));
  261. }
  262. records_array.push(Value::Array(elements_array));
  263. }
  264. csv_map.insert(String::from("records"), Value::Array(records_array));
  265. }
  266. let csv_value: Value = Value::Object(csv_map);
  267. to_value(csv_value).map_err(|err| err.into())
  268. }
  269. #[cfg(test)]
  270. mod tests {
  271. use super::{DataSource, LoadData, OutputFormat};
  272. use std::collections::HashMap;
  273. use std::path::PathBuf;
  274. use tera::{to_value, Function};
  275. fn get_test_file(filename: &str) -> PathBuf {
  276. let test_files = PathBuf::from("../utils/test-files").canonicalize().unwrap();
  277. return test_files.join(filename);
  278. }
  279. #[test]
  280. fn fails_when_missing_file() {
  281. let static_fn = LoadData::new(PathBuf::from("../utils"));
  282. let mut args = HashMap::new();
  283. args.insert("path".to_string(), to_value("../../../READMEE.md").unwrap());
  284. let result = static_fn.call(&args);
  285. assert!(result.is_err());
  286. assert!(result.unwrap_err().to_string().contains("READMEE.md doesn't exist"));
  287. }
  288. #[test]
  289. fn cant_load_outside_content_dir() {
  290. let static_fn = LoadData::new(PathBuf::from(PathBuf::from("../utils")));
  291. let mut args = HashMap::new();
  292. args.insert("path".to_string(), to_value("../../README.md").unwrap());
  293. args.insert("format".to_string(), to_value("plain").unwrap());
  294. let result = static_fn.call(&args);
  295. assert!(result.is_err());
  296. assert!(result
  297. .unwrap_err()
  298. .to_string()
  299. .contains("README.md is not inside the base site directory"));
  300. }
  301. #[test]
  302. fn calculates_cache_key_for_path() {
  303. // We can't test against a fixed value, due to the fact the cache key is built from the absolute path
  304. let cache_key =
  305. DataSource::Path(get_test_file("test.toml")).get_cache_key(&OutputFormat::Toml);
  306. let cache_key_2 =
  307. DataSource::Path(get_test_file("test.toml")).get_cache_key(&OutputFormat::Toml);
  308. assert_eq!(cache_key, cache_key_2);
  309. }
  310. #[test]
  311. fn calculates_cache_key_for_url() {
  312. let cache_key =
  313. DataSource::Url("https://api.github.com/repos/getzola/zola".parse().unwrap())
  314. .get_cache_key(&OutputFormat::Plain);
  315. assert_eq!(cache_key, 8916756616423791754);
  316. }
  317. #[test]
  318. fn different_cache_key_per_filename() {
  319. let toml_cache_key =
  320. DataSource::Path(get_test_file("test.toml")).get_cache_key(&OutputFormat::Toml);
  321. let json_cache_key =
  322. DataSource::Path(get_test_file("test.json")).get_cache_key(&OutputFormat::Toml);
  323. assert_ne!(toml_cache_key, json_cache_key);
  324. }
  325. #[test]
  326. fn different_cache_key_per_format() {
  327. let toml_cache_key =
  328. DataSource::Path(get_test_file("test.toml")).get_cache_key(&OutputFormat::Toml);
  329. let json_cache_key =
  330. DataSource::Path(get_test_file("test.toml")).get_cache_key(&OutputFormat::Json);
  331. assert_ne!(toml_cache_key, json_cache_key);
  332. }
  333. #[test]
  334. fn can_load_remote_data() {
  335. let static_fn = LoadData::new(PathBuf::new());
  336. let mut args = HashMap::new();
  337. args.insert("url".to_string(), to_value("https://httpbin.org/json").unwrap());
  338. args.insert("format".to_string(), to_value("json").unwrap());
  339. let result = static_fn.call(&args).unwrap();
  340. assert_eq!(
  341. result.get("slideshow").unwrap().get("title").unwrap(),
  342. &to_value("Sample Slide Show").unwrap()
  343. );
  344. }
  345. #[test]
  346. fn fails_when_request_404s() {
  347. let static_fn = LoadData::new(PathBuf::new());
  348. let mut args = HashMap::new();
  349. args.insert("url".to_string(), to_value("https://httpbin.org/status/404/").unwrap());
  350. args.insert("format".to_string(), to_value("json").unwrap());
  351. let result = static_fn.call(&args);
  352. assert!(result.is_err());
  353. assert_eq!(
  354. result.unwrap_err().to_string(),
  355. "Failed to request https://httpbin.org/status/404/: 404 Not Found"
  356. );
  357. }
  358. #[test]
  359. fn can_load_toml() {
  360. let static_fn = LoadData::new(PathBuf::from("../utils/test-files"));
  361. let mut args = HashMap::new();
  362. args.insert("path".to_string(), to_value("test.toml").unwrap());
  363. let result = static_fn.call(&args.clone()).unwrap();
  364. // TOML does not load in order
  365. assert_eq!(
  366. result,
  367. json!({
  368. "category": {
  369. "date": "1979-05-27T07:32:00Z",
  370. "key": "value"
  371. },
  372. })
  373. );
  374. }
  375. #[test]
  376. fn can_load_csv() {
  377. let static_fn = LoadData::new(PathBuf::from("../utils/test-files"));
  378. let mut args = HashMap::new();
  379. args.insert("path".to_string(), to_value("test.csv").unwrap());
  380. let result = static_fn.call(&args.clone()).unwrap();
  381. assert_eq!(
  382. result,
  383. json!({
  384. "headers": ["Number", "Title"],
  385. "records": [
  386. ["1", "Gutenberg"],
  387. ["2", "Printing"]
  388. ],
  389. })
  390. )
  391. }
  392. // Test points to bad csv file with uneven row lengths
  393. #[test]
  394. fn bad_csv_should_result_in_error() {
  395. let static_fn = LoadData::new(PathBuf::from("../utils/test-files"));
  396. let mut args = HashMap::new();
  397. args.insert("path".to_string(), to_value("uneven_rows.csv").unwrap());
  398. let result = static_fn.call(&args.clone());
  399. assert!(result.is_err());
  400. let error_kind = result.err().unwrap().kind;
  401. match error_kind {
  402. tera::ErrorKind::Msg(msg) => {
  403. if msg != String::from("Error encountered when parsing csv records") {
  404. panic!("Error message is wrong. Perhaps wrong error is being returned?");
  405. }
  406. }
  407. _ => panic!("Error encountered was not expected CSV error"),
  408. }
  409. }
  410. #[test]
  411. fn can_load_json() {
  412. let static_fn = LoadData::new(PathBuf::from("../utils/test-files"));
  413. let mut args = HashMap::new();
  414. args.insert("path".to_string(), to_value("test.json").unwrap());
  415. let result = static_fn.call(&args.clone()).unwrap();
  416. assert_eq!(
  417. result,
  418. json!({
  419. "key": "value",
  420. "array": [1, 2, 3],
  421. "subpackage": {
  422. "subkey": 5
  423. }
  424. })
  425. )
  426. }
  427. }