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.

412 lines
14KB

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