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.

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