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.

447 lines
15KB

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