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.

374 lines
13KB

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