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.

629 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. render_template(&tpl_name, tera, &context, &config.theme)
  226. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  227. }
  228. /// Creates a vectors of asset URLs.
  229. fn serialize_assets(&self) -> Vec<String> {
  230. self.assets
  231. .iter()
  232. .filter_map(|asset| asset.file_name())
  233. .filter_map(|filename| filename.to_str())
  234. .map(|filename| self.path.clone() + filename)
  235. .collect()
  236. }
  237. pub fn to_serialized<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  238. SerializingPage::from_page(self, library)
  239. }
  240. pub fn to_serialized_basic<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  241. SerializingPage::from_page_basic(self, Some(library))
  242. }
  243. }
  244. impl Default for Page {
  245. fn default() -> Page {
  246. Page {
  247. file: FileInfo::default(),
  248. meta: PageFrontMatter::default(),
  249. ancestors: vec![],
  250. raw_content: "".to_string(),
  251. assets: vec![],
  252. serialized_assets: vec![],
  253. content: "".to_string(),
  254. slug: "".to_string(),
  255. path: "".to_string(),
  256. components: vec![],
  257. permalink: "".to_string(),
  258. summary: None,
  259. earlier: None,
  260. later: None,
  261. lighter: None,
  262. heavier: None,
  263. toc: vec![],
  264. word_count: None,
  265. reading_time: None,
  266. lang: None,
  267. }
  268. }
  269. }
  270. #[cfg(test)]
  271. mod tests {
  272. use std::collections::HashMap;
  273. use std::fs::{create_dir, File};
  274. use std::io::Write;
  275. use std::path::Path;
  276. use globset::{Glob, GlobSetBuilder};
  277. use tempfile::tempdir;
  278. use tera::Tera;
  279. use super::Page;
  280. use config::{Config, Language};
  281. use front_matter::InsertAnchor;
  282. #[test]
  283. fn test_can_parse_a_valid_page() {
  284. let content = r#"
  285. +++
  286. title = "Hello"
  287. description = "hey there"
  288. slug = "hello-world"
  289. +++
  290. Hello world"#;
  291. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  292. assert!(res.is_ok());
  293. let mut page = res.unwrap();
  294. page.render_markdown(
  295. &HashMap::default(),
  296. &Tera::default(),
  297. &Config::default(),
  298. InsertAnchor::None,
  299. )
  300. .unwrap();
  301. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  302. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  303. assert_eq!(page.raw_content, "Hello world".to_string());
  304. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  305. }
  306. #[test]
  307. fn test_can_make_url_from_sections_and_slug() {
  308. let content = r#"
  309. +++
  310. slug = "hello-world"
  311. +++
  312. Hello world"#;
  313. let mut conf = Config::default();
  314. conf.base_url = "http://hello.com/".to_string();
  315. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  316. assert!(res.is_ok());
  317. let page = res.unwrap();
  318. assert_eq!(page.path, "posts/intro/hello-world/");
  319. assert_eq!(page.components, vec!["posts", "intro", "hello-world"]);
  320. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  321. }
  322. #[test]
  323. fn can_make_url_from_slug_only() {
  324. let content = r#"
  325. +++
  326. slug = "hello-world"
  327. +++
  328. Hello world"#;
  329. let config = Config::default();
  330. let res = Page::parse(Path::new("start.md"), content, &config);
  331. assert!(res.is_ok());
  332. let page = res.unwrap();
  333. assert_eq!(page.path, "hello-world/");
  334. assert_eq!(page.components, vec!["hello-world"]);
  335. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  336. }
  337. #[test]
  338. fn can_make_url_from_path() {
  339. let content = r#"
  340. +++
  341. path = "hello-world"
  342. +++
  343. Hello world"#;
  344. let config = Config::default();
  345. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  346. assert!(res.is_ok());
  347. let page = res.unwrap();
  348. assert_eq!(page.path, "hello-world/");
  349. assert_eq!(page.components, vec!["hello-world"]);
  350. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  351. }
  352. #[test]
  353. fn can_make_url_from_path_starting_slash() {
  354. let content = r#"
  355. +++
  356. path = "/hello-world"
  357. +++
  358. Hello world"#;
  359. let config = Config::default();
  360. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  361. assert!(res.is_ok());
  362. let page = res.unwrap();
  363. assert_eq!(page.path, "hello-world/");
  364. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  365. }
  366. #[test]
  367. fn errors_on_invalid_front_matter_format() {
  368. // missing starting +++
  369. let content = r#"
  370. title = "Hello"
  371. description = "hey there"
  372. slug = "hello-world"
  373. +++
  374. Hello world"#;
  375. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  376. assert!(res.is_err());
  377. }
  378. #[test]
  379. fn can_make_slug_from_non_slug_filename() {
  380. let config = Config::default();
  381. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  382. assert!(res.is_ok());
  383. let page = res.unwrap();
  384. assert_eq!(page.slug, "file-with-space");
  385. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  386. }
  387. #[test]
  388. fn can_specify_summary() {
  389. let config = Config::default();
  390. let content = r#"
  391. +++
  392. +++
  393. Hello world
  394. <!-- more -->"#
  395. .to_string();
  396. let res = Page::parse(Path::new("hello.md"), &content, &config);
  397. assert!(res.is_ok());
  398. let mut page = res.unwrap();
  399. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None)
  400. .unwrap();
  401. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  402. }
  403. #[test]
  404. fn page_with_assets_gets_right_info() {
  405. let tmp_dir = tempdir().expect("create temp dir");
  406. let path = tmp_dir.path();
  407. create_dir(&path.join("content")).expect("create content temp dir");
  408. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  409. let nested_path = path.join("content").join("posts").join("with-assets");
  410. create_dir(&nested_path).expect("create nested temp dir");
  411. let mut f = File::create(nested_path.join("index.md")).unwrap();
  412. f.write_all(b"+++\n+++\n").unwrap();
  413. File::create(nested_path.join("example.js")).unwrap();
  414. File::create(nested_path.join("graph.jpg")).unwrap();
  415. File::create(nested_path.join("fail.png")).unwrap();
  416. let res = Page::from_file(nested_path.join("index.md").as_path(), &Config::default());
  417. assert!(res.is_ok());
  418. let page = res.unwrap();
  419. assert_eq!(page.file.parent, path.join("content").join("posts"));
  420. assert_eq!(page.slug, "with-assets");
  421. assert_eq!(page.assets.len(), 3);
  422. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  423. }
  424. #[test]
  425. fn page_with_assets_and_slug_overrides_path() {
  426. let tmp_dir = tempdir().expect("create temp dir");
  427. let path = tmp_dir.path();
  428. create_dir(&path.join("content")).expect("create content temp dir");
  429. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  430. let nested_path = path.join("content").join("posts").join("with-assets");
  431. create_dir(&nested_path).expect("create nested temp dir");
  432. let mut f = File::create(nested_path.join("index.md")).unwrap();
  433. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  434. File::create(nested_path.join("example.js")).unwrap();
  435. File::create(nested_path.join("graph.jpg")).unwrap();
  436. File::create(nested_path.join("fail.png")).unwrap();
  437. let res = Page::from_file(nested_path.join("index.md").as_path(), &Config::default());
  438. assert!(res.is_ok());
  439. let page = res.unwrap();
  440. assert_eq!(page.file.parent, path.join("content").join("posts"));
  441. assert_eq!(page.slug, "hey");
  442. assert_eq!(page.assets.len(), 3);
  443. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  444. }
  445. #[test]
  446. fn page_with_ignored_assets_filters_out_correct_files() {
  447. let tmp_dir = tempdir().expect("create temp dir");
  448. let path = tmp_dir.path();
  449. create_dir(&path.join("content")).expect("create content temp dir");
  450. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  451. let nested_path = path.join("content").join("posts").join("with-assets");
  452. create_dir(&nested_path).expect("create nested temp dir");
  453. let mut f = File::create(nested_path.join("index.md")).unwrap();
  454. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  455. File::create(nested_path.join("example.js")).unwrap();
  456. File::create(nested_path.join("graph.jpg")).unwrap();
  457. File::create(nested_path.join("fail.png")).unwrap();
  458. let mut gsb = GlobSetBuilder::new();
  459. gsb.add(Glob::new("*.{js,png}").unwrap());
  460. let mut config = Config::default();
  461. config.ignored_content_globset = Some(gsb.build().unwrap());
  462. let res = Page::from_file(nested_path.join("index.md").as_path(), &config);
  463. assert!(res.is_ok());
  464. let page = res.unwrap();
  465. assert_eq!(page.assets.len(), 1);
  466. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  467. }
  468. #[test]
  469. fn can_get_date_from_short_date_in_filename() {
  470. let config = Config::default();
  471. let content = r#"
  472. +++
  473. +++
  474. Hello world
  475. <!-- more -->"#
  476. .to_string();
  477. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config);
  478. assert!(res.is_ok());
  479. let page = res.unwrap();
  480. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  481. assert_eq!(page.slug, "hello");
  482. }
  483. #[test]
  484. fn can_get_date_from_full_rfc3339_date_in_filename() {
  485. let config = Config::default();
  486. let content = r#"
  487. +++
  488. +++
  489. Hello world
  490. <!-- more -->"#
  491. .to_string();
  492. let res = Page::parse(Path::new("2018-10-02T15:00:00Z-hello.md"), &content, &config);
  493. assert!(res.is_ok());
  494. let page = res.unwrap();
  495. assert_eq!(page.meta.date, Some("2018-10-02T15:00:00Z".to_string()));
  496. assert_eq!(page.slug, "hello");
  497. }
  498. #[test]
  499. fn frontmatter_date_override_filename_date() {
  500. let config = Config::default();
  501. let content = r#"
  502. +++
  503. date = 2018-09-09
  504. +++
  505. Hello world
  506. <!-- more -->"#
  507. .to_string();
  508. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config);
  509. assert!(res.is_ok());
  510. let page = res.unwrap();
  511. assert_eq!(page.meta.date, Some("2018-09-09".to_string()));
  512. assert_eq!(page.slug, "hello");
  513. }
  514. #[test]
  515. fn can_specify_language_in_filename() {
  516. let mut config = Config::default();
  517. config.languages.push(Language {code: String::from("fr"), rss: false});
  518. let content = r#"
  519. +++
  520. +++
  521. Bonjour le monde"#
  522. .to_string();
  523. let res = Page::parse(Path::new("hello.fr.md"), &content, &config);
  524. assert!(res.is_ok());
  525. let page = res.unwrap();
  526. assert_eq!(page.lang, Some("fr".to_string()));
  527. assert_eq!(page.slug, "hello");
  528. assert_eq!(page.permalink, "http://a-website.com/fr/hello/");
  529. }
  530. #[test]
  531. fn can_specify_language_in_filename_with_date() {
  532. let mut config = Config::default();
  533. config.languages.push(Language {code: String::from("fr"), rss: false});
  534. let content = r#"
  535. +++
  536. +++
  537. Bonjour le monde"#
  538. .to_string();
  539. let res = Page::parse(Path::new("2018-10-08_hello.fr.md"), &content, &config);
  540. assert!(res.is_ok());
  541. let page = res.unwrap();
  542. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  543. assert_eq!(page.lang, Some("fr".to_string()));
  544. assert_eq!(page.slug, "hello");
  545. assert_eq!(page.permalink, "http://a-website.com/fr/hello/");
  546. }
  547. #[test]
  548. fn i18n_frontmatter_path_overrides_default_permalink() {
  549. let mut config = Config::default();
  550. config.languages.push(Language {code: String::from("fr"), rss: false});
  551. let content = r#"
  552. +++
  553. path = "bonjour"
  554. +++
  555. Bonjour le monde"#
  556. .to_string();
  557. let res = Page::parse(Path::new("hello.fr.md"), &content, &config);
  558. assert!(res.is_ok());
  559. let page = res.unwrap();
  560. assert_eq!(page.lang, Some("fr".to_string()));
  561. assert_eq!(page.slug, "hello");
  562. assert_eq!(page.permalink, "http://a-website.com/bonjour/");
  563. }
  564. }