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.

296 lines
8.6KB

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