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.

238 lines
8.4KB

  1. use std::collections::HashMap;
  2. use std::path::{PathBuf};
  3. use tera::{GlobalFn, Value, from_value, to_value, Result};
  4. use content::{Page, Section};
  5. use config::Config;
  6. use utils::site::resolve_internal_link;
  7. use taxonomies::Taxonomy;
  8. macro_rules! required_string_arg {
  9. ($e: expr, $err: expr) => {
  10. match $e {
  11. Some(v) => match from_value::<String>(v.clone()) {
  12. Ok(u) => u,
  13. Err(_) => return Err($err.into())
  14. },
  15. None => return Err($err.into())
  16. };
  17. };
  18. }
  19. pub fn make_trans(config: Config) -> GlobalFn {
  20. let translations_config = config.translations;
  21. let default_lang = to_value(config.default_language).unwrap();
  22. Box::new(move |args| -> Result<Value> {
  23. let key = required_string_arg!(args.get("key"), "`trans` requires a `key` argument.");
  24. let lang_arg = args.get("lang").unwrap_or(&default_lang).clone();
  25. let lang = from_value::<String>(lang_arg).unwrap();
  26. let translations = &translations_config[lang.as_str()];
  27. Ok(to_value(&translations[key.as_str()]).unwrap())
  28. })
  29. }
  30. pub fn make_get_page(all_pages: &HashMap<PathBuf, Page>) -> GlobalFn {
  31. let mut pages = HashMap::new();
  32. for page in all_pages.values() {
  33. pages.insert(page.file.relative.clone(), page.clone());
  34. }
  35. Box::new(move |args| -> Result<Value> {
  36. let path = required_string_arg!(args.get("path"), "`get_page` requires a `path` argument with a string value");
  37. match pages.get(&path) {
  38. Some(p) => Ok(to_value(p).unwrap()),
  39. None => Err(format!("Page `{}` not found.", path).into())
  40. }
  41. })
  42. }
  43. pub fn make_get_section(all_sections: &HashMap<PathBuf, Section>) -> GlobalFn {
  44. let mut sections = HashMap::new();
  45. for section in all_sections.values() {
  46. if section.file.components == vec!["rebuild".to_string()] {
  47. //println!("Setting sections:\n{:#?}", section.pages[0]);
  48. }
  49. sections.insert(section.file.relative.clone(), section.clone());
  50. }
  51. Box::new(move |args| -> Result<Value> {
  52. let path = required_string_arg!(args.get("path"), "`get_section` requires a `path` argument with a string value");
  53. //println!("Found {:#?}", sections.get(&path).unwrap().pages[0]);
  54. match sections.get(&path) {
  55. Some(p) => Ok(to_value(p).unwrap()),
  56. None => Err(format!("Section `{}` not found.", path).into())
  57. }
  58. })
  59. }
  60. pub fn make_get_url(permalinks: HashMap<String, String>, config: Config) -> GlobalFn {
  61. Box::new(move |args| -> Result<Value> {
  62. let cachebust = args
  63. .get("cachebust")
  64. .map_or(false, |c| {
  65. from_value::<bool>(c.clone()).unwrap_or(false)
  66. });
  67. let trailing_slash = args
  68. .get("trailing_slash")
  69. .map_or(true, |c| {
  70. from_value::<bool>(c.clone()).unwrap_or(true)
  71. });
  72. let path = required_string_arg!(args.get("path"), "`get_url` requires a `path` argument with a string value");
  73. if path.starts_with("./") {
  74. match resolve_internal_link(&path, &permalinks) {
  75. Ok(url) => Ok(to_value(url).unwrap()),
  76. Err(_) => Err(format!("Could not resolve URL for link `{}` not found.", path).into())
  77. }
  78. } else {
  79. // anything else
  80. let mut permalink = config.make_permalink(&path);
  81. if !trailing_slash && permalink.ends_with("/") {
  82. permalink.pop(); // Removes the slash
  83. }
  84. if cachebust {
  85. permalink = format!("{}?t={}", permalink, config.build_timestamp.unwrap());
  86. }
  87. Ok(to_value(permalink).unwrap())
  88. }
  89. })
  90. }
  91. pub fn make_get_taxonomy_url(tags: Option<Taxonomy>, categories: Option<Taxonomy>) -> GlobalFn {
  92. Box::new(move |args| -> Result<Value> {
  93. let kind = required_string_arg!(args.get("kind"), "`get_taxonomy_url` requires a `kind` argument with a string value");
  94. let name = required_string_arg!(args.get("name"), "`get_taxonomy_url` requires a `name` argument with a string value");
  95. let container = match kind.as_ref() {
  96. "tag" => &tags,
  97. "category" => &categories,
  98. _ => return Err("`get_taxonomy_url` can only get `tag` or `category` for the `kind` argument".into()),
  99. };
  100. if let Some(ref c) = *container {
  101. for item in &c.items {
  102. if item.name == name {
  103. return Ok(to_value(item.permalink.clone()).unwrap());
  104. }
  105. }
  106. bail!("`get_taxonomy_url`: couldn't find `{}` in `{}` taxonomy", name, kind);
  107. } else {
  108. bail!("`get_taxonomy_url` tried to get a taxonomy of kind `{}` but there isn't any", kind);
  109. }
  110. })
  111. }
  112. #[cfg(test)]
  113. mod tests {
  114. use super::{make_get_url, make_get_taxonomy_url, make_trans};
  115. use std::collections::HashMap;
  116. use tera::to_value;
  117. use config::Config;
  118. use taxonomies::{Taxonomy, TaxonomyKind, TaxonomyItem};
  119. #[test]
  120. fn can_add_cachebust_to_url() {
  121. let config = Config::default();
  122. let static_fn = make_get_url(HashMap::new(), config);
  123. let mut args = HashMap::new();
  124. args.insert("path".to_string(), to_value("app.css").unwrap());
  125. args.insert("cachebust".to_string(), to_value(true).unwrap());
  126. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css/?t=1");
  127. }
  128. #[test]
  129. fn can_remove_trailing_slashes() {
  130. let config = Config::default();
  131. let static_fn = make_get_url(HashMap::new(), config);
  132. let mut args = HashMap::new();
  133. args.insert("path".to_string(), to_value("app.css").unwrap());
  134. args.insert("trailing_slash".to_string(), to_value(false).unwrap());
  135. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css");
  136. }
  137. #[test]
  138. fn can_remove_slashes_and_cachebust() {
  139. let config = Config::default();
  140. let static_fn = make_get_url(HashMap::new(), config);
  141. let mut args = HashMap::new();
  142. args.insert("path".to_string(), to_value("app.css").unwrap());
  143. args.insert("trailing_slash".to_string(), to_value(false).unwrap());
  144. args.insert("cachebust".to_string(), to_value(true).unwrap());
  145. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css?t=1");
  146. }
  147. #[test]
  148. fn can_link_to_some_static_file() {
  149. let config = Config::default();
  150. let static_fn = make_get_url(HashMap::new(), config);
  151. let mut args = HashMap::new();
  152. args.insert("path".to_string(), to_value("app.css").unwrap());
  153. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/app.css/");
  154. }
  155. #[test]
  156. fn can_get_tag_url() {
  157. let tag = TaxonomyItem::new(
  158. "Prog amming",
  159. TaxonomyKind::Tags,
  160. &Config::default(),
  161. vec![],
  162. );
  163. let tags = Taxonomy {
  164. kind: TaxonomyKind::Tags,
  165. items: vec![tag],
  166. };
  167. let static_fn = make_get_taxonomy_url(Some(tags), None);
  168. // can find it correctly
  169. let mut args = HashMap::new();
  170. args.insert("kind".to_string(), to_value("tag").unwrap());
  171. args.insert("name".to_string(), to_value("Prog amming").unwrap());
  172. assert_eq!(static_fn(args).unwrap(), "http://a-website.com/tags/prog-amming/");
  173. // and errors if it can't find it
  174. let mut args = HashMap::new();
  175. args.insert("kind".to_string(), to_value("tag").unwrap());
  176. args.insert("name".to_string(), to_value("random").unwrap());
  177. assert!(static_fn(args).is_err());
  178. }
  179. #[test]
  180. fn can_translate_a_string() {
  181. let trans_config = r#"
  182. base_url = "https://remplace-par-ton-url.fr"
  183. default_language = "fr"
  184. [translations]
  185. [translations.fr]
  186. title = "Un titre"
  187. [translations.en]
  188. title = "A title"
  189. "#;
  190. let config = Config::parse(trans_config).unwrap();
  191. let static_fn = make_trans(config);
  192. let mut args = HashMap::new();
  193. args.insert("key".to_string(), to_value("title").unwrap());
  194. assert_eq!(static_fn(args.clone()).unwrap(), "Un titre");
  195. args.insert("lang".to_string(), to_value("en").unwrap());
  196. assert_eq!(static_fn(args.clone()).unwrap(), "A title");
  197. args.insert("lang".to_string(), to_value("fr").unwrap());
  198. assert_eq!(static_fn(args.clone()).unwrap(), "Un titre");
  199. }
  200. }