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.

338 lines
12KB

  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, Section};
  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 = find_related_assets(path.parent().unwrap());
  100. if !page.assets.is_empty() && page.file.name != "index" {
  101. bail!("Page `{}` has assets ({:?}) but is not named index.md", path.display(), page.assets);
  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, section: Option<&Section>) -> 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. context.add("section", &section);
  132. tera.render(&tpl_name, &context)
  133. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  134. }
  135. }
  136. impl Default for Page {
  137. fn default() -> Page {
  138. Page {
  139. file: FileInfo::default(),
  140. meta: PageFrontMatter::default(),
  141. raw_content: "".to_string(),
  142. assets: vec![],
  143. content: "".to_string(),
  144. slug: "".to_string(),
  145. path: "".to_string(),
  146. permalink: "".to_string(),
  147. summary: None,
  148. previous: None,
  149. next: None,
  150. toc: vec![],
  151. }
  152. }
  153. }
  154. impl ser::Serialize for Page {
  155. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  156. let mut state = serializer.serialize_struct("page", 16)?;
  157. state.serialize_field("content", &self.content)?;
  158. state.serialize_field("title", &self.meta.title)?;
  159. state.serialize_field("description", &self.meta.description)?;
  160. state.serialize_field("date", &self.meta.date)?;
  161. state.serialize_field("slug", &self.slug)?;
  162. state.serialize_field("path", &format!("/{}", self.path))?;
  163. state.serialize_field("permalink", &self.permalink)?;
  164. state.serialize_field("summary", &self.summary)?;
  165. state.serialize_field("tags", &self.meta.tags)?;
  166. state.serialize_field("category", &self.meta.category)?;
  167. state.serialize_field("extra", &self.meta.extra)?;
  168. let (word_count, reading_time) = get_reading_analytics(&self.raw_content);
  169. state.serialize_field("word_count", &word_count)?;
  170. state.serialize_field("reading_time", &reading_time)?;
  171. state.serialize_field("previous", &self.previous)?;
  172. state.serialize_field("next", &self.next)?;
  173. state.serialize_field("toc", &self.toc)?;
  174. state.end()
  175. }
  176. }
  177. #[cfg(test)]
  178. mod tests {
  179. use std::collections::HashMap;
  180. use std::fs::{File, create_dir};
  181. use std::path::Path;
  182. use tera::Tera;
  183. use tempdir::TempDir;
  184. use config::Config;
  185. use super::Page;
  186. use front_matter::InsertAnchor;
  187. #[test]
  188. fn test_can_parse_a_valid_page() {
  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(Path::new("post.md"), content, &Config::default());
  197. assert!(res.is_ok());
  198. let mut page = res.unwrap();
  199. page.render_markdown(&HashMap::default(), &Tera::default(), &Config::default(), InsertAnchor::None).unwrap();
  200. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  201. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  202. assert_eq!(page.raw_content, "Hello world".to_string());
  203. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  204. }
  205. #[test]
  206. fn test_can_make_url_from_sections_and_slug() {
  207. let content = r#"
  208. +++
  209. slug = "hello-world"
  210. +++
  211. Hello world"#;
  212. let mut conf = Config::default();
  213. conf.base_url = "http://hello.com/".to_string();
  214. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  215. assert!(res.is_ok());
  216. let page = res.unwrap();
  217. assert_eq!(page.path, "posts/intro/hello-world/");
  218. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  219. }
  220. #[test]
  221. fn can_make_url_from_slug_only() {
  222. let content = r#"
  223. +++
  224. slug = "hello-world"
  225. +++
  226. Hello world"#;
  227. let config = Config::default();
  228. let res = Page::parse(Path::new("start.md"), content, &config);
  229. assert!(res.is_ok());
  230. let page = res.unwrap();
  231. assert_eq!(page.path, "hello-world/");
  232. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  233. }
  234. #[test]
  235. fn errors_on_invalid_front_matter_format() {
  236. // missing starting +++
  237. let content = r#"
  238. title = "Hello"
  239. description = "hey there"
  240. slug = "hello-world"
  241. +++
  242. Hello world"#;
  243. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  244. assert!(res.is_err());
  245. }
  246. #[test]
  247. fn can_make_slug_from_non_slug_filename() {
  248. let config = Config::default();
  249. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  250. assert!(res.is_ok());
  251. let page = res.unwrap();
  252. assert_eq!(page.slug, "file-with-space");
  253. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  254. }
  255. #[test]
  256. fn can_specify_summary() {
  257. let config = Config::default();
  258. let content = r#"
  259. +++
  260. +++
  261. Hello world
  262. <!-- more -->"#.to_string();
  263. let res = Page::parse(Path::new("hello.md"), &content, &config);
  264. assert!(res.is_ok());
  265. let mut page = res.unwrap();
  266. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None).unwrap();
  267. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  268. }
  269. #[test]
  270. fn page_with_assets_gets_right_parent_path() {
  271. let tmp_dir = TempDir::new("example").expect("create temp dir");
  272. let path = tmp_dir.path();
  273. create_dir(&path.join("content")).expect("create content temp dir");
  274. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  275. let nested_path = path.join("content").join("posts").join("assets");
  276. create_dir(&nested_path).expect("create nested temp dir");
  277. File::create(nested_path.join("index.md")).unwrap();
  278. File::create(nested_path.join("example.js")).unwrap();
  279. File::create(nested_path.join("graph.jpg")).unwrap();
  280. File::create(nested_path.join("fail.png")).unwrap();
  281. let res = Page::parse(
  282. nested_path.join("index.md").as_path(),
  283. "+++\nurl=\"hey\"+++\n",
  284. &Config::default()
  285. );
  286. assert!(res.is_ok());
  287. let page = res.unwrap();
  288. assert_eq!(page.file.parent, path.join("content").join("posts"));
  289. }
  290. #[test]
  291. fn errors_file_not_named_index_with_assets() {
  292. let tmp_dir = TempDir::new("example").expect("create temp dir");
  293. File::create(tmp_dir.path().join("something.md")).unwrap();
  294. File::create(tmp_dir.path().join("example.js")).unwrap();
  295. File::create(tmp_dir.path().join("graph.jpg")).unwrap();
  296. File::create(tmp_dir.path().join("fail.png")).unwrap();
  297. let page = Page::from_file(tmp_dir.path().join("something.md"), &Config::default());
  298. assert!(page.is_err());
  299. }
  300. }