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.

327 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 fs::{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", 15)?;
  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("category", &self.meta.category)?;
  154. state.serialize_field("extra", &self.meta.extra)?;
  155. let (word_count, reading_time) = get_reading_analytics(&self.raw_content);
  156. state.serialize_field("word_count", &word_count)?;
  157. state.serialize_field("reading_time", &reading_time)?;
  158. state.serialize_field("previous", &self.previous)?;
  159. state.serialize_field("next", &self.next)?;
  160. state.end()
  161. }
  162. }
  163. #[cfg(test)]
  164. mod tests {
  165. use std::collections::HashMap;
  166. use std::fs::{File, create_dir};
  167. use std::path::Path;
  168. use tera::Tera;
  169. use tempdir::TempDir;
  170. use config::Config;
  171. use super::Page;
  172. #[test]
  173. fn test_can_parse_a_valid_page() {
  174. let content = r#"
  175. +++
  176. title = "Hello"
  177. description = "hey there"
  178. slug = "hello-world"
  179. +++
  180. Hello world"#;
  181. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  182. assert!(res.is_ok());
  183. let mut page = res.unwrap();
  184. page.render_markdown(&HashMap::default(), &Tera::default(), &Config::default()).unwrap();
  185. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  186. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  187. assert_eq!(page.raw_content, "Hello world".to_string());
  188. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  189. }
  190. #[test]
  191. fn test_can_make_url_from_sections_and_slug() {
  192. let content = r#"
  193. +++
  194. slug = "hello-world"
  195. +++
  196. Hello world"#;
  197. let mut conf = Config::default();
  198. conf.base_url = "http://hello.com/".to_string();
  199. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  200. assert!(res.is_ok());
  201. let mut page = res.unwrap();
  202. page.render_markdown(&HashMap::default(), &Tera::default(), &Config::default()).unwrap();
  203. assert_eq!(page.path, "posts/intro/hello-world");
  204. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world");
  205. }
  206. #[test]
  207. fn can_make_url_from_slug_only() {
  208. let content = r#"
  209. +++
  210. slug = "hello-world"
  211. +++
  212. Hello world"#;
  213. let config = Config::default();
  214. let res = Page::parse(Path::new("start.md"), content, &config);
  215. assert!(res.is_ok());
  216. let mut page = res.unwrap();
  217. page.render_markdown(&HashMap::default(), &Tera::default(), &config).unwrap();
  218. assert_eq!(page.path, "hello-world");
  219. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  220. }
  221. #[test]
  222. fn errors_on_invalid_front_matter_format() {
  223. // missing starting +++
  224. let content = r#"
  225. title = "Hello"
  226. description = "hey there"
  227. slug = "hello-world"
  228. +++
  229. Hello world"#;
  230. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  231. assert!(res.is_err());
  232. }
  233. #[test]
  234. fn can_make_slug_from_non_slug_filename() {
  235. let config = Config::default();
  236. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  237. assert!(res.is_ok());
  238. let mut page = res.unwrap();
  239. page.render_markdown(&HashMap::default(), &Tera::default(), &config).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).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. }