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.

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