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.

325 lines
11KB

  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_url(tags: Option<Taxonomy>, categories: Option<Taxonomy>) -> GlobalFn {
  120. Box::new(move |args| -> Result<Value> {
  121. let kind = required_arg!(
  122. String,
  123. args.get("kind"),
  124. "`get_taxonomy_url` requires a `kind` argument with a string value"
  125. );
  126. let name = required_arg!(
  127. String,
  128. args.get("name"),
  129. "`get_taxonomy_url` requires a `name` argument with a string value"
  130. );
  131. let container = match kind.as_ref() {
  132. "tag" => &tags,
  133. "category" => &categories,
  134. _ => return Err(
  135. "`get_taxonomy_url` can only get `tag` or `category` for the `kind` argument".into()
  136. ),
  137. };
  138. if let Some(ref c) = *container {
  139. for item in &c.items {
  140. if item.name == name {
  141. return Ok(to_value(item.permalink.clone()).unwrap());
  142. }
  143. }
  144. bail!("`get_taxonomy_url`: couldn't find `{}` in `{}` taxonomy", name, kind);
  145. } else {
  146. bail!("`get_taxonomy_url` tried to get a taxonomy of kind `{}` but there isn't any", kind);
  147. }
  148. })
  149. }
  150. pub fn make_resize_image(imageproc: Arc<Mutex<imageproc::Processor>>) -> GlobalFn {
  151. static DEFAULT_OP: &'static str = "fill";
  152. const DEFAULT_Q: u8 = 75;
  153. Box::new(move |args| -> Result<Value> {
  154. let path = required_arg!(
  155. String,
  156. args.get("path"),
  157. "`resize_image` requires a `path` argument with a string value"
  158. );
  159. let width = optional_arg!(
  160. u32,
  161. args.get("width"),
  162. "`resize_image`: `width` must be a non-negative integer"
  163. );
  164. let height = optional_arg!(
  165. u32,
  166. args.get("height"),
  167. "`resize_image`: `height` must be a non-negative integer"
  168. );
  169. let op = optional_arg!(
  170. String,
  171. args.get("op"),
  172. "`resize_image`: `op` must be a string"
  173. ).unwrap_or(DEFAULT_OP.to_string());
  174. let quality = optional_arg!(
  175. u8,
  176. args.get("quality"),
  177. "`resize_image`: `quality` must be a number"
  178. ).unwrap_or(DEFAULT_Q);
  179. if quality == 0 || quality > 100 {
  180. return Err("`resize_image`: `quality` must be in range 1-100".to_string().into());
  181. }
  182. let mut imageproc = imageproc.lock().unwrap();
  183. if !imageproc.source_exists(&path) {
  184. return Err(format!("`resize_image`: Cannot find path: {}", path).into());
  185. }
  186. let imageop = imageproc::ImageOp::from_args(path.clone(), &op, width, height, quality)
  187. .map_err(|e| format!("`resize_image`: {}", e))?;
  188. let url = imageproc.insert(imageop);
  189. to_value(url).map_err(|err| err.into())
  190. })
  191. }
  192. #[cfg(test)]
  193. mod tests {
  194. use super::{make_get_url, make_get_taxonomy_url, make_trans};
  195. use std::collections::HashMap;
  196. use tera::to_value;
  197. use config::Config;
  198. use taxonomies::{Taxonomy, TaxonomyKind, TaxonomyItem};
  199. #[test]
  200. fn can_add_cachebust_to_url() {
  201. let config = Config::default();
  202. let static_fn = make_get_url(HashMap::new(), config);
  203. let mut args = HashMap::new();
  204. args.insert("path".to_string(), to_value("app.css").unwrap());
  205. args.insert("cachebust".to_string(), to_value(true).unwrap());
  206. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css/?t=1");
  207. }
  208. #[test]
  209. fn can_remove_trailing_slashes() {
  210. let config = Config::default();
  211. let static_fn = make_get_url(HashMap::new(), config);
  212. let mut args = HashMap::new();
  213. args.insert("path".to_string(), to_value("app.css").unwrap());
  214. args.insert("trailing_slash".to_string(), to_value(false).unwrap());
  215. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css");
  216. }
  217. #[test]
  218. fn can_remove_slashes_and_cachebust() {
  219. let config = Config::default();
  220. let static_fn = make_get_url(HashMap::new(), config);
  221. let mut args = HashMap::new();
  222. args.insert("path".to_string(), to_value("app.css").unwrap());
  223. args.insert("trailing_slash".to_string(), to_value(false).unwrap());
  224. args.insert("cachebust".to_string(), to_value(true).unwrap());
  225. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css?t=1");
  226. }
  227. #[test]
  228. fn can_link_to_some_static_file() {
  229. let config = Config::default();
  230. let static_fn = make_get_url(HashMap::new(), config);
  231. let mut args = HashMap::new();
  232. args.insert("path".to_string(), to_value("app.css").unwrap());
  233. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css/");
  234. }
  235. #[test]
  236. fn can_get_tag_url() {
  237. let tag = TaxonomyItem::new(
  238. "Prog amming",
  239. TaxonomyKind::Tags,
  240. &Config::default(),
  241. vec![],
  242. );
  243. let tags = Taxonomy {
  244. kind: TaxonomyKind::Tags,
  245. items: vec![tag],
  246. };
  247. let static_fn = make_get_taxonomy_url(Some(tags), None);
  248. // can find it correctly
  249. let mut args = HashMap::new();
  250. args.insert("kind".to_string(), to_value("tag").unwrap());
  251. args.insert("name".to_string(), to_value("Prog amming").unwrap());
  252. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/tags/prog-amming/");
  253. // and errors if it can't find it
  254. let mut args = HashMap::new();
  255. args.insert("kind".to_string(), to_value("tag").unwrap());
  256. args.insert("name".to_string(), to_value("random").unwrap());
  257. assert!(static_fn(args).is_err());
  258. }
  259. #[test]
  260. fn can_translate_a_string() {
  261. let trans_config = r#"
  262. base_url = "https://remplace-par-ton-url.fr"
  263. default_language = "fr"
  264. [translations]
  265. [translations.fr]
  266. title = "Un titre"
  267. [translations.en]
  268. title = "A title"
  269. "#;
  270. let config = Config::parse(trans_config).unwrap();
  271. let static_fn = make_trans(config);
  272. let mut args = HashMap::new();
  273. args.insert("key".to_string(), to_value("title").unwrap());
  274. assert_eq!(static_fn(args.clone()).unwrap(), "Un titre");
  275. args.insert("lang".to_string(), to_value("en").unwrap());
  276. assert_eq!(static_fn(args.clone()).unwrap(), "A title");
  277. args.insert("lang".to_string(), to_value("fr").unwrap());
  278. assert_eq!(static_fn(args.clone()).unwrap(), "Un titre");
  279. }
  280. }