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.

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