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.

563 lines
20KB

  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 regex::Regex;
  5. use slotmap::Key;
  6. use slug::slugify;
  7. use tera::{Context as TeraContext, Tera};
  8. use config::Config;
  9. use errors::{Result, ResultExt};
  10. use front_matter::{split_page_content, InsertAnchor, PageFrontMatter};
  11. use library::Library;
  12. use rendering::{render_content, Header, RenderContext};
  13. use utils::fs::{find_related_assets, read_file};
  14. use utils::site::get_reading_analytics;
  15. use utils::templates::render_template;
  16. use content::file_info::FileInfo;
  17. use content::ser::SerializingPage;
  18. lazy_static! {
  19. // Based on https://regex101.com/r/H2n38Z/1/tests
  20. // A regex parsing RFC3339 date followed by {_,-}, some characters and ended by .md
  21. static ref RFC3339_DATE: Regex = Regex::new(
  22. r"^(?P<datetime>(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9])))?)(_|-)(?P<slug>.+$)"
  23. ).unwrap();
  24. }
  25. #[derive(Clone, Debug, PartialEq)]
  26. pub struct Page {
  27. /// All info about the actual file
  28. pub file: FileInfo,
  29. /// The front matter meta-data
  30. pub meta: PageFrontMatter,
  31. /// The list of parent sections
  32. pub ancestors: Vec<Key>,
  33. /// The actual content of the page, in markdown
  34. pub raw_content: String,
  35. /// All the non-md files we found next to the .md file
  36. pub assets: Vec<PathBuf>,
  37. /// All the non-md files we found next to the .md file as string for use in templates
  38. pub serialized_assets: Vec<String>,
  39. /// The HTML rendered of the page
  40. pub content: String,
  41. /// The slug of that page.
  42. /// First tries to find the slug in the meta and defaults to filename otherwise
  43. pub slug: String,
  44. /// The URL path of the page
  45. pub path: String,
  46. /// The components of the path of the page
  47. pub components: Vec<String>,
  48. /// The full URL for that page
  49. pub permalink: String,
  50. /// The summary for the article, defaults to None
  51. /// When <!-- more --> is found in the text, will take the content up to that part
  52. /// as summary
  53. pub summary: Option<String>,
  54. /// The earlier page, for pages sorted by date
  55. pub earlier: Option<Key>,
  56. /// The later page, for pages sorted by date
  57. pub later: Option<Key>,
  58. /// The lighter page, for pages sorted by weight
  59. pub lighter: Option<Key>,
  60. /// The heavier page, for pages sorted by weight
  61. pub heavier: Option<Key>,
  62. /// Toc made from the headers of the markdown file
  63. pub toc: Vec<Header>,
  64. /// How many words in the raw content
  65. pub word_count: Option<usize>,
  66. /// How long would it take to read the raw content.
  67. /// See `get_reading_analytics` on how it is calculated
  68. pub reading_time: Option<usize>,
  69. }
  70. impl Page {
  71. pub fn new<P: AsRef<Path>>(file_path: P, meta: PageFrontMatter) -> Page {
  72. let file_path = file_path.as_ref();
  73. Page {
  74. file: FileInfo::new_page(file_path),
  75. meta,
  76. ancestors: vec![],
  77. raw_content: "".to_string(),
  78. assets: vec![],
  79. serialized_assets: vec![],
  80. content: "".to_string(),
  81. slug: "".to_string(),
  82. path: "".to_string(),
  83. components: vec![],
  84. permalink: "".to_string(),
  85. summary: None,
  86. earlier: None,
  87. later: None,
  88. lighter: None,
  89. heavier: None,
  90. toc: vec![],
  91. word_count: None,
  92. reading_time: None,
  93. }
  94. }
  95. pub fn is_draft(&self) -> bool {
  96. self.meta.draft
  97. }
  98. /// Parse a page given the content of the .md file
  99. /// Files without front matter or with invalid front matter are considered
  100. /// erroneous
  101. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Page> {
  102. let (meta, content) = split_page_content(file_path, content)?;
  103. let mut page = Page::new(file_path, meta);
  104. page.raw_content = content;
  105. let (word_count, reading_time) = get_reading_analytics(&page.raw_content);
  106. page.word_count = Some(word_count);
  107. page.reading_time = Some(reading_time);
  108. let mut slug_from_dated_filename = None;
  109. if let Some(ref caps) = RFC3339_DATE.captures(&page.file.name.replace(".md", "")) {
  110. slug_from_dated_filename = Some(caps.name("slug").unwrap().as_str().to_string());
  111. if page.meta.date.is_none() {
  112. page.meta.date = Some(caps.name("datetime").unwrap().as_str().to_string());
  113. page.meta.date_to_datetime();
  114. }
  115. }
  116. page.slug = {
  117. if let Some(ref slug) = page.meta.slug {
  118. slug.trim().to_string()
  119. } else if page.file.name == "index" {
  120. if let Some(parent) = page.file.path.parent() {
  121. slugify(parent.file_name().unwrap().to_str().unwrap())
  122. } else {
  123. slugify(&page.file.name)
  124. }
  125. } else {
  126. if let Some(slug) = slug_from_dated_filename {
  127. slugify(&slug)
  128. } else {
  129. slugify(&page.file.name)
  130. }
  131. }
  132. };
  133. if let Some(ref p) = page.meta.path {
  134. page.path = p.trim().trim_left_matches('/').to_string();
  135. } else {
  136. page.path = if page.file.components.is_empty() {
  137. page.slug.clone()
  138. } else {
  139. format!("{}/{}", page.file.components.join("/"), page.slug)
  140. };
  141. }
  142. if !page.path.ends_with('/') {
  143. page.path = format!("{}/", page.path);
  144. }
  145. page.components = page
  146. .path
  147. .split('/')
  148. .map(|p| p.to_string())
  149. .filter(|p| !p.is_empty())
  150. .collect::<Vec<_>>();
  151. page.permalink = config.make_permalink(&page.path);
  152. Ok(page)
  153. }
  154. /// Read and parse a .md file into a Page struct
  155. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Page> {
  156. let path = path.as_ref();
  157. let content = read_file(path)?;
  158. let mut page = Page::parse(path, &content, config)?;
  159. if page.file.name == "index" {
  160. let parent_dir = path.parent().unwrap();
  161. let assets = find_related_assets(parent_dir);
  162. if let Some(ref globset) = config.ignored_content_globset {
  163. // `find_related_assets` only scans the immediate directory (it is not recursive) so our
  164. // filtering only needs to work against the file_name component, not the full suffix. If
  165. // `find_related_assets` was changed to also return files in subdirectories, we could
  166. // use `PathBuf.strip_prefix` to remove the parent directory and then glob-filter
  167. // against the remaining path. Note that the current behaviour effectively means that
  168. // the `ignored_content` setting in the config file is limited to single-file glob
  169. // patterns (no "**" patterns).
  170. page.assets = assets
  171. .into_iter()
  172. .filter(|path| match path.file_name() {
  173. None => true,
  174. Some(file) => !globset.is_match(file),
  175. })
  176. .collect();
  177. } else {
  178. page.assets = assets;
  179. }
  180. page.serialized_assets = page.serialize_assets();
  181. } else {
  182. page.assets = vec![];
  183. }
  184. Ok(page)
  185. }
  186. /// We need access to all pages url to render links relative to content
  187. /// so that can't happen at the same time as parsing
  188. pub fn render_markdown(
  189. &mut self,
  190. permalinks: &HashMap<String, String>,
  191. tera: &Tera,
  192. config: &Config,
  193. anchor_insert: InsertAnchor,
  194. ) -> Result<()> {
  195. let mut context =
  196. RenderContext::new(tera, config, &self.permalink, permalinks, anchor_insert);
  197. context.tera_context.insert("page", &SerializingPage::from_page_basic(self, None));
  198. let res = render_content(&self.raw_content, &context)
  199. .chain_err(|| format!("Failed to render content of {}", self.file.path.display()))?;
  200. self.summary = res.summary_len.map(|l| res.body[0..l].to_owned());
  201. self.content = res.body;
  202. self.toc = res.toc;
  203. Ok(())
  204. }
  205. /// Renders the page using the default layout, unless specified in front-matter
  206. pub fn render_html(&self, tera: &Tera, config: &Config, library: &Library) -> Result<String> {
  207. let tpl_name = match self.meta.template {
  208. Some(ref l) => l,
  209. None => "page.html",
  210. };
  211. let mut context = TeraContext::new();
  212. context.insert("config", config);
  213. context.insert("current_url", &self.permalink);
  214. context.insert("current_path", &self.path);
  215. context.insert("page", &self.to_serialized(library));
  216. render_template(&tpl_name, tera, &context, &config.theme)
  217. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  218. }
  219. /// Creates a vectors of asset URLs.
  220. fn serialize_assets(&self) -> Vec<String> {
  221. self.assets
  222. .iter()
  223. .filter_map(|asset| asset.file_name())
  224. .filter_map(|filename| filename.to_str())
  225. .map(|filename| self.path.clone() + filename)
  226. .collect()
  227. }
  228. pub fn to_serialized<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  229. SerializingPage::from_page(self, library)
  230. }
  231. pub fn to_serialized_basic<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  232. SerializingPage::from_page_basic(self, Some(library))
  233. }
  234. }
  235. impl Default for Page {
  236. fn default() -> Page {
  237. Page {
  238. file: FileInfo::default(),
  239. meta: PageFrontMatter::default(),
  240. ancestors: vec![],
  241. raw_content: "".to_string(),
  242. assets: vec![],
  243. serialized_assets: vec![],
  244. content: "".to_string(),
  245. slug: "".to_string(),
  246. path: "".to_string(),
  247. components: vec![],
  248. permalink: "".to_string(),
  249. summary: None,
  250. earlier: None,
  251. later: None,
  252. lighter: None,
  253. heavier: None,
  254. toc: vec![],
  255. word_count: None,
  256. reading_time: None,
  257. }
  258. }
  259. }
  260. #[cfg(test)]
  261. mod tests {
  262. use std::collections::HashMap;
  263. use std::fs::{create_dir, File};
  264. use std::io::Write;
  265. use std::path::Path;
  266. use globset::{Glob, GlobSetBuilder};
  267. use tempfile::tempdir;
  268. use tera::Tera;
  269. use super::Page;
  270. use config::Config;
  271. use front_matter::InsertAnchor;
  272. #[test]
  273. fn test_can_parse_a_valid_page() {
  274. let content = r#"
  275. +++
  276. title = "Hello"
  277. description = "hey there"
  278. slug = "hello-world"
  279. +++
  280. Hello world"#;
  281. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  282. assert!(res.is_ok());
  283. let mut page = res.unwrap();
  284. page.render_markdown(
  285. &HashMap::default(),
  286. &Tera::default(),
  287. &Config::default(),
  288. InsertAnchor::None,
  289. )
  290. .unwrap();
  291. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  292. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  293. assert_eq!(page.raw_content, "Hello world".to_string());
  294. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  295. }
  296. #[test]
  297. fn test_can_make_url_from_sections_and_slug() {
  298. let content = r#"
  299. +++
  300. slug = "hello-world"
  301. +++
  302. Hello world"#;
  303. let mut conf = Config::default();
  304. conf.base_url = "http://hello.com/".to_string();
  305. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  306. assert!(res.is_ok());
  307. let page = res.unwrap();
  308. assert_eq!(page.path, "posts/intro/hello-world/");
  309. assert_eq!(page.components, vec!["posts", "intro", "hello-world"]);
  310. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  311. }
  312. #[test]
  313. fn can_make_url_from_slug_only() {
  314. let content = r#"
  315. +++
  316. slug = "hello-world"
  317. +++
  318. Hello world"#;
  319. let config = Config::default();
  320. let res = Page::parse(Path::new("start.md"), content, &config);
  321. assert!(res.is_ok());
  322. let page = res.unwrap();
  323. assert_eq!(page.path, "hello-world/");
  324. assert_eq!(page.components, vec!["hello-world"]);
  325. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  326. }
  327. #[test]
  328. fn can_make_url_from_path() {
  329. let content = r#"
  330. +++
  331. path = "hello-world"
  332. +++
  333. Hello world"#;
  334. let config = Config::default();
  335. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  336. assert!(res.is_ok());
  337. let page = res.unwrap();
  338. assert_eq!(page.path, "hello-world/");
  339. assert_eq!(page.components, vec!["hello-world"]);
  340. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  341. }
  342. #[test]
  343. fn can_make_url_from_path_starting_slash() {
  344. let content = r#"
  345. +++
  346. path = "/hello-world"
  347. +++
  348. Hello world"#;
  349. let config = Config::default();
  350. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  351. assert!(res.is_ok());
  352. let page = res.unwrap();
  353. assert_eq!(page.path, "hello-world/");
  354. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  355. }
  356. #[test]
  357. fn errors_on_invalid_front_matter_format() {
  358. // missing starting +++
  359. let content = r#"
  360. title = "Hello"
  361. description = "hey there"
  362. slug = "hello-world"
  363. +++
  364. Hello world"#;
  365. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  366. assert!(res.is_err());
  367. }
  368. #[test]
  369. fn can_make_slug_from_non_slug_filename() {
  370. let config = Config::default();
  371. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  372. assert!(res.is_ok());
  373. let page = res.unwrap();
  374. assert_eq!(page.slug, "file-with-space");
  375. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  376. }
  377. #[test]
  378. fn can_specify_summary() {
  379. let config = Config::default();
  380. let content = r#"
  381. +++
  382. +++
  383. Hello world
  384. <!-- more -->"#
  385. .to_string();
  386. let res = Page::parse(Path::new("hello.md"), &content, &config);
  387. assert!(res.is_ok());
  388. let mut page = res.unwrap();
  389. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None)
  390. .unwrap();
  391. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  392. }
  393. #[test]
  394. fn page_with_assets_gets_right_info() {
  395. let tmp_dir = tempdir().expect("create temp dir");
  396. let path = tmp_dir.path();
  397. create_dir(&path.join("content")).expect("create content temp dir");
  398. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  399. let nested_path = path.join("content").join("posts").join("with-assets");
  400. create_dir(&nested_path).expect("create nested temp dir");
  401. let mut f = File::create(nested_path.join("index.md")).unwrap();
  402. f.write_all(b"+++\n+++\n").unwrap();
  403. File::create(nested_path.join("example.js")).unwrap();
  404. File::create(nested_path.join("graph.jpg")).unwrap();
  405. File::create(nested_path.join("fail.png")).unwrap();
  406. let res = Page::from_file(nested_path.join("index.md").as_path(), &Config::default());
  407. assert!(res.is_ok());
  408. let page = res.unwrap();
  409. assert_eq!(page.file.parent, path.join("content").join("posts"));
  410. assert_eq!(page.slug, "with-assets");
  411. assert_eq!(page.assets.len(), 3);
  412. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  413. }
  414. #[test]
  415. fn page_with_assets_and_slug_overrides_path() {
  416. let tmp_dir = tempdir().expect("create temp dir");
  417. let path = tmp_dir.path();
  418. create_dir(&path.join("content")).expect("create content temp dir");
  419. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  420. let nested_path = path.join("content").join("posts").join("with-assets");
  421. create_dir(&nested_path).expect("create nested temp dir");
  422. let mut f = File::create(nested_path.join("index.md")).unwrap();
  423. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  424. File::create(nested_path.join("example.js")).unwrap();
  425. File::create(nested_path.join("graph.jpg")).unwrap();
  426. File::create(nested_path.join("fail.png")).unwrap();
  427. let res = Page::from_file(nested_path.join("index.md").as_path(), &Config::default());
  428. assert!(res.is_ok());
  429. let page = res.unwrap();
  430. assert_eq!(page.file.parent, path.join("content").join("posts"));
  431. assert_eq!(page.slug, "hey");
  432. assert_eq!(page.assets.len(), 3);
  433. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  434. }
  435. #[test]
  436. fn page_with_ignored_assets_filters_out_correct_files() {
  437. let tmp_dir = tempdir().expect("create temp dir");
  438. let path = tmp_dir.path();
  439. create_dir(&path.join("content")).expect("create content temp dir");
  440. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  441. let nested_path = path.join("content").join("posts").join("with-assets");
  442. create_dir(&nested_path).expect("create nested temp dir");
  443. let mut f = File::create(nested_path.join("index.md")).unwrap();
  444. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  445. File::create(nested_path.join("example.js")).unwrap();
  446. File::create(nested_path.join("graph.jpg")).unwrap();
  447. File::create(nested_path.join("fail.png")).unwrap();
  448. let mut gsb = GlobSetBuilder::new();
  449. gsb.add(Glob::new("*.{js,png}").unwrap());
  450. let mut config = Config::default();
  451. config.ignored_content_globset = Some(gsb.build().unwrap());
  452. let res = Page::from_file(nested_path.join("index.md").as_path(), &config);
  453. assert!(res.is_ok());
  454. let page = res.unwrap();
  455. assert_eq!(page.assets.len(), 1);
  456. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  457. }
  458. #[test]
  459. fn can_get_date_from_short_date_in_filename() {
  460. let config = Config::default();
  461. let content = r#"
  462. +++
  463. +++
  464. Hello world
  465. <!-- more -->"#
  466. .to_string();
  467. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config);
  468. assert!(res.is_ok());
  469. let page = res.unwrap();
  470. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  471. assert_eq!(page.slug, "hello");
  472. }
  473. #[test]
  474. fn can_get_date_from_full_rfc3339_date_in_filename() {
  475. let config = Config::default();
  476. let content = r#"
  477. +++
  478. +++
  479. Hello world
  480. <!-- more -->"#
  481. .to_string();
  482. let res = Page::parse(Path::new("2018-10-02T15:00:00Z-hello.md"), &content, &config);
  483. assert!(res.is_ok());
  484. let page = res.unwrap();
  485. assert_eq!(page.meta.date, Some("2018-10-02T15:00:00Z".to_string()));
  486. assert_eq!(page.slug, "hello");
  487. }
  488. #[test]
  489. fn frontmatter_date_override_filename_date() {
  490. let config = Config::default();
  491. let content = r#"
  492. +++
  493. date = 2018-09-09
  494. +++
  495. Hello world
  496. <!-- more -->"#
  497. .to_string();
  498. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config);
  499. assert!(res.is_ok());
  500. let page = res.unwrap();
  501. assert_eq!(page.meta.date, Some("2018-09-09".to_string()));
  502. assert_eq!(page.slug, "hello");
  503. }
  504. }