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.

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