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.

426 lines
14KB

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