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.

278 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!(String, args.get("lang"), "`trans`: `lang` must be a string.").unwrap_or(default_lang.clone());
  38. let translations = &translations_config[lang.as_str()];
  39. Ok(to_value(&translations[key.as_str()]).unwrap())
  40. })
  41. }
  42. pub fn make_get_page(all_pages: &HashMap<PathBuf, Page>) -> GlobalFn {
  43. let mut pages = HashMap::new();
  44. for page in all_pages.values() {
  45. pages.insert(page.file.relative.clone(), page.clone());
  46. }
  47. Box::new(move |args| -> Result<Value> {
  48. let path = required_arg!(String, args.get("path"), "`get_page` requires a `path` argument with a string value");
  49. match pages.get(&path) {
  50. Some(p) => Ok(to_value(p).unwrap()),
  51. None => Err(format!("Page `{}` not found.", path).into())
  52. }
  53. })
  54. }
  55. pub fn make_get_section(all_sections: &HashMap<PathBuf, Section>) -> GlobalFn {
  56. let mut sections = HashMap::new();
  57. for section in all_sections.values() {
  58. if section.file.components == vec!["rebuild".to_string()] {
  59. //println!("Setting sections:\n{:#?}", section.pages[0]);
  60. }
  61. sections.insert(section.file.relative.clone(), section.clone());
  62. }
  63. Box::new(move |args| -> Result<Value> {
  64. let path = required_arg!(String, args.get("path"), "`get_section` requires a `path` argument with a string value");
  65. //println!("Found {:#?}", sections.get(&path).unwrap().pages[0]);
  66. match sections.get(&path) {
  67. Some(p) => Ok(to_value(p).unwrap()),
  68. None => Err(format!("Section `{}` not found.", path).into())
  69. }
  70. })
  71. }
  72. pub fn make_get_url(permalinks: HashMap<String, String>, config: Config) -> GlobalFn {
  73. Box::new(move |args| -> Result<Value> {
  74. let cachebust = args
  75. .get("cachebust")
  76. .map_or(false, |c| {
  77. from_value::<bool>(c.clone()).unwrap_or(false)
  78. });
  79. let trailing_slash = args
  80. .get("trailing_slash")
  81. .map_or(true, |c| {
  82. from_value::<bool>(c.clone()).unwrap_or(true)
  83. });
  84. let path = required_arg!(String, args.get("path"), "`get_url` requires a `path` argument with a string value");
  85. if path.starts_with("./") {
  86. match resolve_internal_link(&path, &permalinks) {
  87. Ok(url) => Ok(to_value(url).unwrap()),
  88. Err(_) => Err(format!("Could not resolve URL for link `{}` not found.", path).into())
  89. }
  90. } else {
  91. // anything else
  92. let mut permalink = config.make_permalink(&path);
  93. if !trailing_slash && permalink.ends_with("/") {
  94. permalink.pop(); // Removes the slash
  95. }
  96. if cachebust {
  97. permalink = format!("{}?t={}", permalink, config.build_timestamp.unwrap());
  98. }
  99. Ok(to_value(permalink).unwrap())
  100. }
  101. })
  102. }
  103. pub fn make_get_taxonomy_url(tags: Option<Taxonomy>, categories: Option<Taxonomy>) -> GlobalFn {
  104. Box::new(move |args| -> Result<Value> {
  105. let kind = required_arg!(String, args.get("kind"), "`get_taxonomy_url` requires a `kind` argument with a string value");
  106. let name = required_arg!(String, args.get("name"), "`get_taxonomy_url` requires a `name` argument with a string value");
  107. let container = match kind.as_ref() {
  108. "tag" => &tags,
  109. "category" => &categories,
  110. _ => return Err("`get_taxonomy_url` can only get `tag` or `category` for the `kind` argument".into()),
  111. };
  112. if let Some(ref c) = *container {
  113. for item in &c.items {
  114. if item.name == name {
  115. return Ok(to_value(item.permalink.clone()).unwrap());
  116. }
  117. }
  118. bail!("`get_taxonomy_url`: couldn't find `{}` in `{}` taxonomy", name, kind);
  119. } else {
  120. bail!("`get_taxonomy_url` tried to get a taxonomy of kind `{}` but there isn't any", kind);
  121. }
  122. })
  123. }
  124. pub fn make_resize_image(imageproc: Arc<Mutex<imageproc::Processor>>) -> GlobalFn {
  125. static DEFAULT_OP: &'static str = "fill";
  126. const DEFAULT_Q: u8 = 75;
  127. Box::new(move |args| -> Result<Value> {
  128. let path = required_arg!(String, args.get("path"), "`resize_image` requires a `path` argument with a string value");
  129. let width = optional_arg!(u32, args.get("width"), "`resize_image`: `width` must be a non-negative integer");
  130. let height = optional_arg!(u32, args.get("height"), "`resize_image`: `height` must be a non-negative integer");
  131. let op = optional_arg!(String, args.get("op"), "`resize_image`: `op` must be a string").unwrap_or(DEFAULT_OP.to_owned());
  132. let quality = optional_arg!(u8, args.get("quality"), "`resize_image`: `quality` must be a number").unwrap_or(DEFAULT_Q);
  133. if quality == 0 || quality > 100 {
  134. return Err("`resize_image`: `quality` must be in range 1-100".to_string().into());
  135. }
  136. let mut imageproc = imageproc.lock().unwrap();
  137. if !imageproc.source_exists(&path) {
  138. return Err(format!("`resize_image`: Cannot find path: {}", path).into());
  139. }
  140. let imageop = imageproc::ImageOp::from_args(path.clone(), &op, width, height, quality).map_err(|e| format!("`resize_image`: {}", e))?;
  141. let url = imageproc.insert(imageop);
  142. to_value(url).map_err(|err| err.into())
  143. })
  144. }
  145. #[cfg(test)]
  146. mod tests {
  147. use super::{make_get_url, make_get_taxonomy_url, make_trans};
  148. use std::collections::HashMap;
  149. use tera::to_value;
  150. use config::Config;
  151. use taxonomies::{Taxonomy, TaxonomyKind, TaxonomyItem};
  152. #[test]
  153. fn can_add_cachebust_to_url() {
  154. let config = Config::default();
  155. let static_fn = make_get_url(HashMap::new(), config);
  156. let mut args = HashMap::new();
  157. args.insert("path".to_string(), to_value("app.css").unwrap());
  158. args.insert("cachebust".to_string(), to_value(true).unwrap());
  159. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css/?t=1");
  160. }
  161. #[test]
  162. fn can_remove_trailing_slashes() {
  163. let config = Config::default();
  164. let static_fn = make_get_url(HashMap::new(), config);
  165. let mut args = HashMap::new();
  166. args.insert("path".to_string(), to_value("app.css").unwrap());
  167. args.insert("trailing_slash".to_string(), to_value(false).unwrap());
  168. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css");
  169. }
  170. #[test]
  171. fn can_remove_slashes_and_cachebust() {
  172. let config = Config::default();
  173. let static_fn = make_get_url(HashMap::new(), config);
  174. let mut args = HashMap::new();
  175. args.insert("path".to_string(), to_value("app.css").unwrap());
  176. args.insert("trailing_slash".to_string(), to_value(false).unwrap());
  177. args.insert("cachebust".to_string(), to_value(true).unwrap());
  178. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css?t=1");
  179. }
  180. #[test]
  181. fn can_link_to_some_static_file() {
  182. let config = Config::default();
  183. let static_fn = make_get_url(HashMap::new(), config);
  184. let mut args = HashMap::new();
  185. args.insert("path".to_string(), to_value("app.css").unwrap());
  186. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css/");
  187. }
  188. #[test]
  189. fn can_get_tag_url() {
  190. let tag = TaxonomyItem::new(
  191. "Prog amming",
  192. TaxonomyKind::Tags,
  193. &Config::default(),
  194. vec![],
  195. );
  196. let tags = Taxonomy {
  197. kind: TaxonomyKind::Tags,
  198. items: vec![tag],
  199. };
  200. let static_fn = make_get_taxonomy_url(Some(tags), None);
  201. // can find it correctly
  202. let mut args = HashMap::new();
  203. args.insert("kind".to_string(), to_value("tag").unwrap());
  204. args.insert("name".to_string(), to_value("Prog amming").unwrap());
  205. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/tags/prog-amming/");
  206. // and errors if it can't find it
  207. let mut args = HashMap::new();
  208. args.insert("kind".to_string(), to_value("tag").unwrap());
  209. args.insert("name".to_string(), to_value("random").unwrap());
  210. assert!(static_fn(args).is_err());
  211. }
  212. #[test]
  213. fn can_translate_a_string() {
  214. let trans_config = r#"
  215. base_url = "https://remplace-par-ton-url.fr"
  216. default_language = "fr"
  217. [translations]
  218. [translations.fr]
  219. title = "Un titre"
  220. [translations.en]
  221. title = "A title"
  222. "#;
  223. let config = Config::parse(trans_config).unwrap();
  224. let static_fn = make_trans(config);
  225. let mut args = HashMap::new();
  226. args.insert("key".to_string(), to_value("title").unwrap());
  227. assert_eq!(static_fn(args.clone()).unwrap(), "Un titre");
  228. args.insert("lang".to_string(), to_value("en").unwrap());
  229. assert_eq!(static_fn(args.clone()).unwrap(), "A title");
  230. args.insert("lang".to_string(), to_value("fr").unwrap());
  231. assert_eq!(static_fn(args.clone()).unwrap(), "Un titre");
  232. }
  233. }