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.

603 lines
21KB

  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. /// The language of that page. `None` if the user doesn't setup `languages` in config.
  70. /// Corresponds to the lang in the {slug}.{lang}.md file scheme
  71. pub lang: Option<String>,
  72. }
  73. impl Page {
  74. pub fn new<P: AsRef<Path>>(file_path: P, meta: PageFrontMatter) -> Page {
  75. let file_path = file_path.as_ref();
  76. Page {
  77. file: FileInfo::new_page(file_path),
  78. meta,
  79. ancestors: vec![],
  80. raw_content: "".to_string(),
  81. assets: vec![],
  82. serialized_assets: vec![],
  83. content: "".to_string(),
  84. slug: "".to_string(),
  85. path: "".to_string(),
  86. components: vec![],
  87. permalink: "".to_string(),
  88. summary: None,
  89. earlier: None,
  90. later: None,
  91. lighter: None,
  92. heavier: None,
  93. toc: vec![],
  94. word_count: None,
  95. reading_time: None,
  96. lang: None,
  97. }
  98. }
  99. pub fn is_draft(&self) -> bool {
  100. self.meta.draft
  101. }
  102. /// Parse a page given the content of the .md file
  103. /// Files without front matter or with invalid front matter are considered
  104. /// erroneous
  105. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Page> {
  106. let (meta, content) = split_page_content(file_path, content)?;
  107. let mut page = Page::new(file_path, meta);
  108. page.lang = page.file.find_language(config)?;
  109. page.raw_content = content;
  110. let (word_count, reading_time) = get_reading_analytics(&page.raw_content);
  111. page.word_count = Some(word_count);
  112. page.reading_time = Some(reading_time);
  113. let mut slug_from_dated_filename = None;
  114. if let Some(ref caps) = RFC3339_DATE.captures(&page.file.name.replace(".md", "")) {
  115. slug_from_dated_filename = Some(caps.name("slug").unwrap().as_str().to_string());
  116. if page.meta.date.is_none() {
  117. page.meta.date = Some(caps.name("datetime").unwrap().as_str().to_string());
  118. page.meta.date_to_datetime();
  119. }
  120. }
  121. page.slug = {
  122. if let Some(ref slug) = page.meta.slug {
  123. slug.trim().to_string()
  124. } else if page.file.name == "index" {
  125. if let Some(parent) = page.file.path.parent() {
  126. slugify(parent.file_name().unwrap().to_str().unwrap())
  127. } else {
  128. slugify(&page.file.name)
  129. }
  130. } else {
  131. if let Some(slug) = slug_from_dated_filename {
  132. slugify(&slug)
  133. } else {
  134. slugify(&page.file.name)
  135. }
  136. }
  137. };
  138. if let Some(ref p) = page.meta.path {
  139. page.path = p.trim().trim_left_matches('/').to_string();
  140. } else {
  141. page.path = if page.file.components.is_empty() {
  142. page.slug.clone()
  143. } else {
  144. format!("{}/{}", page.file.components.join("/"), page.slug)
  145. };
  146. }
  147. if !page.path.ends_with('/') {
  148. page.path = format!("{}/", page.path);
  149. }
  150. page.components = page
  151. .path
  152. .split('/')
  153. .map(|p| p.to_string())
  154. .filter(|p| !p.is_empty())
  155. .collect::<Vec<_>>();
  156. page.permalink = config.make_permalink(&page.path);
  157. Ok(page)
  158. }
  159. /// Read and parse a .md file into a Page struct
  160. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Page> {
  161. let path = path.as_ref();
  162. let content = read_file(path)?;
  163. let mut page = Page::parse(path, &content, config)?;
  164. if page.file.name == "index" {
  165. let parent_dir = path.parent().unwrap();
  166. let assets = find_related_assets(parent_dir);
  167. if let Some(ref globset) = config.ignored_content_globset {
  168. // `find_related_assets` only scans the immediate directory (it is not recursive) so our
  169. // filtering only needs to work against the file_name component, not the full suffix. If
  170. // `find_related_assets` was changed to also return files in subdirectories, we could
  171. // use `PathBuf.strip_prefix` to remove the parent directory and then glob-filter
  172. // against the remaining path. Note that the current behaviour effectively means that
  173. // the `ignored_content` setting in the config file is limited to single-file glob
  174. // patterns (no "**" patterns).
  175. page.assets = assets
  176. .into_iter()
  177. .filter(|path| match path.file_name() {
  178. None => true,
  179. Some(file) => !globset.is_match(file),
  180. })
  181. .collect();
  182. } else {
  183. page.assets = assets;
  184. }
  185. page.serialized_assets = page.serialize_assets();
  186. } else {
  187. page.assets = vec![];
  188. }
  189. Ok(page)
  190. }
  191. /// We need access to all pages url to render links relative to content
  192. /// so that can't happen at the same time as parsing
  193. pub fn render_markdown(
  194. &mut self,
  195. permalinks: &HashMap<String, String>,
  196. tera: &Tera,
  197. config: &Config,
  198. anchor_insert: InsertAnchor,
  199. ) -> Result<()> {
  200. let mut context =
  201. RenderContext::new(tera, config, &self.permalink, permalinks, anchor_insert);
  202. context.tera_context.insert("page", &SerializingPage::from_page_basic(self, None));
  203. let res = render_content(&self.raw_content, &context)
  204. .chain_err(|| format!("Failed to render content of {}", self.file.path.display()))?;
  205. self.summary = res.summary_len.map(|l| res.body[0..l].to_owned());
  206. self.content = res.body;
  207. self.toc = res.toc;
  208. Ok(())
  209. }
  210. /// Renders the page using the default layout, unless specified in front-matter
  211. pub fn render_html(&self, tera: &Tera, config: &Config, library: &Library) -> Result<String> {
  212. let tpl_name = match self.meta.template {
  213. Some(ref l) => l,
  214. None => "page.html",
  215. };
  216. let mut context = TeraContext::new();
  217. context.insert("config", config);
  218. context.insert("current_url", &self.permalink);
  219. context.insert("current_path", &self.path);
  220. context.insert("page", &self.to_serialized(library));
  221. render_template(&tpl_name, tera, &context, &config.theme)
  222. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  223. }
  224. /// Creates a vectors of asset URLs.
  225. fn serialize_assets(&self) -> Vec<String> {
  226. self.assets
  227. .iter()
  228. .filter_map(|asset| asset.file_name())
  229. .filter_map(|filename| filename.to_str())
  230. .map(|filename| self.path.clone() + filename)
  231. .collect()
  232. }
  233. pub fn to_serialized<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  234. SerializingPage::from_page(self, library)
  235. }
  236. pub fn to_serialized_basic<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  237. SerializingPage::from_page_basic(self, Some(library))
  238. }
  239. }
  240. impl Default for Page {
  241. fn default() -> Page {
  242. Page {
  243. file: FileInfo::default(),
  244. meta: PageFrontMatter::default(),
  245. ancestors: vec![],
  246. raw_content: "".to_string(),
  247. assets: vec![],
  248. serialized_assets: vec![],
  249. content: "".to_string(),
  250. slug: "".to_string(),
  251. path: "".to_string(),
  252. components: vec![],
  253. permalink: "".to_string(),
  254. summary: None,
  255. earlier: None,
  256. later: None,
  257. lighter: None,
  258. heavier: None,
  259. toc: vec![],
  260. word_count: None,
  261. reading_time: None,
  262. lang: None,
  263. }
  264. }
  265. }
  266. #[cfg(test)]
  267. mod tests {
  268. use std::collections::HashMap;
  269. use std::fs::{create_dir, File};
  270. use std::io::Write;
  271. use std::path::Path;
  272. use globset::{Glob, GlobSetBuilder};
  273. use tempfile::tempdir;
  274. use tera::Tera;
  275. use super::Page;
  276. use config::{Config, Language};
  277. use front_matter::InsertAnchor;
  278. #[test]
  279. fn test_can_parse_a_valid_page() {
  280. let content = r#"
  281. +++
  282. title = "Hello"
  283. description = "hey there"
  284. slug = "hello-world"
  285. +++
  286. Hello world"#;
  287. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  288. assert!(res.is_ok());
  289. let mut page = res.unwrap();
  290. page.render_markdown(
  291. &HashMap::default(),
  292. &Tera::default(),
  293. &Config::default(),
  294. InsertAnchor::None,
  295. )
  296. .unwrap();
  297. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  298. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  299. assert_eq!(page.raw_content, "Hello world".to_string());
  300. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  301. }
  302. #[test]
  303. fn test_can_make_url_from_sections_and_slug() {
  304. let content = r#"
  305. +++
  306. slug = "hello-world"
  307. +++
  308. Hello world"#;
  309. let mut conf = Config::default();
  310. conf.base_url = "http://hello.com/".to_string();
  311. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  312. assert!(res.is_ok());
  313. let page = res.unwrap();
  314. assert_eq!(page.path, "posts/intro/hello-world/");
  315. assert_eq!(page.components, vec!["posts", "intro", "hello-world"]);
  316. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  317. }
  318. #[test]
  319. fn can_make_url_from_slug_only() {
  320. let content = r#"
  321. +++
  322. slug = "hello-world"
  323. +++
  324. Hello world"#;
  325. let config = Config::default();
  326. let res = Page::parse(Path::new("start.md"), content, &config);
  327. assert!(res.is_ok());
  328. let page = res.unwrap();
  329. assert_eq!(page.path, "hello-world/");
  330. assert_eq!(page.components, vec!["hello-world"]);
  331. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  332. }
  333. #[test]
  334. fn can_make_url_from_path() {
  335. let content = r#"
  336. +++
  337. path = "hello-world"
  338. +++
  339. Hello world"#;
  340. let config = Config::default();
  341. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  342. assert!(res.is_ok());
  343. let page = res.unwrap();
  344. assert_eq!(page.path, "hello-world/");
  345. assert_eq!(page.components, vec!["hello-world"]);
  346. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  347. }
  348. #[test]
  349. fn can_make_url_from_path_starting_slash() {
  350. let content = r#"
  351. +++
  352. path = "/hello-world"
  353. +++
  354. Hello world"#;
  355. let config = Config::default();
  356. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  357. assert!(res.is_ok());
  358. let page = res.unwrap();
  359. assert_eq!(page.path, "hello-world/");
  360. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  361. }
  362. #[test]
  363. fn errors_on_invalid_front_matter_format() {
  364. // missing starting +++
  365. let content = r#"
  366. title = "Hello"
  367. description = "hey there"
  368. slug = "hello-world"
  369. +++
  370. Hello world"#;
  371. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  372. assert!(res.is_err());
  373. }
  374. #[test]
  375. fn can_make_slug_from_non_slug_filename() {
  376. let config = Config::default();
  377. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  378. assert!(res.is_ok());
  379. let page = res.unwrap();
  380. assert_eq!(page.slug, "file-with-space");
  381. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  382. }
  383. #[test]
  384. fn can_specify_summary() {
  385. let config = Config::default();
  386. let content = r#"
  387. +++
  388. +++
  389. Hello world
  390. <!-- more -->"#
  391. .to_string();
  392. let res = Page::parse(Path::new("hello.md"), &content, &config);
  393. assert!(res.is_ok());
  394. let mut page = res.unwrap();
  395. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None)
  396. .unwrap();
  397. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  398. }
  399. #[test]
  400. fn page_with_assets_gets_right_info() {
  401. let tmp_dir = tempdir().expect("create temp dir");
  402. let path = tmp_dir.path();
  403. create_dir(&path.join("content")).expect("create content temp dir");
  404. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  405. let nested_path = path.join("content").join("posts").join("with-assets");
  406. create_dir(&nested_path).expect("create nested temp dir");
  407. let mut f = File::create(nested_path.join("index.md")).unwrap();
  408. f.write_all(b"+++\n+++\n").unwrap();
  409. File::create(nested_path.join("example.js")).unwrap();
  410. File::create(nested_path.join("graph.jpg")).unwrap();
  411. File::create(nested_path.join("fail.png")).unwrap();
  412. let res = Page::from_file(nested_path.join("index.md").as_path(), &Config::default());
  413. assert!(res.is_ok());
  414. let page = res.unwrap();
  415. assert_eq!(page.file.parent, path.join("content").join("posts"));
  416. assert_eq!(page.slug, "with-assets");
  417. assert_eq!(page.assets.len(), 3);
  418. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  419. }
  420. #[test]
  421. fn page_with_assets_and_slug_overrides_path() {
  422. let tmp_dir = tempdir().expect("create temp dir");
  423. let path = tmp_dir.path();
  424. create_dir(&path.join("content")).expect("create content temp dir");
  425. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  426. let nested_path = path.join("content").join("posts").join("with-assets");
  427. create_dir(&nested_path).expect("create nested temp dir");
  428. let mut f = File::create(nested_path.join("index.md")).unwrap();
  429. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  430. File::create(nested_path.join("example.js")).unwrap();
  431. File::create(nested_path.join("graph.jpg")).unwrap();
  432. File::create(nested_path.join("fail.png")).unwrap();
  433. let res = Page::from_file(nested_path.join("index.md").as_path(), &Config::default());
  434. assert!(res.is_ok());
  435. let page = res.unwrap();
  436. assert_eq!(page.file.parent, path.join("content").join("posts"));
  437. assert_eq!(page.slug, "hey");
  438. assert_eq!(page.assets.len(), 3);
  439. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  440. }
  441. #[test]
  442. fn page_with_ignored_assets_filters_out_correct_files() {
  443. let tmp_dir = tempdir().expect("create temp dir");
  444. let path = tmp_dir.path();
  445. create_dir(&path.join("content")).expect("create content temp dir");
  446. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  447. let nested_path = path.join("content").join("posts").join("with-assets");
  448. create_dir(&nested_path).expect("create nested temp dir");
  449. let mut f = File::create(nested_path.join("index.md")).unwrap();
  450. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  451. File::create(nested_path.join("example.js")).unwrap();
  452. File::create(nested_path.join("graph.jpg")).unwrap();
  453. File::create(nested_path.join("fail.png")).unwrap();
  454. let mut gsb = GlobSetBuilder::new();
  455. gsb.add(Glob::new("*.{js,png}").unwrap());
  456. let mut config = Config::default();
  457. config.ignored_content_globset = Some(gsb.build().unwrap());
  458. let res = Page::from_file(nested_path.join("index.md").as_path(), &config);
  459. assert!(res.is_ok());
  460. let page = res.unwrap();
  461. assert_eq!(page.assets.len(), 1);
  462. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  463. }
  464. #[test]
  465. fn can_get_date_from_short_date_in_filename() {
  466. let config = Config::default();
  467. let content = r#"
  468. +++
  469. +++
  470. Hello world
  471. <!-- more -->"#
  472. .to_string();
  473. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config);
  474. assert!(res.is_ok());
  475. let page = res.unwrap();
  476. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  477. assert_eq!(page.slug, "hello");
  478. }
  479. #[test]
  480. fn can_get_date_from_full_rfc3339_date_in_filename() {
  481. let config = Config::default();
  482. let content = r#"
  483. +++
  484. +++
  485. Hello world
  486. <!-- more -->"#
  487. .to_string();
  488. let res = Page::parse(Path::new("2018-10-02T15:00:00Z-hello.md"), &content, &config);
  489. assert!(res.is_ok());
  490. let page = res.unwrap();
  491. assert_eq!(page.meta.date, Some("2018-10-02T15:00:00Z".to_string()));
  492. assert_eq!(page.slug, "hello");
  493. }
  494. #[test]
  495. fn frontmatter_date_override_filename_date() {
  496. let config = Config::default();
  497. let content = r#"
  498. +++
  499. date = 2018-09-09
  500. +++
  501. Hello world
  502. <!-- more -->"#
  503. .to_string();
  504. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config);
  505. assert!(res.is_ok());
  506. let page = res.unwrap();
  507. assert_eq!(page.meta.date, Some("2018-09-09".to_string()));
  508. assert_eq!(page.slug, "hello");
  509. }
  510. #[test]
  511. fn can_specify_language_in_filename() {
  512. let mut config = Config::default();
  513. config.languages.push(Language {code: String::from("fr"), rss: false});
  514. let content = r#"
  515. +++
  516. +++
  517. Bonjour le monde"#
  518. .to_string();
  519. let res = Page::parse(Path::new("hello.fr.md"), &content, &config);
  520. assert!(res.is_ok());
  521. let page = res.unwrap();
  522. assert_eq!(page.lang, Some("fr".to_string()));
  523. assert_eq!(page.slug, "hello".to_string());
  524. }
  525. #[test]
  526. fn can_specify_language_in_filename_with_date() {
  527. let mut config = Config::default();
  528. config.languages.push(Language {code: String::from("fr"), rss: false});
  529. let content = r#"
  530. +++
  531. +++
  532. Bonjour le monde"#
  533. .to_string();
  534. let res = Page::parse(Path::new("2018-10-08_hello.fr.md"), &content, &config);
  535. assert!(res.is_ok());
  536. let page = res.unwrap();
  537. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  538. assert_eq!(page.lang, Some("fr".to_string()));
  539. assert_eq!(page.slug, "hello".to_string());
  540. }
  541. }