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.

325 lines
11KB

  1. /// A page, can be a blog post or a basic page
  2. use std::collections::HashMap;
  3. use std::path::{Path, PathBuf};
  4. use std::result::Result as StdResult;
  5. use tera::{Tera, Context as TeraContext};
  6. use serde::ser::{SerializeStruct, self};
  7. use slug::slugify;
  8. use errors::{Result, ResultExt};
  9. use config::Config;
  10. use front_matter::{PageFrontMatter, InsertAnchor, split_page_content};
  11. use rendering::markdown::markdown_to_html;
  12. use rendering::context::Context;
  13. use fs::{read_file};
  14. use content::utils::{find_related_assets, get_reading_analytics};
  15. use content::file_info::FileInfo;
  16. use content::{Header};
  17. #[derive(Clone, Debug, PartialEq)]
  18. pub struct Page {
  19. /// All info about the actual file
  20. pub file: FileInfo,
  21. /// The front matter meta-data
  22. pub meta: PageFrontMatter,
  23. /// The actual content of the page, in markdown
  24. pub raw_content: String,
  25. /// All the non-md files we found next to the .md file
  26. pub assets: Vec<PathBuf>,
  27. /// The HTML rendered of the page
  28. pub content: String,
  29. /// The slug of that page.
  30. /// First tries to find the slug in the meta and defaults to filename otherwise
  31. pub slug: String,
  32. /// The URL path of the page
  33. pub path: String,
  34. /// The full URL for that page
  35. pub permalink: String,
  36. /// The summary for the article, defaults to None
  37. /// When <!-- more --> is found in the text, will take the content up to that part
  38. /// as summary
  39. pub summary: Option<String>,
  40. /// The previous page, by whatever sorting is used for the index/section
  41. pub previous: Option<Box<Page>>,
  42. /// The next page, by whatever sorting is used for the index/section
  43. pub next: Option<Box<Page>>,
  44. /// Toc made from the headers of the markdown file
  45. pub toc: Vec<Header>,
  46. }
  47. impl Page {
  48. pub fn new<P: AsRef<Path>>(file_path: P, meta: PageFrontMatter) -> Page {
  49. let file_path = file_path.as_ref();
  50. Page {
  51. file: FileInfo::new_page(file_path),
  52. meta: meta,
  53. raw_content: "".to_string(),
  54. assets: vec![],
  55. content: "".to_string(),
  56. slug: "".to_string(),
  57. path: "".to_string(),
  58. permalink: "".to_string(),
  59. summary: None,
  60. previous: None,
  61. next: None,
  62. toc: vec![],
  63. }
  64. }
  65. /// Parse a page given the content of the .md file
  66. /// Files without front matter or with invalid front matter are considered
  67. /// erroneous
  68. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Page> {
  69. let (meta, content) = split_page_content(file_path, content)?;
  70. let mut page = Page::new(file_path, meta);
  71. page.raw_content = content;
  72. page.slug = {
  73. if let Some(ref slug) = page.meta.slug {
  74. slug.trim().to_string()
  75. } else {
  76. slugify(page.file.name.clone())
  77. }
  78. };
  79. if let Some(ref u) = page.meta.url {
  80. page.path = u.trim().to_string();
  81. } else {
  82. page.path = if page.file.components.is_empty() {
  83. page.slug.clone()
  84. } else {
  85. format!("{}/{}", page.file.components.join("/"), page.slug)
  86. };
  87. }
  88. if !page.path.ends_with('/') {
  89. page.path = format!("{}/", page.path);
  90. }
  91. page.permalink = config.make_permalink(&page.path);
  92. Ok(page)
  93. }
  94. /// Read and parse a .md file into a Page struct
  95. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Page> {
  96. let path = path.as_ref();
  97. let content = read_file(path)?;
  98. let mut page = Page::parse(path, &content, config)?;
  99. page.assets = vec![];
  100. if page.file.name == "index" {
  101. page.assets = find_related_assets(path.parent().unwrap());
  102. }
  103. Ok(page)
  104. }
  105. /// We need access to all pages url to render links relative to content
  106. /// so that can't happen at the same time as parsing
  107. pub fn render_markdown(&mut self, permalinks: &HashMap<String, String>, tera: &Tera, config: &Config, anchor_insert: InsertAnchor) -> Result<()> {
  108. let context = Context::new(tera, config, &self.permalink, permalinks, anchor_insert);
  109. let res = markdown_to_html(&self.raw_content, &context)?;
  110. self.content = res.0;
  111. self.toc = res.1;
  112. if self.raw_content.contains("<!-- more -->") {
  113. self.summary = Some({
  114. let summary = self.raw_content.splitn(2, "<!-- more -->").collect::<Vec<&str>>()[0];
  115. markdown_to_html(summary, &context)?.0
  116. })
  117. }
  118. Ok(())
  119. }
  120. /// Renders the page using the default layout, unless specified in front-matter
  121. pub fn render_html(&self, tera: &Tera, config: &Config) -> Result<String> {
  122. let tpl_name = match self.meta.template {
  123. Some(ref l) => l.to_string(),
  124. None => "page.html".to_string()
  125. };
  126. let mut context = TeraContext::new();
  127. context.add("config", config);
  128. context.add("page", self);
  129. context.add("current_url", &self.permalink);
  130. context.add("current_path", &self.path);
  131. tera.render(&tpl_name, &context)
  132. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  133. }
  134. }
  135. impl Default for Page {
  136. fn default() -> Page {
  137. Page {
  138. file: FileInfo::default(),
  139. meta: PageFrontMatter::default(),
  140. raw_content: "".to_string(),
  141. assets: vec![],
  142. content: "".to_string(),
  143. slug: "".to_string(),
  144. path: "".to_string(),
  145. permalink: "".to_string(),
  146. summary: None,
  147. previous: None,
  148. next: None,
  149. toc: vec![],
  150. }
  151. }
  152. }
  153. impl ser::Serialize for Page {
  154. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  155. let mut state = serializer.serialize_struct("page", 16)?;
  156. state.serialize_field("content", &self.content)?;
  157. state.serialize_field("title", &self.meta.title)?;
  158. state.serialize_field("description", &self.meta.description)?;
  159. state.serialize_field("date", &self.meta.date)?;
  160. state.serialize_field("slug", &self.slug)?;
  161. state.serialize_field("path", &format!("/{}", self.path))?;
  162. state.serialize_field("permalink", &self.permalink)?;
  163. state.serialize_field("summary", &self.summary)?;
  164. state.serialize_field("tags", &self.meta.tags)?;
  165. state.serialize_field("category", &self.meta.category)?;
  166. state.serialize_field("extra", &self.meta.extra)?;
  167. let (word_count, reading_time) = get_reading_analytics(&self.raw_content);
  168. state.serialize_field("word_count", &word_count)?;
  169. state.serialize_field("reading_time", &reading_time)?;
  170. state.serialize_field("previous", &self.previous)?;
  171. state.serialize_field("next", &self.next)?;
  172. state.serialize_field("toc", &self.toc)?;
  173. state.end()
  174. }
  175. }
  176. #[cfg(test)]
  177. mod tests {
  178. use std::collections::HashMap;
  179. use std::fs::{File, create_dir};
  180. use std::path::Path;
  181. use tera::Tera;
  182. use tempdir::TempDir;
  183. use config::Config;
  184. use super::Page;
  185. use front_matter::InsertAnchor;
  186. #[test]
  187. fn test_can_parse_a_valid_page() {
  188. let content = r#"
  189. +++
  190. title = "Hello"
  191. description = "hey there"
  192. slug = "hello-world"
  193. +++
  194. Hello world"#;
  195. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  196. assert!(res.is_ok());
  197. let mut page = res.unwrap();
  198. page.render_markdown(&HashMap::default(), &Tera::default(), &Config::default(), InsertAnchor::None).unwrap();
  199. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  200. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  201. assert_eq!(page.raw_content, "Hello world".to_string());
  202. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  203. }
  204. #[test]
  205. fn test_can_make_url_from_sections_and_slug() {
  206. let content = r#"
  207. +++
  208. slug = "hello-world"
  209. +++
  210. Hello world"#;
  211. let mut conf = Config::default();
  212. conf.base_url = "http://hello.com/".to_string();
  213. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  214. assert!(res.is_ok());
  215. let page = res.unwrap();
  216. assert_eq!(page.path, "posts/intro/hello-world/");
  217. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  218. }
  219. #[test]
  220. fn can_make_url_from_slug_only() {
  221. let content = r#"
  222. +++
  223. slug = "hello-world"
  224. +++
  225. Hello world"#;
  226. let config = Config::default();
  227. let res = Page::parse(Path::new("start.md"), content, &config);
  228. assert!(res.is_ok());
  229. let page = res.unwrap();
  230. assert_eq!(page.path, "hello-world/");
  231. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  232. }
  233. #[test]
  234. fn errors_on_invalid_front_matter_format() {
  235. // missing starting +++
  236. let content = r#"
  237. title = "Hello"
  238. description = "hey there"
  239. slug = "hello-world"
  240. +++
  241. Hello world"#;
  242. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  243. assert!(res.is_err());
  244. }
  245. #[test]
  246. fn can_make_slug_from_non_slug_filename() {
  247. let config = Config::default();
  248. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  249. assert!(res.is_ok());
  250. let page = res.unwrap();
  251. assert_eq!(page.slug, "file-with-space");
  252. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  253. }
  254. #[test]
  255. fn can_specify_summary() {
  256. let config = Config::default();
  257. let content = r#"
  258. +++
  259. +++
  260. Hello world
  261. <!-- more -->"#.to_string();
  262. let res = Page::parse(Path::new("hello.md"), &content, &config);
  263. assert!(res.is_ok());
  264. let mut page = res.unwrap();
  265. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None).unwrap();
  266. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  267. }
  268. #[test]
  269. fn page_with_assets_gets_right_parent_path() {
  270. let tmp_dir = TempDir::new("example").expect("create temp dir");
  271. let path = tmp_dir.path();
  272. create_dir(&path.join("content")).expect("create content temp dir");
  273. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  274. let nested_path = path.join("content").join("posts").join("assets");
  275. create_dir(&nested_path).expect("create nested temp dir");
  276. File::create(nested_path.join("index.md")).unwrap();
  277. File::create(nested_path.join("example.js")).unwrap();
  278. File::create(nested_path.join("graph.jpg")).unwrap();
  279. File::create(nested_path.join("fail.png")).unwrap();
  280. let res = Page::parse(
  281. nested_path.join("index.md").as_path(),
  282. "+++\nurl=\"hey\"+++\n",
  283. &Config::default()
  284. );
  285. assert!(res.is_ok());
  286. let page = res.unwrap();
  287. assert_eq!(page.file.parent, path.join("content").join("posts"));
  288. }
  289. }