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.

558 lines
19KB

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