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.

544 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 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. // 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. page.meta.date_to_datetime();
  111. }
  112. }
  113. page.slug = {
  114. if let Some(ref slug) = page.meta.slug {
  115. slug.trim().to_string()
  116. } else if page.file.name == "index" {
  117. if let Some(parent) = page.file.path.parent() {
  118. slugify(parent.file_name().unwrap().to_str().unwrap())
  119. } else {
  120. slugify(&page.file.name)
  121. }
  122. } else {
  123. if has_date_in_name {
  124. // skip the date + the {_,-}
  125. slugify(&page.file.name[11..])
  126. } else {
  127. slugify(&page.file.name)
  128. }
  129. }
  130. };
  131. if let Some(ref p) = page.meta.path {
  132. page.path = p.trim().trim_left_matches('/').to_string();
  133. } else {
  134. page.path = if page.file.components.is_empty() {
  135. page.slug.clone()
  136. } else {
  137. format!("{}/{}", page.file.components.join("/"), page.slug)
  138. };
  139. }
  140. if !page.path.ends_with('/') {
  141. page.path = format!("{}/", page.path);
  142. }
  143. page.components = page
  144. .path
  145. .split('/')
  146. .map(|p| p.to_string())
  147. .filter(|p| !p.is_empty())
  148. .collect::<Vec<_>>();
  149. page.permalink = config.make_permalink(&page.path);
  150. Ok(page)
  151. }
  152. /// Read and parse a .md file into a Page struct
  153. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Page> {
  154. let path = path.as_ref();
  155. let content = read_file(path)?;
  156. let mut page = Page::parse(path, &content, config)?;
  157. if page.file.name == "index" {
  158. let parent_dir = path.parent().unwrap();
  159. let assets = find_related_assets(parent_dir);
  160. if let Some(ref globset) = config.ignored_content_globset {
  161. // `find_related_assets` only scans the immediate directory (it is not recursive) so our
  162. // filtering only needs to work against the file_name component, not the full suffix. If
  163. // `find_related_assets` was changed to also return files in subdirectories, we could
  164. // use `PathBuf.strip_prefix` to remove the parent directory and then glob-filter
  165. // against the remaining path. Note that the current behaviour effectively means that
  166. // the `ignored_content` setting in the config file is limited to single-file glob
  167. // patterns (no "**" patterns).
  168. page.assets = assets
  169. .into_iter()
  170. .filter(|path| match path.file_name() {
  171. None => true,
  172. Some(file) => !globset.is_match(file),
  173. })
  174. .collect();
  175. } else {
  176. page.assets = assets;
  177. }
  178. page.serialized_assets = page.serialize_assets();
  179. } else {
  180. page.assets = vec![];
  181. }
  182. Ok(page)
  183. }
  184. /// We need access to all pages url to render links relative to content
  185. /// so that can't happen at the same time as parsing
  186. pub fn render_markdown(
  187. &mut self,
  188. permalinks: &HashMap<String, String>,
  189. tera: &Tera,
  190. config: &Config,
  191. anchor_insert: InsertAnchor,
  192. ) -> Result<()> {
  193. let mut context =
  194. RenderContext::new(tera, config, &self.permalink, permalinks, anchor_insert);
  195. context.tera_context.insert("page", &SerializingPage::from_page_basic(self, None));
  196. let res = render_content(&self.raw_content, &context)
  197. .chain_err(|| format!("Failed to render content of {}", self.file.path.display()))?;
  198. self.summary = res.summary_len.map(|l| res.body[0..l].to_owned());
  199. self.content = res.body;
  200. self.toc = res.toc;
  201. Ok(())
  202. }
  203. /// Renders the page using the default layout, unless specified in front-matter
  204. pub fn render_html(&self, tera: &Tera, config: &Config, library: &Library) -> Result<String> {
  205. let tpl_name = match self.meta.template {
  206. Some(ref l) => l,
  207. None => "page.html",
  208. };
  209. let mut context = TeraContext::new();
  210. context.insert("config", config);
  211. context.insert("current_url", &self.permalink);
  212. context.insert("current_path", &self.path);
  213. context.insert("page", &self.to_serialized(library));
  214. render_template(&tpl_name, tera, &context, &config.theme)
  215. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  216. }
  217. /// Creates a vectors of asset URLs.
  218. fn serialize_assets(&self) -> Vec<String> {
  219. self.assets
  220. .iter()
  221. .filter_map(|asset| asset.file_name())
  222. .filter_map(|filename| filename.to_str())
  223. .map(|filename| self.path.clone() + filename)
  224. .collect()
  225. }
  226. pub fn to_serialized<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  227. SerializingPage::from_page(self, library)
  228. }
  229. pub fn to_serialized_basic<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  230. SerializingPage::from_page_basic(self, Some(library))
  231. }
  232. }
  233. impl Default for Page {
  234. fn default() -> Page {
  235. Page {
  236. file: FileInfo::default(),
  237. meta: PageFrontMatter::default(),
  238. ancestors: vec![],
  239. raw_content: "".to_string(),
  240. assets: vec![],
  241. serialized_assets: vec![],
  242. content: "".to_string(),
  243. slug: "".to_string(),
  244. path: "".to_string(),
  245. components: vec![],
  246. permalink: "".to_string(),
  247. summary: None,
  248. earlier: None,
  249. later: None,
  250. lighter: None,
  251. heavier: None,
  252. toc: vec![],
  253. word_count: None,
  254. reading_time: None,
  255. }
  256. }
  257. }
  258. #[cfg(test)]
  259. mod tests {
  260. use std::collections::HashMap;
  261. use std::fs::{create_dir, File};
  262. use std::io::Write;
  263. use std::path::Path;
  264. use globset::{Glob, GlobSetBuilder};
  265. use tempfile::tempdir;
  266. use tera::Tera;
  267. use super::Page;
  268. use config::Config;
  269. use front_matter::InsertAnchor;
  270. #[test]
  271. fn test_can_parse_a_valid_page() {
  272. let content = r#"
  273. +++
  274. title = "Hello"
  275. description = "hey there"
  276. slug = "hello-world"
  277. +++
  278. Hello world"#;
  279. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  280. assert!(res.is_ok());
  281. let mut page = res.unwrap();
  282. page.render_markdown(
  283. &HashMap::default(),
  284. &Tera::default(),
  285. &Config::default(),
  286. InsertAnchor::None,
  287. )
  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 -->"#
  383. .to_string();
  384. let res = Page::parse(Path::new("hello.md"), &content, &config);
  385. assert!(res.is_ok());
  386. let mut page = res.unwrap();
  387. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None)
  388. .unwrap();
  389. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  390. }
  391. #[test]
  392. fn page_with_assets_gets_right_info() {
  393. let tmp_dir = tempdir().expect("create temp dir");
  394. let path = tmp_dir.path();
  395. create_dir(&path.join("content")).expect("create content temp dir");
  396. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  397. let nested_path = path.join("content").join("posts").join("with-assets");
  398. create_dir(&nested_path).expect("create nested temp dir");
  399. let mut f = File::create(nested_path.join("index.md")).unwrap();
  400. f.write_all(b"+++\n+++\n").unwrap();
  401. File::create(nested_path.join("example.js")).unwrap();
  402. File::create(nested_path.join("graph.jpg")).unwrap();
  403. File::create(nested_path.join("fail.png")).unwrap();
  404. let res = Page::from_file(nested_path.join("index.md").as_path(), &Config::default());
  405. assert!(res.is_ok());
  406. let page = res.unwrap();
  407. assert_eq!(page.file.parent, path.join("content").join("posts"));
  408. assert_eq!(page.slug, "with-assets");
  409. assert_eq!(page.assets.len(), 3);
  410. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  411. }
  412. #[test]
  413. fn page_with_assets_and_slug_overrides_path() {
  414. let tmp_dir = tempdir().expect("create temp dir");
  415. let path = tmp_dir.path();
  416. create_dir(&path.join("content")).expect("create content temp dir");
  417. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  418. let nested_path = path.join("content").join("posts").join("with-assets");
  419. create_dir(&nested_path).expect("create nested temp dir");
  420. let mut f = File::create(nested_path.join("index.md")).unwrap();
  421. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  422. File::create(nested_path.join("example.js")).unwrap();
  423. File::create(nested_path.join("graph.jpg")).unwrap();
  424. File::create(nested_path.join("fail.png")).unwrap();
  425. let res = Page::from_file(nested_path.join("index.md").as_path(), &Config::default());
  426. assert!(res.is_ok());
  427. let page = res.unwrap();
  428. assert_eq!(page.file.parent, path.join("content").join("posts"));
  429. assert_eq!(page.slug, "hey");
  430. assert_eq!(page.assets.len(), 3);
  431. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  432. }
  433. #[test]
  434. fn page_with_ignored_assets_filters_out_correct_files() {
  435. let tmp_dir = tempdir().expect("create temp dir");
  436. let path = tmp_dir.path();
  437. create_dir(&path.join("content")).expect("create content temp dir");
  438. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  439. let nested_path = path.join("content").join("posts").join("with-assets");
  440. create_dir(&nested_path).expect("create nested temp dir");
  441. let mut f = File::create(nested_path.join("index.md")).unwrap();
  442. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  443. File::create(nested_path.join("example.js")).unwrap();
  444. File::create(nested_path.join("graph.jpg")).unwrap();
  445. File::create(nested_path.join("fail.png")).unwrap();
  446. let mut gsb = GlobSetBuilder::new();
  447. gsb.add(Glob::new("*.{js,png}").unwrap());
  448. let mut config = Config::default();
  449. config.ignored_content_globset = Some(gsb.build().unwrap());
  450. let res = Page::from_file(nested_path.join("index.md").as_path(), &config);
  451. assert!(res.is_ok());
  452. let page = res.unwrap();
  453. assert_eq!(page.assets.len(), 1);
  454. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  455. }
  456. #[test]
  457. fn can_get_date_from_filename() {
  458. let config = Config::default();
  459. let content = r#"
  460. +++
  461. +++
  462. Hello world
  463. <!-- more -->"#
  464. .to_string();
  465. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config);
  466. assert!(res.is_ok());
  467. let page = res.unwrap();
  468. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  469. assert_eq!(page.slug, "hello");
  470. }
  471. #[test]
  472. fn frontmatter_date_override_filename_date() {
  473. let config = Config::default();
  474. let content = r#"
  475. +++
  476. date = 2018-09-09
  477. +++
  478. Hello world
  479. <!-- more -->"#
  480. .to_string();
  481. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config);
  482. assert!(res.is_ok());
  483. let page = res.unwrap();
  484. assert_eq!(page.meta.date, Some("2018-09-09".to_string()));
  485. assert_eq!(page.slug, "hello");
  486. }
  487. }