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.

542 lines
17KB

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