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.

564 lines
18KB

  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 mockito::mock;
  276. use serde_json::json;
  277. use tera::{to_value, Function};
  278. fn get_test_file(filename: &str) -> PathBuf {
  279. let test_files = PathBuf::from("../utils/test-files").canonicalize().unwrap();
  280. return test_files.join(filename);
  281. }
  282. #[test]
  283. fn fails_when_missing_file() {
  284. let static_fn = LoadData::new(PathBuf::from("../utils"));
  285. let mut args = HashMap::new();
  286. args.insert("path".to_string(), to_value("../../../READMEE.md").unwrap());
  287. let result = static_fn.call(&args);
  288. assert!(result.is_err());
  289. assert!(result.unwrap_err().to_string().contains("READMEE.md doesn't exist"));
  290. }
  291. #[test]
  292. fn cant_load_outside_content_dir() {
  293. let static_fn = LoadData::new(PathBuf::from(PathBuf::from("../utils")));
  294. let mut args = HashMap::new();
  295. args.insert("path".to_string(), to_value("../../README.md").unwrap());
  296. args.insert("format".to_string(), to_value("plain").unwrap());
  297. let result = static_fn.call(&args);
  298. assert!(result.is_err());
  299. assert!(result
  300. .unwrap_err()
  301. .to_string()
  302. .contains("README.md is not inside the base site directory"));
  303. }
  304. #[test]
  305. fn calculates_cache_key_for_path() {
  306. // We can't test against a fixed value, due to the fact the cache key is built from the absolute path
  307. let cache_key =
  308. DataSource::Path(get_test_file("test.toml")).get_cache_key(&OutputFormat::Toml);
  309. let cache_key_2 =
  310. DataSource::Path(get_test_file("test.toml")).get_cache_key(&OutputFormat::Toml);
  311. assert_eq!(cache_key, cache_key_2);
  312. }
  313. #[test]
  314. fn calculates_cache_key_for_url() {
  315. let _m = mock("GET", "/test")
  316. .with_header("content-type", "text/plain")
  317. .with_body("Test")
  318. .create();
  319. let url = format!("{}{}", mockito::server_url(), "/test");
  320. let cache_key = DataSource::Url(url.parse().unwrap()).get_cache_key(&OutputFormat::Plain);
  321. assert_eq!(cache_key, 12502656262443320092);
  322. }
  323. #[test]
  324. fn different_cache_key_per_filename() {
  325. let toml_cache_key =
  326. DataSource::Path(get_test_file("test.toml")).get_cache_key(&OutputFormat::Toml);
  327. let json_cache_key =
  328. DataSource::Path(get_test_file("test.json")).get_cache_key(&OutputFormat::Toml);
  329. assert_ne!(toml_cache_key, json_cache_key);
  330. }
  331. #[test]
  332. fn different_cache_key_per_format() {
  333. let toml_cache_key =
  334. DataSource::Path(get_test_file("test.toml")).get_cache_key(&OutputFormat::Toml);
  335. let json_cache_key =
  336. DataSource::Path(get_test_file("test.toml")).get_cache_key(&OutputFormat::Json);
  337. assert_ne!(toml_cache_key, json_cache_key);
  338. }
  339. #[test]
  340. fn can_load_remote_data() {
  341. let _m = mock("GET", "/json")
  342. .with_header("content-type", "application/json")
  343. .with_body(
  344. r#"{
  345. "test": {
  346. "foo": "bar"
  347. }
  348. }
  349. "#,
  350. )
  351. .create();
  352. let url = format!("{}{}", mockito::server_url(), "/json");
  353. let static_fn = LoadData::new(PathBuf::new());
  354. let mut args = HashMap::new();
  355. args.insert("url".to_string(), to_value(&url).unwrap());
  356. args.insert("format".to_string(), to_value("json").unwrap());
  357. let result = static_fn.call(&args).unwrap();
  358. assert_eq!(result.get("test").unwrap().get("foo").unwrap(), &to_value("bar").unwrap());
  359. }
  360. #[test]
  361. fn fails_when_request_404s() {
  362. let _m = mock("GET", "/404")
  363. .with_status(404)
  364. .with_header("content-type", "text/plain")
  365. .with_body("Not Found")
  366. .create();
  367. let url = format!("{}{}", mockito::server_url(), "/404");
  368. let static_fn = LoadData::new(PathBuf::new());
  369. let mut args = HashMap::new();
  370. args.insert("url".to_string(), to_value(&url).unwrap());
  371. args.insert("format".to_string(), to_value("json").unwrap());
  372. let result = static_fn.call(&args);
  373. assert!(result.is_err());
  374. assert_eq!(
  375. result.unwrap_err().to_string(),
  376. format!("Failed to request {}: 404 Not Found", url)
  377. );
  378. }
  379. #[test]
  380. fn can_load_toml() {
  381. let static_fn = LoadData::new(PathBuf::from("../utils/test-files"));
  382. let mut args = HashMap::new();
  383. args.insert("path".to_string(), to_value("test.toml").unwrap());
  384. let result = static_fn.call(&args.clone()).unwrap();
  385. // TOML does not load in order
  386. assert_eq!(
  387. result,
  388. json!({
  389. "category": {
  390. "date": "1979-05-27T07:32:00Z",
  391. "lt1": "07:32:00",
  392. "key": "value"
  393. },
  394. })
  395. );
  396. }
  397. #[test]
  398. fn unknown_extension_defaults_to_plain() {
  399. let static_fn = LoadData::new(PathBuf::from("../utils/test-files"));
  400. let mut args = HashMap::new();
  401. args.insert("path".to_string(), to_value("test.css").unwrap());
  402. let result = static_fn.call(&args.clone()).unwrap();
  403. if cfg!(windows) {
  404. assert_eq!(result, ".hello {}\r\n",);
  405. } else {
  406. assert_eq!(result, ".hello {}\n",);
  407. };
  408. }
  409. #[test]
  410. fn can_override_known_extension_with_format() {
  411. let static_fn = LoadData::new(PathBuf::from("../utils/test-files"));
  412. let mut args = HashMap::new();
  413. args.insert("path".to_string(), to_value("test.csv").unwrap());
  414. args.insert("format".to_string(), to_value("plain").unwrap());
  415. let result = static_fn.call(&args.clone()).unwrap();
  416. if cfg!(windows) {
  417. assert_eq!(result, "Number,Title\r\n1,Gutenberg\r\n2,Printing",);
  418. } else {
  419. assert_eq!(result, "Number,Title\n1,Gutenberg\n2,Printing",);
  420. };
  421. }
  422. #[test]
  423. fn will_use_format_on_unknown_extension() {
  424. let static_fn = LoadData::new(PathBuf::from("../utils/test-files"));
  425. let mut args = HashMap::new();
  426. args.insert("path".to_string(), to_value("test.css").unwrap());
  427. args.insert("format".to_string(), to_value("plain").unwrap());
  428. let result = static_fn.call(&args.clone()).unwrap();
  429. if cfg!(windows) {
  430. assert_eq!(result, ".hello {}\r\n",);
  431. } else {
  432. assert_eq!(result, ".hello {}\n",);
  433. };
  434. }
  435. #[test]
  436. fn can_load_csv() {
  437. let static_fn = LoadData::new(PathBuf::from("../utils/test-files"));
  438. let mut args = HashMap::new();
  439. args.insert("path".to_string(), to_value("test.csv").unwrap());
  440. let result = static_fn.call(&args.clone()).unwrap();
  441. assert_eq!(
  442. result,
  443. json!({
  444. "headers": ["Number", "Title"],
  445. "records": [
  446. ["1", "Gutenberg"],
  447. ["2", "Printing"]
  448. ],
  449. })
  450. )
  451. }
  452. // Test points to bad csv file with uneven row lengths
  453. #[test]
  454. fn bad_csv_should_result_in_error() {
  455. let static_fn = LoadData::new(PathBuf::from("../utils/test-files"));
  456. let mut args = HashMap::new();
  457. args.insert("path".to_string(), to_value("uneven_rows.csv").unwrap());
  458. let result = static_fn.call(&args.clone());
  459. assert!(result.is_err());
  460. let error_kind = result.err().unwrap().kind;
  461. match error_kind {
  462. tera::ErrorKind::Msg(msg) => {
  463. if msg != String::from("Error encountered when parsing csv records") {
  464. panic!("Error message is wrong. Perhaps wrong error is being returned?");
  465. }
  466. }
  467. _ => panic!("Error encountered was not expected CSV error"),
  468. }
  469. }
  470. #[test]
  471. fn can_load_json() {
  472. let static_fn = LoadData::new(PathBuf::from("../utils/test-files"));
  473. let mut args = HashMap::new();
  474. args.insert("path".to_string(), to_value("test.json").unwrap());
  475. let result = static_fn.call(&args.clone()).unwrap();
  476. assert_eq!(
  477. result,
  478. json!({
  479. "key": "value",
  480. "array": [1, 2, 3],
  481. "subpackage": {
  482. "subkey": 5
  483. }
  484. })
  485. )
  486. }
  487. }