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.

mod.rs 14KB

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