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.

402 lines
12KB

  1. /// A page, can be a blog post or a basic page
  2. use std::cmp::Ordering;
  3. use std::fs::File;
  4. use std::io::prelude::*;
  5. use std::path::Path;
  6. use std::result::Result as StdResult;
  7. use pulldown_cmark as cmark;
  8. use regex::Regex;
  9. use tera::{Tera, Context};
  10. use serde::ser::{SerializeStruct, self};
  11. use slug::slugify;
  12. use errors::{Result, ResultExt};
  13. use config::Config;
  14. use front_matter::{FrontMatter};
  15. lazy_static! {
  16. static ref PAGE_RE: Regex = Regex::new(r"^\n?\+\+\+\n((?s).*(?-s))\+\+\+\n((?s).*(?-s))$").unwrap();
  17. }
  18. #[derive(Clone, Debug, PartialEq, Deserialize)]
  19. pub struct Page {
  20. /// .md filepath, excluding the content/ bit
  21. #[serde(skip_serializing)]
  22. pub filepath: String,
  23. /// The name of the .md file
  24. #[serde(skip_serializing)]
  25. pub filename: String,
  26. /// The directories above our .md file are called sections
  27. /// for example a file at content/kb/solutions/blabla.md will have 2 sections:
  28. /// `kb` and `solutions`
  29. #[serde(skip_serializing)]
  30. pub sections: Vec<String>,
  31. /// The actual content of the page, in markdown
  32. #[serde(skip_serializing)]
  33. pub raw_content: String,
  34. /// The HTML rendered of the page
  35. pub content: String,
  36. /// The front matter meta-data
  37. pub meta: FrontMatter,
  38. /// The slug of that page.
  39. /// First tries to find the slug in the meta and defaults to filename otherwise
  40. pub slug: String,
  41. /// The relative URL of the page
  42. pub url: String,
  43. /// The full URL for that page
  44. pub permalink: String,
  45. /// The previous page, by date
  46. pub previous: Option<Box<Page>>,
  47. /// The next page, by date
  48. pub next: Option<Box<Page>>,
  49. }
  50. impl Page {
  51. pub fn new(meta: FrontMatter) -> Page {
  52. Page {
  53. filepath: "".to_string(),
  54. filename: "".to_string(),
  55. sections: vec![],
  56. raw_content: "".to_string(),
  57. content: "".to_string(),
  58. slug: "".to_string(),
  59. url: "".to_string(),
  60. permalink: "".to_string(),
  61. meta: meta,
  62. previous: None,
  63. next: None,
  64. }
  65. }
  66. // Get word count and estimated reading time
  67. pub fn get_reading_analytics(&self) -> (usize, usize) {
  68. // Only works for latin language but good enough for a start
  69. let word_count: usize = self.raw_content.split_whitespace().count();
  70. // https://help.medium.com/hc/en-us/articles/214991667-Read-time
  71. // 275 seems a bit too high though
  72. (word_count, (word_count / 200))
  73. }
  74. // Parse a page given the content of the .md file
  75. // Files without front matter or with invalid front matter are considered
  76. // erroneous
  77. pub fn parse(filepath: &str, content: &str, config: &Config) -> Result<Page> {
  78. // 1. separate front matter from content
  79. if !PAGE_RE.is_match(content) {
  80. bail!("Couldn't find front matter in `{}`. Did you forget to add `+++`?", filepath);
  81. }
  82. // 2. extract the front matter and the content
  83. let caps = PAGE_RE.captures(content).unwrap();
  84. // caps[0] is the full match
  85. let front_matter = &caps[1];
  86. let content = &caps[2];
  87. // 3. create our page, parse front matter and assign all of that
  88. let meta = FrontMatter::parse(&front_matter)
  89. .chain_err(|| format!("Error when parsing front matter of file `{}`", filepath))?;
  90. let mut page = Page::new(meta);
  91. page.filepath = filepath.to_string();
  92. page.raw_content = content.to_string();
  93. page.content = {
  94. let mut html = String::new();
  95. let parser = cmark::Parser::new(&page.raw_content);
  96. cmark::html::push_html(&mut html, parser);
  97. html
  98. };
  99. let path = Path::new(filepath);
  100. page.filename = path.file_stem().expect("Couldn't get filename").to_string_lossy().to_string();
  101. page.slug = {
  102. if let Some(ref slug) = page.meta.slug {
  103. slug.to_string()
  104. } else {
  105. slugify(page.filename.clone())
  106. }
  107. };
  108. // 4. Find sections
  109. // Pages with custom urls exists outside of sections
  110. if let Some(ref u) = page.meta.url {
  111. page.url = u.to_string();
  112. } else {
  113. // find out if we have sections
  114. for section in path.parent().unwrap().components() {
  115. page.sections.push(section.as_ref().to_string_lossy().to_string());
  116. }
  117. if !page.sections.is_empty() {
  118. page.url = format!("{}/{}", page.sections.join("/"), page.slug);
  119. } else {
  120. page.url = format!("{}", page.slug);
  121. }
  122. }
  123. page.permalink = if config.base_url.ends_with("/") {
  124. format!("{}{}", config.base_url, page.url)
  125. } else {
  126. format!("{}/{}", config.base_url, page.url)
  127. };
  128. Ok(page)
  129. }
  130. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Page> {
  131. let path = path.as_ref();
  132. let mut content = String::new();
  133. File::open(path)
  134. .chain_err(|| format!("Failed to open '{:?}'", path.display()))?
  135. .read_to_string(&mut content)?;
  136. // Remove the content string from name
  137. // Maybe get a path as an arg instead and use strip_prefix?
  138. Page::parse(&path.strip_prefix("content").unwrap().to_string_lossy(), &content, config)
  139. }
  140. fn get_layout_name(&self) -> String {
  141. match self.meta.layout {
  142. Some(ref l) => l.to_string(),
  143. None => "page.html".to_string()
  144. }
  145. }
  146. /// Renders the page using the default layout, unless specified in front-matter
  147. pub fn render_html(&self, tera: &Tera, config: &Config) -> Result<String> {
  148. let tpl = self.get_layout_name();
  149. let mut context = Context::new();
  150. context.add("site", config);
  151. context.add("page", self);
  152. tera.render(&tpl, &context)
  153. .chain_err(|| "Error while rendering template")
  154. }
  155. }
  156. impl ser::Serialize for Page {
  157. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  158. let mut state = serializer.serialize_struct("page", 13)?;
  159. state.serialize_field("content", &self.content)?;
  160. state.serialize_field("title", &self.meta.title)?;
  161. state.serialize_field("description", &self.meta.description)?;
  162. state.serialize_field("date", &self.meta.date)?;
  163. state.serialize_field("slug", &self.slug)?;
  164. state.serialize_field("url", &format!("/{}", self.url))?;
  165. state.serialize_field("permalink", &self.permalink)?;
  166. state.serialize_field("tags", &self.meta.tags)?;
  167. state.serialize_field("draft", &self.meta.draft)?;
  168. state.serialize_field("category", &self.meta.category)?;
  169. state.serialize_field("extra", &self.meta.extra)?;
  170. let (word_count, reading_time) = self.get_reading_analytics();
  171. state.serialize_field("word_count", &word_count)?;
  172. state.serialize_field("reading_time", &reading_time)?;
  173. state.end()
  174. }
  175. }
  176. impl PartialOrd for Page {
  177. fn partial_cmp(&self, other: &Page) -> Option<Ordering> {
  178. if self.meta.date.is_none() {
  179. println!("No self data");
  180. return Some(Ordering::Less);
  181. }
  182. if other.meta.date.is_none() {
  183. println!("No other date");
  184. return Some(Ordering::Greater);
  185. }
  186. let this_date = self.meta.parse_date().unwrap();
  187. let other_date = other.meta.parse_date().unwrap();
  188. if this_date > other_date {
  189. return Some(Ordering::Less);
  190. }
  191. if this_date < other_date {
  192. return Some(Ordering::Greater);
  193. }
  194. Some(Ordering::Equal)
  195. }
  196. }
  197. #[cfg(test)]
  198. mod tests {
  199. use super::{Page};
  200. use config::Config;
  201. #[test]
  202. fn test_can_parse_a_valid_page() {
  203. let content = r#"
  204. +++
  205. title = "Hello"
  206. description = "hey there"
  207. slug = "hello-world"
  208. +++
  209. Hello world"#;
  210. let res = Page::parse("post.md", content, &Config::default());
  211. assert!(res.is_ok());
  212. let page = res.unwrap();
  213. assert_eq!(page.meta.title, "Hello".to_string());
  214. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  215. assert_eq!(page.raw_content, "Hello world".to_string());
  216. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  217. }
  218. #[test]
  219. fn test_can_find_one_parent_directory() {
  220. let content = r#"
  221. +++
  222. title = "Hello"
  223. description = "hey there"
  224. slug = "hello-world"
  225. +++
  226. Hello world"#;
  227. let res = Page::parse("posts/intro.md", content, &Config::default());
  228. assert!(res.is_ok());
  229. let page = res.unwrap();
  230. assert_eq!(page.sections, vec!["posts".to_string()]);
  231. }
  232. #[test]
  233. fn test_can_find_multiple_parent_directories() {
  234. let content = r#"
  235. +++
  236. title = "Hello"
  237. description = "hey there"
  238. slug = "hello-world"
  239. +++
  240. Hello world"#;
  241. let res = Page::parse("posts/intro/start.md", content, &Config::default());
  242. assert!(res.is_ok());
  243. let page = res.unwrap();
  244. assert_eq!(page.sections, vec!["posts".to_string(), "intro".to_string()]);
  245. }
  246. #[test]
  247. fn test_can_make_url_from_sections_and_slug() {
  248. let content = r#"
  249. +++
  250. title = "Hello"
  251. description = "hey there"
  252. slug = "hello-world"
  253. +++
  254. Hello world"#;
  255. let mut conf = Config::default();
  256. conf.base_url = "http://hello.com/".to_string();
  257. let res = Page::parse("posts/intro/start.md", content, &conf);
  258. assert!(res.is_ok());
  259. let page = res.unwrap();
  260. assert_eq!(page.url, "posts/intro/hello-world");
  261. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world");
  262. }
  263. #[test]
  264. fn test_can_make_permalink_with_non_trailing_slash_base_url() {
  265. let content = r#"
  266. +++
  267. title = "Hello"
  268. description = "hey there"
  269. slug = "hello-world"
  270. +++
  271. Hello world"#;
  272. let mut conf = Config::default();
  273. conf.base_url = "http://hello.com".to_string();
  274. let res = Page::parse("posts/intro/start.md", content, &conf);
  275. assert!(res.is_ok());
  276. let page = res.unwrap();
  277. assert_eq!(page.url, "posts/intro/hello-world");
  278. println!("{}", page.permalink);
  279. assert_eq!(page.permalink, format!("{}{}", conf.base_url, "/posts/intro/hello-world"));
  280. }
  281. #[test]
  282. fn test_can_make_url_from_slug_only() {
  283. let content = r#"
  284. +++
  285. title = "Hello"
  286. description = "hey there"
  287. slug = "hello-world"
  288. +++
  289. Hello world"#;
  290. let res = Page::parse("start.md", content, &Config::default());
  291. assert!(res.is_ok());
  292. let page = res.unwrap();
  293. assert_eq!(page.url, "hello-world");
  294. assert_eq!(page.permalink, format!("{}{}", Config::default().base_url, "hello-world"));
  295. }
  296. #[test]
  297. fn test_errors_on_invalid_front_matter_format() {
  298. let content = r#"
  299. title = "Hello"
  300. description = "hey there"
  301. slug = "hello-world"
  302. +++
  303. Hello world"#;
  304. let res = Page::parse("start.md", content, &Config::default());
  305. assert!(res.is_err());
  306. }
  307. #[test]
  308. fn test_can_make_slug_from_non_slug_filename() {
  309. let content = r#"
  310. +++
  311. title = "Hello"
  312. description = "hey there"
  313. +++
  314. Hello world"#;
  315. let res = Page::parse("file with space.md", content, &Config::default());
  316. assert!(res.is_ok());
  317. let page = res.unwrap();
  318. assert_eq!(page.slug, "file-with-space");
  319. assert_eq!(page.permalink, format!("{}{}", Config::default().base_url, "file-with-space"));
  320. }
  321. #[test]
  322. fn test_reading_analytics_short() {
  323. let content = r#"
  324. +++
  325. title = "Hello"
  326. description = "hey there"
  327. +++
  328. Hello world"#;
  329. let res = Page::parse("file with space.md", content, &Config::default());
  330. assert!(res.is_ok());
  331. let page = res.unwrap();
  332. let (word_count, reading_time) = page.get_reading_analytics();
  333. assert_eq!(word_count, 2);
  334. assert_eq!(reading_time, 0);
  335. }
  336. #[test]
  337. fn test_reading_analytics_long() {
  338. let mut content = r#"
  339. +++
  340. title = "Hello"
  341. description = "hey there"
  342. +++
  343. Hello world"#.to_string();
  344. for _ in 0..1000 {
  345. content.push_str(" Hello world");
  346. }
  347. let res = Page::parse("hello.md", &content, &Config::default());
  348. assert!(res.is_ok());
  349. let page = res.unwrap();
  350. let (word_count, reading_time) = page.get_reading_analytics();
  351. assert_eq!(word_count, 2002);
  352. assert_eq!(reading_time, 10);
  353. }
  354. }