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.

386 lines
14KB

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