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.

634 lines
22KB

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