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.

410 lines
14KB

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