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.

313 lines
10KB

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