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.

317 lines
9.1KB

  1. /// A page, can be a blog post or a basic page
  2. use std::cmp::Ordering;
  3. use std::fs::File;
  4. use std::io::prelude::*;
  5. use std::path::Path;
  6. use std::result::Result as StdResult;
  7. use pulldown_cmark as cmark;
  8. use regex::Regex;
  9. use tera::{Tera, Context};
  10. use serde::ser::{SerializeStruct, self};
  11. use slug::slugify;
  12. use errors::{Result, ResultExt};
  13. use config::Config;
  14. use front_matter::{FrontMatter};
  15. lazy_static! {
  16. static ref PAGE_RE: Regex = Regex::new(r"^\n?\+\+\+\n((?s).*(?-s))\+\+\+\n((?s).*(?-s))$").unwrap();
  17. }
  18. #[derive(Clone, Debug, PartialEq, Deserialize)]
  19. pub struct Page {
  20. /// .md filepath, excluding the content/ bit
  21. #[serde(skip_serializing)]
  22. pub filepath: String,
  23. /// The name of the .md file
  24. #[serde(skip_serializing)]
  25. pub filename: String,
  26. /// The directories above our .md file are called sections
  27. /// for example a file at content/kb/solutions/blabla.md will have 2 sections:
  28. /// `kb` and `solutions`
  29. #[serde(skip_serializing)]
  30. pub sections: Vec<String>,
  31. /// The actual content of the page, in markdown
  32. #[serde(skip_serializing)]
  33. pub raw_content: String,
  34. /// The HTML rendered of the page
  35. pub content: String,
  36. /// The front matter meta-data
  37. pub meta: FrontMatter,
  38. /// The previous page, by date
  39. pub previous: Option<Box<Page>>,
  40. /// The next page, by date
  41. pub next: Option<Box<Page>>,
  42. }
  43. impl Page {
  44. pub fn new(meta: FrontMatter) -> Page {
  45. Page {
  46. filepath: "".to_string(),
  47. filename: "".to_string(),
  48. sections: vec![],
  49. raw_content: "".to_string(),
  50. content: "".to_string(),
  51. meta: meta,
  52. previous: None,
  53. next: None,
  54. }
  55. }
  56. /// Get the slug for the page.
  57. /// First tries to find the slug in the meta and defaults to filename otherwise
  58. pub fn get_slug(&self) -> String {
  59. if let Some(ref slug) = self.meta.slug {
  60. slug.to_string()
  61. } else {
  62. slugify(self.filename.clone())
  63. }
  64. }
  65. pub fn get_url(&self) -> String {
  66. if let Some(ref u) = self.meta.url {
  67. return u.to_string();
  68. }
  69. if !self.sections.is_empty() {
  70. return format!("/{}/{}", self.sections.join("/"), self.get_slug());
  71. }
  72. format!("/{}", self.get_slug())
  73. }
  74. // Parse a page given the content of the .md file
  75. // Files without front matter or with invalid front matter are considered
  76. // erroneous
  77. pub fn parse(filepath: &str, content: &str) -> Result<Page> {
  78. // 1. separate front matter from content
  79. if !PAGE_RE.is_match(content) {
  80. bail!("Couldn't find front matter in `{}`. Did you forget to add `+++`?", filepath);
  81. }
  82. // 2. extract the front matter and the content
  83. let caps = PAGE_RE.captures(content).unwrap();
  84. // caps[0] is the full match
  85. let front_matter = &caps[1];
  86. let content = &caps[2];
  87. // 3. create our page, parse front matter and assign all of that
  88. let meta = FrontMatter::parse(&front_matter)
  89. .chain_err(|| format!("Error when parsing front matter of file `{}`", filepath))?;
  90. let mut page = Page::new(meta);
  91. page.filepath = filepath.to_string();
  92. page.raw_content = content.to_string();
  93. page.content = {
  94. let mut html = String::new();
  95. let parser = cmark::Parser::new(&page.raw_content);
  96. cmark::html::push_html(&mut html, parser);
  97. html
  98. };
  99. // 4. Find sections
  100. // Pages with custom urls exists outside of sections
  101. if page.meta.url.is_none() {
  102. let path = Path::new(filepath);
  103. page.filename = path.file_stem().expect("Couldn't get filename").to_string_lossy().to_string();
  104. // find out if we have sections
  105. for section in path.parent().unwrap().components() {
  106. page.sections.push(section.as_ref().to_string_lossy().to_string());
  107. }
  108. }
  109. Ok(page)
  110. }
  111. pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Page> {
  112. let path = path.as_ref();
  113. let mut content = String::new();
  114. File::open(path)
  115. .chain_err(|| format!("Failed to open '{:?}'", path.display()))?
  116. .read_to_string(&mut content)?;
  117. // Remove the content string from name
  118. // Maybe get a path as an arg instead and use strip_prefix?
  119. Page::parse(&path.strip_prefix("content").unwrap().to_string_lossy(), &content)
  120. }
  121. fn get_layout_name(&self) -> String {
  122. match self.meta.layout {
  123. Some(ref l) => l.to_string(),
  124. None => "page.html".to_string()
  125. }
  126. }
  127. pub fn render_html(&self, tera: &Tera, config: &Config) -> Result<String> {
  128. let tpl = self.get_layout_name();
  129. let mut context = Context::new();
  130. context.add("site", config);
  131. context.add("page", self);
  132. tera.render(&tpl, &context)
  133. .chain_err(|| "Error while rendering template")
  134. }
  135. }
  136. impl ser::Serialize for Page {
  137. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  138. let mut state = serializer.serialize_struct("page", 10)?;
  139. state.serialize_field("content", &self.content)?;
  140. state.serialize_field("title", &self.meta.title)?;
  141. state.serialize_field("description", &self.meta.description)?;
  142. state.serialize_field("date", &self.meta.date)?;
  143. state.serialize_field("slug", &self.get_slug())?;
  144. state.serialize_field("url", &self.get_url())?;
  145. state.serialize_field("tags", &self.meta.tags)?;
  146. state.serialize_field("draft", &self.meta.draft)?;
  147. state.serialize_field("category", &self.meta.category)?;
  148. state.serialize_field("extra", &self.meta.extra)?;
  149. state.end()
  150. }
  151. }
  152. impl PartialOrd for Page {
  153. fn partial_cmp(&self, other: &Page) -> Option<Ordering> {
  154. if self.meta.date.is_none() {
  155. println!("No self data");
  156. return Some(Ordering::Less);
  157. }
  158. if other.meta.date.is_none() {
  159. println!("No other date");
  160. return Some(Ordering::Greater);
  161. }
  162. let this_date = self.meta.parse_date().unwrap();
  163. let other_date = other.meta.parse_date().unwrap();
  164. if this_date > other_date {
  165. return Some(Ordering::Less);
  166. }
  167. if this_date < other_date {
  168. return Some(Ordering::Greater);
  169. }
  170. Some(Ordering::Equal)
  171. }
  172. }
  173. #[cfg(test)]
  174. mod tests {
  175. use super::{Page};
  176. #[test]
  177. fn test_can_parse_a_valid_page() {
  178. let content = r#"
  179. +++
  180. title = "Hello"
  181. description = "hey there"
  182. slug = "hello-world"
  183. +++
  184. Hello world"#;
  185. let res = Page::parse("post.md", content);
  186. assert!(res.is_ok());
  187. let page = res.unwrap();
  188. assert_eq!(page.meta.title, "Hello".to_string());
  189. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  190. assert_eq!(page.raw_content, "Hello world".to_string());
  191. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  192. }
  193. #[test]
  194. fn test_can_find_one_parent_directory() {
  195. let content = r#"
  196. +++
  197. title = "Hello"
  198. description = "hey there"
  199. slug = "hello-world"
  200. +++
  201. Hello world"#;
  202. let res = Page::parse("posts/intro.md", content);
  203. assert!(res.is_ok());
  204. let page = res.unwrap();
  205. assert_eq!(page.sections, vec!["posts".to_string()]);
  206. }
  207. #[test]
  208. fn test_can_find_multiple_parent_directories() {
  209. let content = r#"
  210. +++
  211. title = "Hello"
  212. description = "hey there"
  213. slug = "hello-world"
  214. +++
  215. Hello world"#;
  216. let res = Page::parse("posts/intro/start.md", content);
  217. assert!(res.is_ok());
  218. let page = res.unwrap();
  219. assert_eq!(page.sections, vec!["posts".to_string(), "intro".to_string()]);
  220. }
  221. #[test]
  222. fn test_can_make_url_from_sections_and_slug() {
  223. let content = r#"
  224. +++
  225. title = "Hello"
  226. description = "hey there"
  227. slug = "hello-world"
  228. +++
  229. Hello world"#;
  230. let res = Page::parse("posts/intro/start.md", content);
  231. assert!(res.is_ok());
  232. let page = res.unwrap();
  233. assert_eq!(page.get_url(), "/posts/intro/hello-world");
  234. }
  235. #[test]
  236. fn test_can_make_url_from_sections_and_slug_root() {
  237. let content = r#"
  238. +++
  239. title = "Hello"
  240. description = "hey there"
  241. slug = "hello-world"
  242. +++
  243. Hello world"#;
  244. let res = Page::parse("start.md", content);
  245. assert!(res.is_ok());
  246. let page = res.unwrap();
  247. assert_eq!(page.get_url(), "/hello-world");
  248. }
  249. #[test]
  250. fn test_errors_on_invalid_front_matter_format() {
  251. let content = r#"
  252. title = "Hello"
  253. description = "hey there"
  254. slug = "hello-world"
  255. +++
  256. Hello world"#;
  257. let res = Page::parse("start.md", content);
  258. assert!(res.is_err());
  259. }
  260. #[test]
  261. fn test_can_make_slug_from_non_slug_filename() {
  262. let content = r#"
  263. +++
  264. title = "Hello"
  265. description = "hey there"
  266. +++
  267. Hello world"#;
  268. let res = Page::parse("file with space.md", content);
  269. assert!(res.is_ok());
  270. let page = res.unwrap();
  271. assert_eq!(page.get_slug(), "file-with-space");
  272. }
  273. }