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.

380 lines
13KB

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