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.

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