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.

page.rs 11KB

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