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.

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