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.

page.rs 8.0KB

5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. use std::collections::HashMap;
  2. use chrono::prelude::*;
  3. use serde_derive::Deserialize;
  4. use tera::{Map, Value};
  5. use toml;
  6. use errors::{bail, Result};
  7. use utils::de::{fix_toml_dates, from_toml_datetime};
  8. /// The front matter of every page
  9. #[derive(Debug, Clone, PartialEq, Deserialize)]
  10. #[serde(default)]
  11. pub struct PageFrontMatter {
  12. /// <title> of the page
  13. pub title: Option<String>,
  14. /// Description in <meta> that appears when linked, e.g. on twitter
  15. pub description: Option<String>,
  16. /// Date if we want to order pages (ie blog post)
  17. #[serde(default, deserialize_with = "from_toml_datetime")]
  18. pub date: Option<String>,
  19. /// Chrono converted datetime
  20. #[serde(default, skip_deserializing)]
  21. pub datetime: Option<NaiveDateTime>,
  22. /// The converted date into a (year, month, day) tuple
  23. #[serde(default, skip_deserializing)]
  24. pub datetime_tuple: Option<(i32, u32, u32)>,
  25. /// Whether this page is a draft
  26. pub draft: bool,
  27. /// The page slug. Will be used instead of the filename if present
  28. /// Can't be an empty string if present
  29. pub slug: Option<String>,
  30. /// The path the page appears at, overrides the slug if set in the front-matter
  31. /// otherwise is set after parsing front matter and sections
  32. /// Can't be an empty string if present
  33. pub path: Option<String>,
  34. pub taxonomies: HashMap<String, Vec<String>>,
  35. /// Integer to use to order content. Lowest is at the bottom, highest first
  36. pub order: Option<usize>,
  37. /// Integer to use to order content. Highest is at the bottom, lowest first
  38. pub weight: Option<usize>,
  39. /// All aliases for that page. Zola will create HTML templates that will
  40. /// redirect to this
  41. #[serde(skip_serializing)]
  42. pub aliases: Vec<String>,
  43. /// Specify a template different from `page.html` to use for that page
  44. #[serde(skip_serializing)]
  45. pub template: Option<String>,
  46. /// Whether the page is included in the search index
  47. /// Defaults to `true` but is only used if search if explicitly enabled in the config.
  48. #[serde(skip_serializing)]
  49. pub in_search_index: bool,
  50. /// Any extra parameter present in the front matter
  51. pub extra: Map<String, Value>,
  52. }
  53. impl PageFrontMatter {
  54. pub fn parse(toml: &str) -> Result<PageFrontMatter> {
  55. let mut f: PageFrontMatter = match toml::from_str(toml) {
  56. Ok(d) => d,
  57. Err(e) => bail!(e),
  58. };
  59. if let Some(ref slug) = f.slug {
  60. if slug == "" {
  61. bail!("`slug` can't be empty if present")
  62. }
  63. }
  64. if let Some(ref path) = f.path {
  65. if path == "" {
  66. bail!("`path` can't be empty if present")
  67. }
  68. }
  69. f.extra = match fix_toml_dates(f.extra) {
  70. Value::Object(o) => o,
  71. _ => unreachable!("Got something other than a table in page extra"),
  72. };
  73. f.date_to_datetime();
  74. Ok(f)
  75. }
  76. /// Converts the TOML datetime to a Chrono naive datetime
  77. /// Also grabs the year/month/day tuple that will be used in serialization
  78. pub fn date_to_datetime(&mut self) {
  79. self.datetime = if let Some(ref d) = self.date {
  80. if d.contains('T') {
  81. DateTime::parse_from_rfc3339(&d).ok().map(|s| s.naive_local())
  82. } else {
  83. NaiveDate::parse_from_str(&d, "%Y-%m-%d")
  84. .ok()
  85. .map(|s| s.and_hms(0, 0, 0))
  86. }
  87. } else {
  88. None
  89. };
  90. self.datetime_tuple = if let Some(ref dt) = self.datetime {
  91. Some((dt.year(), dt.month(), dt.day()))
  92. } else {
  93. None
  94. };
  95. }
  96. pub fn order(&self) -> usize {
  97. self.order.unwrap()
  98. }
  99. pub fn weight(&self) -> usize {
  100. self.weight.unwrap()
  101. }
  102. }
  103. impl Default for PageFrontMatter {
  104. fn default() -> PageFrontMatter {
  105. PageFrontMatter {
  106. title: None,
  107. description: None,
  108. date: None,
  109. datetime: None,
  110. datetime_tuple: None,
  111. draft: false,
  112. slug: None,
  113. path: None,
  114. taxonomies: HashMap::new(),
  115. order: None,
  116. weight: None,
  117. aliases: Vec::new(),
  118. in_search_index: true,
  119. template: None,
  120. extra: Map::new(),
  121. }
  122. }
  123. }
  124. #[cfg(test)]
  125. mod tests {
  126. use super::PageFrontMatter;
  127. use tera::to_value;
  128. #[test]
  129. fn can_have_empty_front_matter() {
  130. let content = r#" "#;
  131. let res = PageFrontMatter::parse(content);
  132. println!("{:?}", res);
  133. assert!(res.is_ok());
  134. }
  135. #[test]
  136. fn can_parse_valid_front_matter() {
  137. let content = r#"
  138. title = "Hello"
  139. description = "hey there""#;
  140. let res = PageFrontMatter::parse(content);
  141. assert!(res.is_ok());
  142. let res = res.unwrap();
  143. assert_eq!(res.title.unwrap(), "Hello".to_string());
  144. assert_eq!(res.description.unwrap(), "hey there".to_string())
  145. }
  146. #[test]
  147. fn errors_with_invalid_front_matter() {
  148. let content = r#"title = 1\n"#;
  149. let res = PageFrontMatter::parse(content);
  150. assert!(res.is_err());
  151. }
  152. #[test]
  153. fn errors_on_present_but_empty_slug() {
  154. let content = r#"
  155. title = "Hello"
  156. description = "hey there"
  157. slug = """#;
  158. let res = PageFrontMatter::parse(content);
  159. assert!(res.is_err());
  160. }
  161. #[test]
  162. fn errors_on_present_but_empty_path() {
  163. let content = r#"
  164. title = "Hello"
  165. description = "hey there"
  166. path = """#;
  167. let res = PageFrontMatter::parse(content);
  168. assert!(res.is_err());
  169. }
  170. #[test]
  171. fn can_parse_date_yyyy_mm_dd() {
  172. let content = r#"
  173. title = "Hello"
  174. description = "hey there"
  175. date = 2016-10-10
  176. "#;
  177. let res = PageFrontMatter::parse(content).unwrap();
  178. assert!(res.date.is_some());
  179. }
  180. #[test]
  181. fn can_parse_date_rfc3339() {
  182. let content = r#"
  183. title = "Hello"
  184. description = "hey there"
  185. date = 2002-10-02T15:00:00Z
  186. "#;
  187. let res = PageFrontMatter::parse(content).unwrap();
  188. assert!(res.date.is_some());
  189. }
  190. #[test]
  191. fn cannot_parse_random_date_format() {
  192. let content = r#"
  193. title = "Hello"
  194. description = "hey there"
  195. date = 2002/10/12"#;
  196. let res = PageFrontMatter::parse(content);
  197. assert!(res.is_err());
  198. }
  199. #[test]
  200. fn cannot_parse_invalid_date_format() {
  201. let content = r#"
  202. title = "Hello"
  203. description = "hey there"
  204. date = 2002-14-01"#;
  205. let res = PageFrontMatter::parse(content);
  206. assert!(res.is_err());
  207. }
  208. #[test]
  209. fn cannot_parse_date_as_string() {
  210. let content = r#"
  211. title = "Hello"
  212. description = "hey there"
  213. date = "2002-14-01""#;
  214. let res = PageFrontMatter::parse(content);
  215. assert!(res.is_err());
  216. }
  217. #[test]
  218. fn can_parse_dates_in_extra() {
  219. let content = r#"
  220. title = "Hello"
  221. description = "hey there"
  222. [extra]
  223. some-date = 2002-14-01"#;
  224. let res = PageFrontMatter::parse(content);
  225. println!("{:?}", res);
  226. assert!(res.is_ok());
  227. assert_eq!(res.unwrap().extra["some-date"], to_value("2002-14-01").unwrap());
  228. }
  229. #[test]
  230. fn can_parse_nested_dates_in_extra() {
  231. let content = r#"
  232. title = "Hello"
  233. description = "hey there"
  234. [extra.something]
  235. some-date = 2002-14-01"#;
  236. let res = PageFrontMatter::parse(content);
  237. println!("{:?}", res);
  238. assert!(res.is_ok());
  239. assert_eq!(res.unwrap().extra["something"]["some-date"], to_value("2002-14-01").unwrap());
  240. }
  241. #[test]
  242. fn can_parse_taxonomies() {
  243. let content = r#"
  244. title = "Hello World"
  245. [taxonomies]
  246. tags = ["Rust", "JavaScript"]
  247. categories = ["Dev"]
  248. "#;
  249. let res = PageFrontMatter::parse(content);
  250. println!("{:?}", res);
  251. assert!(res.is_ok());
  252. let res2 = res.unwrap();
  253. assert_eq!(res2.taxonomies["categories"], vec!["Dev"]);
  254. assert_eq!(res2.taxonomies["tags"], vec!["Rust", "JavaScript"]);
  255. }
  256. }