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.

377 lines
12KB

  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_get_taxonomy_url(all_taxonomies: Vec<Taxonomy>) -> GlobalFn {
  140. let mut taxonomies = HashMap::new();
  141. for taxonomy in all_taxonomies {
  142. taxonomies.insert(taxonomy.kind.name.clone(), taxonomy);
  143. }
  144. Box::new(move |args| -> Result<Value> {
  145. let kind = required_arg!(
  146. String,
  147. args.get("kind"),
  148. "`get_taxonomy_url` requires a `kind` argument with a string value"
  149. );
  150. let name = required_arg!(
  151. String,
  152. args.get("name"),
  153. "`get_taxonomy_url` requires a `name` argument with a string value"
  154. );
  155. let container = match taxonomies.get(&kind) {
  156. Some(c) => c,
  157. None => return Err(
  158. format!("`get_taxonomy_url` received an unknown taxonomy as kind: {}", kind).into()
  159. )
  160. };
  161. for item in &container.items {
  162. if item.name == name {
  163. return Ok(to_value(item.permalink.clone()).unwrap());
  164. }
  165. }
  166. Err(
  167. format!("`get_taxonomy_url`: couldn't find `{}` in `{}` taxonomy", name, kind).into()
  168. )
  169. })
  170. }
  171. pub fn make_resize_image(imageproc: Arc<Mutex<imageproc::Processor>>) -> GlobalFn {
  172. static DEFAULT_OP: &'static str = "fill";
  173. const DEFAULT_Q: u8 = 75;
  174. Box::new(move |args| -> Result<Value> {
  175. let path = required_arg!(
  176. String,
  177. args.get("path"),
  178. "`resize_image` requires a `path` argument with a string value"
  179. );
  180. let width = optional_arg!(
  181. u32,
  182. args.get("width"),
  183. "`resize_image`: `width` must be a non-negative integer"
  184. );
  185. let height = optional_arg!(
  186. u32,
  187. args.get("height"),
  188. "`resize_image`: `height` must be a non-negative integer"
  189. );
  190. let op = optional_arg!(
  191. String,
  192. args.get("op"),
  193. "`resize_image`: `op` must be a string"
  194. ).unwrap_or(DEFAULT_OP.to_string());
  195. let quality = optional_arg!(
  196. u8,
  197. args.get("quality"),
  198. "`resize_image`: `quality` must be a number"
  199. ).unwrap_or(DEFAULT_Q);
  200. if quality == 0 || quality > 100 {
  201. return Err("`resize_image`: `quality` must be in range 1-100".to_string().into());
  202. }
  203. let mut imageproc = imageproc.lock().unwrap();
  204. if !imageproc.source_exists(&path) {
  205. return Err(format!("`resize_image`: Cannot find path: {}", path).into());
  206. }
  207. let imageop = imageproc::ImageOp::from_args(path.clone(), &op, width, height, quality)
  208. .map_err(|e| format!("`resize_image`: {}", e))?;
  209. let url = imageproc.insert(imageop);
  210. to_value(url).map_err(|err| err.into())
  211. })
  212. }
  213. #[cfg(test)]
  214. mod tests {
  215. use super::{make_get_url, make_get_taxonomy, make_get_taxonomy_url, make_trans};
  216. use std::collections::HashMap;
  217. use tera::to_value;
  218. use config::{Config, Taxonomy as TaxonomyConfig};
  219. use taxonomies::{Taxonomy, TaxonomyItem};
  220. #[test]
  221. fn can_add_cachebust_to_url() {
  222. let config = Config::default();
  223. let static_fn = make_get_url(HashMap::new(), config);
  224. let mut args = HashMap::new();
  225. args.insert("path".to_string(), to_value("app.css").unwrap());
  226. args.insert("cachebust".to_string(), to_value(true).unwrap());
  227. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css/?t=1");
  228. }
  229. #[test]
  230. fn can_remove_trailing_slashes() {
  231. let config = Config::default();
  232. let static_fn = make_get_url(HashMap::new(), config);
  233. let mut args = HashMap::new();
  234. args.insert("path".to_string(), to_value("app.css").unwrap());
  235. args.insert("trailing_slash".to_string(), to_value(false).unwrap());
  236. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css");
  237. }
  238. #[test]
  239. fn can_remove_slashes_and_cachebust() {
  240. let config = Config::default();
  241. let static_fn = make_get_url(HashMap::new(), config);
  242. let mut args = HashMap::new();
  243. args.insert("path".to_string(), to_value("app.css").unwrap());
  244. args.insert("trailing_slash".to_string(), to_value(false).unwrap());
  245. args.insert("cachebust".to_string(), to_value(true).unwrap());
  246. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css?t=1");
  247. }
  248. #[test]
  249. fn can_link_to_some_static_file() {
  250. let config = Config::default();
  251. let static_fn = make_get_url(HashMap::new(), config);
  252. let mut args = HashMap::new();
  253. args.insert("path".to_string(), to_value("app.css").unwrap());
  254. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css/");
  255. }
  256. #[test]
  257. fn can_get_taxonomy() {
  258. let taxo_config = TaxonomyConfig { name: "tags".to_string(), ..TaxonomyConfig::default() };
  259. let tag = TaxonomyItem::new(
  260. "Progamming",
  261. "tags",
  262. &Config::default(),
  263. vec![],
  264. );
  265. let tags = Taxonomy {
  266. kind: taxo_config,
  267. items: vec![tag],
  268. };
  269. let static_fn = make_get_taxonomy(vec![tags.clone()]);
  270. // can find it correctly
  271. let mut args = HashMap::new();
  272. args.insert("kind".to_string(), to_value("tags").unwrap());
  273. assert_eq!(static_fn(args).unwrap(), to_value(&tags).unwrap());
  274. // and errors if it can't find it
  275. let mut args = HashMap::new();
  276. args.insert("kind".to_string(), to_value("something-else").unwrap());
  277. assert!(static_fn(args).is_err());
  278. }
  279. #[test]
  280. fn can_get_taxonomy_url() {
  281. let taxo_config = TaxonomyConfig { name: "tags".to_string(), ..TaxonomyConfig::default() };
  282. let tag = TaxonomyItem::new(
  283. "Programming",
  284. "tags",
  285. &Config::default(),
  286. vec![],
  287. );
  288. let tags = Taxonomy {
  289. kind: taxo_config,
  290. items: vec![tag],
  291. };
  292. let static_fn = make_get_taxonomy_url(vec![tags.clone()]);
  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!(static_fn(args).unwrap(), "http://a-website.com/tags/prog-amming/");
  298. // and errors if it can't find it
  299. let mut args = HashMap::new();
  300. args.insert("kind".to_string(), to_value("tags").unwrap());
  301. args.insert("name".to_string(), to_value("random").unwrap());
  302. assert!(static_fn(args).is_err());
  303. }
  304. #[test]
  305. fn can_translate_a_string() {
  306. let trans_config = r#"
  307. base_url = "https://remplace-par-ton-url.fr"
  308. default_language = "fr"
  309. [translations]
  310. [translations.fr]
  311. title = "Un titre"
  312. [translations.en]
  313. title = "A title"
  314. "#;
  315. let config = Config::parse(trans_config).unwrap();
  316. let static_fn = make_trans(config);
  317. let mut args = HashMap::new();
  318. args.insert("key".to_string(), to_value("title").unwrap());
  319. assert_eq!(static_fn(args.clone()).unwrap(), "Un titre");
  320. args.insert("lang".to_string(), to_value("en").unwrap());
  321. assert_eq!(static_fn(args.clone()).unwrap(), "A title");
  322. args.insert("lang".to_string(), to_value("fr").unwrap());
  323. assert_eq!(static_fn(args.clone()).unwrap(), "Un titre");
  324. }
  325. }