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.

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