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.

329 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. if !page.path.ends_with('/') {
  85. page.path = format!("{}/", page.path);
  86. }
  87. page.permalink = config.make_permalink(&page.path);
  88. Ok(page)
  89. }
  90. /// Read and parse a .md file into a Page struct
  91. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Page> {
  92. let path = path.as_ref();
  93. let content = read_file(path)?;
  94. let mut page = Page::parse(path, &content, config)?;
  95. page.assets = find_related_assets(path.parent().unwrap());
  96. if !page.assets.is_empty() && page.file.name != "index" {
  97. bail!("Page `{}` has assets ({:?}) but is not named index.md", path.display(), page.assets);
  98. }
  99. Ok(page)
  100. }
  101. /// We need access to all pages url to render links relative to content
  102. /// so that can't happen at the same time as parsing
  103. pub fn render_markdown(&mut self, permalinks: &HashMap<String, String>, tera: &Tera, config: &Config, anchor_insert: InsertAnchor) -> Result<()> {
  104. let context = Context::new(tera, config, permalinks, anchor_insert);
  105. self.content = markdown_to_html(&self.raw_content, &context)?;
  106. if self.raw_content.contains("<!-- more -->") {
  107. self.summary = Some({
  108. let summary = self.raw_content.splitn(2, "<!-- more -->").collect::<Vec<&str>>()[0];
  109. markdown_to_html(summary, &context)?
  110. })
  111. }
  112. Ok(())
  113. }
  114. /// Renders the page using the default layout, unless specified in front-matter
  115. pub fn render_html(&self, tera: &Tera, config: &Config) -> Result<String> {
  116. let tpl_name = match self.meta.template {
  117. Some(ref l) => l.to_string(),
  118. None => "page.html".to_string()
  119. };
  120. let mut context = TeraContext::new();
  121. context.add("config", config);
  122. context.add("page", self);
  123. context.add("current_url", &self.permalink);
  124. context.add("current_path", &self.path);
  125. tera.render(&tpl_name, &context)
  126. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  127. }
  128. }
  129. impl Default for Page {
  130. fn default() -> Page {
  131. Page {
  132. file: FileInfo::default(),
  133. meta: PageFrontMatter::default(),
  134. raw_content: "".to_string(),
  135. assets: vec![],
  136. content: "".to_string(),
  137. slug: "".to_string(),
  138. path: "".to_string(),
  139. permalink: "".to_string(),
  140. summary: None,
  141. previous: None,
  142. next: None,
  143. }
  144. }
  145. }
  146. impl ser::Serialize for Page {
  147. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  148. let mut state = serializer.serialize_struct("page", 15)?;
  149. state.serialize_field("content", &self.content)?;
  150. state.serialize_field("title", &self.meta.title)?;
  151. state.serialize_field("description", &self.meta.description)?;
  152. state.serialize_field("date", &self.meta.date)?;
  153. state.serialize_field("slug", &self.slug)?;
  154. state.serialize_field("path", &format!("/{}", self.path))?;
  155. state.serialize_field("permalink", &self.permalink)?;
  156. state.serialize_field("summary", &self.summary)?;
  157. state.serialize_field("tags", &self.meta.tags)?;
  158. state.serialize_field("category", &self.meta.category)?;
  159. state.serialize_field("extra", &self.meta.extra)?;
  160. let (word_count, reading_time) = get_reading_analytics(&self.raw_content);
  161. state.serialize_field("word_count", &word_count)?;
  162. state.serialize_field("reading_time", &reading_time)?;
  163. state.serialize_field("previous", &self.previous)?;
  164. state.serialize_field("next", &self.next)?;
  165. state.end()
  166. }
  167. }
  168. #[cfg(test)]
  169. mod tests {
  170. use std::collections::HashMap;
  171. use std::fs::{File, create_dir};
  172. use std::path::Path;
  173. use tera::Tera;
  174. use tempdir::TempDir;
  175. use config::Config;
  176. use super::Page;
  177. use front_matter::InsertAnchor;
  178. #[test]
  179. fn test_can_parse_a_valid_page() {
  180. let content = r#"
  181. +++
  182. title = "Hello"
  183. description = "hey there"
  184. slug = "hello-world"
  185. +++
  186. Hello world"#;
  187. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  188. assert!(res.is_ok());
  189. let mut page = res.unwrap();
  190. page.render_markdown(&HashMap::default(), &Tera::default(), &Config::default(), InsertAnchor::None).unwrap();
  191. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  192. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  193. assert_eq!(page.raw_content, "Hello world".to_string());
  194. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  195. }
  196. #[test]
  197. fn test_can_make_url_from_sections_and_slug() {
  198. let content = r#"
  199. +++
  200. slug = "hello-world"
  201. +++
  202. Hello world"#;
  203. let mut conf = Config::default();
  204. conf.base_url = "http://hello.com/".to_string();
  205. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  206. assert!(res.is_ok());
  207. let page = res.unwrap();
  208. assert_eq!(page.path, "posts/intro/hello-world/");
  209. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  210. }
  211. #[test]
  212. fn can_make_url_from_slug_only() {
  213. let content = r#"
  214. +++
  215. slug = "hello-world"
  216. +++
  217. Hello world"#;
  218. let config = Config::default();
  219. let res = Page::parse(Path::new("start.md"), content, &config);
  220. assert!(res.is_ok());
  221. let page = res.unwrap();
  222. assert_eq!(page.path, "hello-world/");
  223. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  224. }
  225. #[test]
  226. fn errors_on_invalid_front_matter_format() {
  227. // missing starting +++
  228. let content = r#"
  229. title = "Hello"
  230. description = "hey there"
  231. slug = "hello-world"
  232. +++
  233. Hello world"#;
  234. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  235. assert!(res.is_err());
  236. }
  237. #[test]
  238. fn can_make_slug_from_non_slug_filename() {
  239. let config = Config::default();
  240. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  241. assert!(res.is_ok());
  242. let page = res.unwrap();
  243. assert_eq!(page.slug, "file-with-space");
  244. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  245. }
  246. #[test]
  247. fn can_specify_summary() {
  248. let config = Config::default();
  249. let content = r#"
  250. +++
  251. +++
  252. Hello world
  253. <!-- more -->"#.to_string();
  254. let res = Page::parse(Path::new("hello.md"), &content, &config);
  255. assert!(res.is_ok());
  256. let mut page = res.unwrap();
  257. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None).unwrap();
  258. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  259. }
  260. #[test]
  261. fn page_with_assets_gets_right_parent_path() {
  262. let tmp_dir = TempDir::new("example").expect("create temp dir");
  263. let path = tmp_dir.path();
  264. create_dir(&path.join("content")).expect("create content temp dir");
  265. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  266. let nested_path = path.join("content").join("posts").join("assets");
  267. create_dir(&nested_path).expect("create nested temp dir");
  268. File::create(nested_path.join("index.md")).unwrap();
  269. File::create(nested_path.join("example.js")).unwrap();
  270. File::create(nested_path.join("graph.jpg")).unwrap();
  271. File::create(nested_path.join("fail.png")).unwrap();
  272. let res = Page::parse(
  273. nested_path.join("index.md").as_path(),
  274. "+++\nurl=\"hey\"+++\n",
  275. &Config::default()
  276. );
  277. assert!(res.is_ok());
  278. let page = res.unwrap();
  279. assert_eq!(page.file.parent, path.join("content").join("posts"));
  280. }
  281. #[test]
  282. fn errors_file_not_named_index_with_assets() {
  283. let tmp_dir = TempDir::new("example").expect("create temp dir");
  284. File::create(tmp_dir.path().join("something.md")).unwrap();
  285. File::create(tmp_dir.path().join("example.js")).unwrap();
  286. File::create(tmp_dir.path().join("graph.jpg")).unwrap();
  287. File::create(tmp_dir.path().join("fail.png")).unwrap();
  288. let page = Page::from_file(tmp_dir.path().join("something.md"), &Config::default());
  289. assert!(page.is_err());
  290. }
  291. }