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.

408 lines
13KB

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