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.

277 lines
8.2KB

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