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.

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