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.

472 lines
17KB

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