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.

382 lines
13KB

  1. extern crate error_chain;
  2. use std::collections::HashMap;
  3. use std::sync::{Arc, Mutex};
  4. use tera::{from_value, to_value, GlobalFn, Result, Value};
  5. use config::Config;
  6. use library::{Library, Taxonomy};
  7. use utils::site::resolve_internal_link;
  8. use imageproc;
  9. #[macro_use]
  10. mod macros;
  11. mod load_data;
  12. pub use self::load_data::make_load_data;
  13. pub fn make_trans(config: Config) -> GlobalFn {
  14. let translations_config = config.translations;
  15. let default_lang = config.default_language.clone();
  16. Box::new(move |args| -> Result<Value> {
  17. let key = required_arg!(String, args.get("key"), "`trans` requires a `key` argument.");
  18. let lang = optional_arg!(String, args.get("lang"), "`trans`: `lang` must be a string.")
  19. .unwrap_or_else(|| default_lang.clone());
  20. let translations = &translations_config[lang.as_str()];
  21. Ok(to_value(&translations[key.as_str()]).unwrap())
  22. })
  23. }
  24. pub fn make_get_page(library: &Library) -> GlobalFn {
  25. let mut pages = HashMap::new();
  26. for page in library.pages_values() {
  27. pages.insert(
  28. page.file.relative.clone(),
  29. to_value(library.get_page(&page.file.path).unwrap().to_serialized(library)).unwrap(),
  30. );
  31. }
  32. Box::new(move |args| -> Result<Value> {
  33. let path = required_arg!(
  34. String,
  35. args.get("path"),
  36. "`get_page` requires a `path` argument with a string value"
  37. );
  38. match pages.get(&path) {
  39. Some(p) => Ok(p.clone()),
  40. None => Err(format!("Page `{}` not found.", path).into()),
  41. }
  42. })
  43. }
  44. pub fn make_get_section(library: &Library) -> GlobalFn {
  45. let mut sections = HashMap::new();
  46. let mut sections_basic = HashMap::new();
  47. for section in library.sections_values() {
  48. sections.insert(
  49. section.file.relative.clone(),
  50. to_value(library.get_section(&section.file.path).unwrap().to_serialized(library))
  51. .unwrap(),
  52. );
  53. sections_basic.insert(
  54. section.file.relative.clone(),
  55. to_value(library.get_section(&section.file.path).unwrap().to_serialized_basic(library))
  56. .unwrap(),
  57. );
  58. }
  59. Box::new(move |args| -> Result<Value> {
  60. let path = required_arg!(
  61. String,
  62. args.get("path"),
  63. "`get_section` requires a `path` argument with a string value"
  64. );
  65. let metadata_only = args
  66. .get("metadata_only")
  67. .map_or(false, |c| from_value::<bool>(c.clone()).unwrap_or(false));
  68. let container = if metadata_only { &sections_basic } else { &sections };
  69. match container.get(&path) {
  70. Some(p) => Ok(p.clone()),
  71. None => Err(format!("Section `{}` not found.", path).into()),
  72. }
  73. })
  74. }
  75. pub fn make_get_url(permalinks: HashMap<String, String>, config: Config) -> GlobalFn {
  76. Box::new(move |args| -> Result<Value> {
  77. let cachebust =
  78. args.get("cachebust").map_or(false, |c| from_value::<bool>(c.clone()).unwrap_or(false));
  79. let trailing_slash = args
  80. .get("trailing_slash")
  81. .map_or(false, |c| from_value::<bool>(c.clone()).unwrap_or(false));
  82. let path = required_arg!(
  83. String,
  84. args.get("path"),
  85. "`get_url` requires a `path` argument with a string value"
  86. );
  87. if path.starts_with("./") {
  88. match resolve_internal_link(&path, &permalinks) {
  89. Ok(url) => Ok(to_value(url).unwrap()),
  90. Err(_) => {
  91. Err(format!("Could not resolve URL for link `{}` not found.", path).into())
  92. }
  93. }
  94. } else {
  95. // anything else
  96. let mut permalink = config.make_permalink(&path);
  97. if !trailing_slash && permalink.ends_with('/') {
  98. permalink.pop(); // Removes the slash
  99. }
  100. if cachebust {
  101. permalink = format!("{}?t={}", permalink, config.build_timestamp.unwrap());
  102. }
  103. Ok(to_value(permalink).unwrap())
  104. }
  105. })
  106. }
  107. pub fn make_get_taxonomy(all_taxonomies: &[Taxonomy], library: &Library) -> GlobalFn {
  108. let mut taxonomies = HashMap::new();
  109. for taxonomy in all_taxonomies {
  110. taxonomies
  111. .insert(taxonomy.kind.name.clone(), to_value(taxonomy.to_serialized(library)).unwrap());
  112. }
  113. Box::new(move |args| -> Result<Value> {
  114. let kind = required_arg!(
  115. String,
  116. args.get("kind"),
  117. "`get_taxonomy` requires a `kind` argument with a string value"
  118. );
  119. let container = match taxonomies.get(&kind) {
  120. Some(c) => c,
  121. None => {
  122. return Err(format!(
  123. "`get_taxonomy` received an unknown taxonomy as kind: {}",
  124. kind
  125. )
  126. .into());
  127. }
  128. };
  129. Ok(to_value(container).unwrap())
  130. })
  131. }
  132. pub fn make_get_taxonomy_url(all_taxonomies: &[Taxonomy]) -> GlobalFn {
  133. let mut taxonomies = HashMap::new();
  134. for taxonomy in all_taxonomies {
  135. let mut items = HashMap::new();
  136. for item in &taxonomy.items {
  137. items.insert(item.name.clone(), item.permalink.clone());
  138. }
  139. taxonomies.insert(taxonomy.kind.name.clone(), items);
  140. }
  141. Box::new(move |args| -> Result<Value> {
  142. let kind = required_arg!(
  143. String,
  144. args.get("kind"),
  145. "`get_taxonomy_url` requires a `kind` argument with a string value"
  146. );
  147. let name = required_arg!(
  148. String,
  149. args.get("name"),
  150. "`get_taxonomy_url` requires a `name` argument with a string value"
  151. );
  152. let container = match taxonomies.get(&kind) {
  153. Some(c) => c,
  154. None => {
  155. return Err(format!(
  156. "`get_taxonomy_url` received an unknown taxonomy as kind: {}",
  157. kind
  158. )
  159. .into());
  160. }
  161. };
  162. if let Some(permalink) = container.get(&name) {
  163. return Ok(to_value(permalink).unwrap());
  164. }
  165. Err(format!("`get_taxonomy_url`: couldn't find `{}` in `{}` taxonomy", name, kind).into())
  166. })
  167. }
  168. pub fn make_resize_image(imageproc: Arc<Mutex<imageproc::Processor>>) -> GlobalFn {
  169. static DEFAULT_OP: &'static str = "fill";
  170. const DEFAULT_Q: u8 = 75;
  171. Box::new(move |args| -> Result<Value> {
  172. let path = required_arg!(
  173. String,
  174. args.get("path"),
  175. "`resize_image` requires a `path` argument with a string value"
  176. );
  177. let width = optional_arg!(
  178. u32,
  179. args.get("width"),
  180. "`resize_image`: `width` must be a non-negative integer"
  181. );
  182. let height = optional_arg!(
  183. u32,
  184. args.get("height"),
  185. "`resize_image`: `height` must be a non-negative integer"
  186. );
  187. let op = optional_arg!(String, args.get("op"), "`resize_image`: `op` must be a string")
  188. .unwrap_or_else(|| DEFAULT_OP.to_string());
  189. let quality =
  190. optional_arg!(u8, args.get("quality"), "`resize_image`: `quality` must be a number")
  191. .unwrap_or(DEFAULT_Q);
  192. if quality == 0 || quality > 100 {
  193. return Err("`resize_image`: `quality` must be in range 1-100".to_string().into());
  194. }
  195. let mut imageproc = imageproc.lock().unwrap();
  196. if !imageproc.source_exists(&path) {
  197. return Err(format!("`resize_image`: Cannot find path: {}", path).into());
  198. }
  199. let imageop = imageproc::ImageOp::from_args(path, &op, width, height, quality)
  200. .map_err(|e| format!("`resize_image`: {}", e))?;
  201. let url = imageproc.insert(imageop);
  202. to_value(url).map_err(|err| err.into())
  203. })
  204. }
  205. #[cfg(test)]
  206. mod tests {
  207. use super::{make_get_taxonomy, make_get_taxonomy_url, make_get_url, make_trans};
  208. use std::collections::HashMap;
  209. use tera::{to_value, Value};
  210. use config::{Config, Taxonomy as TaxonomyConfig};
  211. use library::{Library, Taxonomy, TaxonomyItem};
  212. #[test]
  213. fn can_add_cachebust_to_url() {
  214. let config = Config::default();
  215. let static_fn = make_get_url(HashMap::new(), config);
  216. let mut args = HashMap::new();
  217. args.insert("path".to_string(), to_value("app.css").unwrap());
  218. args.insert("cachebust".to_string(), to_value(true).unwrap());
  219. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css?t=1");
  220. }
  221. #[test]
  222. fn can_add_trailing_slashes() {
  223. let config = Config::default();
  224. let static_fn = make_get_url(HashMap::new(), config);
  225. let mut args = HashMap::new();
  226. args.insert("path".to_string(), to_value("app.css").unwrap());
  227. args.insert("trailing_slash".to_string(), to_value(true).unwrap());
  228. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css/");
  229. }
  230. #[test]
  231. fn can_add_slashes_and_cachebust() {
  232. let config = Config::default();
  233. let static_fn = make_get_url(HashMap::new(), config);
  234. let mut args = HashMap::new();
  235. args.insert("path".to_string(), to_value("app.css").unwrap());
  236. args.insert("trailing_slash".to_string(), to_value(true).unwrap());
  237. args.insert("cachebust".to_string(), to_value(true).unwrap());
  238. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css/?t=1");
  239. }
  240. #[test]
  241. fn can_link_to_some_static_file() {
  242. let config = Config::default();
  243. let static_fn = make_get_url(HashMap::new(), config);
  244. let mut args = HashMap::new();
  245. args.insert("path".to_string(), to_value("app.css").unwrap());
  246. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css");
  247. }
  248. #[test]
  249. fn can_get_taxonomy() {
  250. let taxo_config = TaxonomyConfig { name: "tags".to_string(), ..TaxonomyConfig::default() };
  251. let library = Library::new(0, 0);
  252. let tag = TaxonomyItem::new("Programming", "tags", &Config::default(), vec![], &library);
  253. let tags = Taxonomy { kind: taxo_config, items: vec![tag] };
  254. let taxonomies = vec![tags.clone()];
  255. let static_fn = make_get_taxonomy(&taxonomies, &library);
  256. // can find it correctly
  257. let mut args = HashMap::new();
  258. args.insert("kind".to_string(), to_value("tags").unwrap());
  259. let res = static_fn(args).unwrap();
  260. let res_obj = res.as_object().unwrap();
  261. assert_eq!(res_obj["kind"], to_value(tags.kind).unwrap());
  262. assert_eq!(res_obj["items"].clone().as_array().unwrap().len(), 1);
  263. assert_eq!(
  264. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["name"],
  265. Value::String("Programming".to_string())
  266. );
  267. assert_eq!(
  268. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["slug"],
  269. Value::String("programming".to_string())
  270. );
  271. assert_eq!(
  272. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()
  273. ["permalink"],
  274. Value::String("http://a-website.com/tags/programming/".to_string())
  275. );
  276. assert_eq!(
  277. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["pages"],
  278. Value::Array(vec![])
  279. );
  280. // and errors if it can't find it
  281. let mut args = HashMap::new();
  282. args.insert("kind".to_string(), to_value("something-else").unwrap());
  283. assert!(static_fn(args).is_err());
  284. }
  285. #[test]
  286. fn can_get_taxonomy_url() {
  287. let taxo_config = TaxonomyConfig { name: "tags".to_string(), ..TaxonomyConfig::default() };
  288. let library = Library::new(0, 0);
  289. let tag = TaxonomyItem::new("Programming", "tags", &Config::default(), vec![], &library);
  290. let tags = Taxonomy { kind: taxo_config, items: vec![tag] };
  291. let taxonomies = vec![tags.clone()];
  292. let static_fn = make_get_taxonomy_url(&taxonomies);
  293. // can find it correctly
  294. let mut args = HashMap::new();
  295. args.insert("kind".to_string(), to_value("tags").unwrap());
  296. args.insert("name".to_string(), to_value("Programming").unwrap());
  297. assert_eq!(
  298. static_fn(args).unwrap(),
  299. to_value("http://a-website.com/tags/programming/").unwrap()
  300. );
  301. // and errors if it can't find it
  302. let mut args = HashMap::new();
  303. args.insert("kind".to_string(), to_value("tags").unwrap());
  304. args.insert("name".to_string(), to_value("random").unwrap());
  305. assert!(static_fn(args).is_err());
  306. }
  307. #[test]
  308. fn can_translate_a_string() {
  309. let trans_config = r#"
  310. base_url = "https://remplace-par-ton-url.fr"
  311. default_language = "fr"
  312. [translations]
  313. [translations.fr]
  314. title = "Un titre"
  315. [translations.en]
  316. title = "A title"
  317. "#;
  318. let config = Config::parse(trans_config).unwrap();
  319. let static_fn = make_trans(config);
  320. let mut args = HashMap::new();
  321. args.insert("key".to_string(), to_value("title").unwrap());
  322. assert_eq!(static_fn(args.clone()).unwrap(), "Un titre");
  323. args.insert("lang".to_string(), to_value("en").unwrap());
  324. assert_eq!(static_fn(args.clone()).unwrap(), "A title");
  325. args.insert("lang".to_string(), to_value("fr").unwrap());
  326. assert_eq!(static_fn(args.clone()).unwrap(), "Un titre");
  327. }
  328. }