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.

466 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::{Context, Header, markdown_to_html};
  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.unwrap_or(false)
  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. // `find_related_assets` only scans the immediate directory (it is not recursive) so our
  118. // filtering only needs to work against the file_name component, not the full suffix. If
  119. // `find_related_assets` was changed to also return files in subdirectories, we could
  120. // use `PathBuf.strip_prefix` to remove the parent directory and then glob-filter
  121. // against the remaining path. Note that the current behaviour effectively means that
  122. // the `ignored_content` setting in the config file is limited to single-file glob
  123. // patterns (no "**" patterns).
  124. let globber = config.ignored_content_globber.as_ref().unwrap();
  125. let parent_dir = path.parent().unwrap();
  126. page.assets = find_related_assets(parent_dir).into_iter()
  127. .filter(|path|
  128. match path.file_name() {
  129. None => true,
  130. Some(file) => !globber.is_match(file)
  131. }
  132. ).collect();
  133. } else {
  134. page.assets = vec![];
  135. }
  136. Ok(page)
  137. }
  138. /// We need access to all pages url to render links relative to content
  139. /// so that can't happen at the same time as parsing
  140. pub fn render_markdown(&mut self, permalinks: &HashMap<String, String>, tera: &Tera, config: &Config, anchor_insert: InsertAnchor) -> Result<()> {
  141. let context = Context::new(
  142. tera,
  143. config.highlight_code.unwrap(),
  144. config.highlight_theme.clone().unwrap(),
  145. &self.permalink,
  146. permalinks,
  147. anchor_insert
  148. );
  149. let res = markdown_to_html(&self.raw_content, &context)?;
  150. self.content = res.0;
  151. self.toc = res.1;
  152. if self.raw_content.contains("<!-- more -->") {
  153. self.summary = Some({
  154. let summary = self.raw_content.splitn(2, "<!-- more -->").collect::<Vec<&str>>()[0];
  155. markdown_to_html(summary, &context)?.0
  156. })
  157. }
  158. Ok(())
  159. }
  160. /// Renders the page using the default layout, unless specified in front-matter
  161. pub fn render_html(&self, tera: &Tera, config: &Config) -> Result<String> {
  162. let tpl_name = match self.meta.template {
  163. Some(ref l) => l.to_string(),
  164. None => "page.html".to_string()
  165. };
  166. let mut context = TeraContext::new();
  167. context.add("config", config);
  168. context.add("page", self);
  169. context.add("current_url", &self.permalink);
  170. context.add("current_path", &self.path);
  171. render_template(&tpl_name, tera, &context, config.theme.clone())
  172. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  173. }
  174. }
  175. impl Default for Page {
  176. fn default() -> Page {
  177. Page {
  178. file: FileInfo::default(),
  179. meta: PageFrontMatter::default(),
  180. raw_content: "".to_string(),
  181. assets: vec![],
  182. content: "".to_string(),
  183. slug: "".to_string(),
  184. path: "".to_string(),
  185. components: vec![],
  186. permalink: "".to_string(),
  187. summary: None,
  188. previous: None,
  189. next: None,
  190. toc: vec![],
  191. }
  192. }
  193. }
  194. impl ser::Serialize for Page {
  195. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  196. let mut state = serializer.serialize_struct("page", 18)?;
  197. state.serialize_field("content", &self.content)?;
  198. state.serialize_field("title", &self.meta.title)?;
  199. state.serialize_field("description", &self.meta.description)?;
  200. state.serialize_field("date", &self.meta.date)?;
  201. state.serialize_field("slug", &self.slug)?;
  202. state.serialize_field("path", &self.path)?;
  203. state.serialize_field("components", &self.components)?;
  204. state.serialize_field("permalink", &self.permalink)?;
  205. state.serialize_field("summary", &self.summary)?;
  206. state.serialize_field("tags", &self.meta.tags)?;
  207. state.serialize_field("category", &self.meta.category)?;
  208. state.serialize_field("extra", &self.meta.extra)?;
  209. let (word_count, reading_time) = get_reading_analytics(&self.raw_content);
  210. state.serialize_field("word_count", &word_count)?;
  211. state.serialize_field("reading_time", &reading_time)?;
  212. state.serialize_field("previous", &self.previous)?;
  213. state.serialize_field("next", &self.next)?;
  214. state.serialize_field("toc", &self.toc)?;
  215. state.serialize_field("draft", &self.is_draft())?;
  216. state.end()
  217. }
  218. }
  219. #[cfg(test)]
  220. mod tests {
  221. use std::collections::HashMap;
  222. use std::io::Write;
  223. use std::fs::{File, create_dir};
  224. use std::path::Path;
  225. use tera::Tera;
  226. use tempdir::TempDir;
  227. use globset::{Glob, GlobSetBuilder};
  228. use config::Config;
  229. use super::Page;
  230. use front_matter::InsertAnchor;
  231. #[test]
  232. fn test_can_parse_a_valid_page() {
  233. let content = r#"
  234. +++
  235. title = "Hello"
  236. description = "hey there"
  237. slug = "hello-world"
  238. +++
  239. Hello world"#;
  240. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  241. assert!(res.is_ok());
  242. let mut page = res.unwrap();
  243. page.render_markdown(&HashMap::default(), &Tera::default(), &Config::default(), InsertAnchor::None).unwrap();
  244. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  245. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  246. assert_eq!(page.raw_content, "Hello world".to_string());
  247. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  248. }
  249. #[test]
  250. fn test_can_make_url_from_sections_and_slug() {
  251. let content = r#"
  252. +++
  253. slug = "hello-world"
  254. +++
  255. Hello world"#;
  256. let mut conf = Config::default();
  257. conf.base_url = "http://hello.com/".to_string();
  258. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  259. assert!(res.is_ok());
  260. let page = res.unwrap();
  261. assert_eq!(page.path, "posts/intro/hello-world/");
  262. assert_eq!(page.components, vec!["posts", "intro", "hello-world"]);
  263. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  264. }
  265. #[test]
  266. fn can_make_url_from_slug_only() {
  267. let content = r#"
  268. +++
  269. slug = "hello-world"
  270. +++
  271. Hello world"#;
  272. let config = Config::default();
  273. let res = Page::parse(Path::new("start.md"), content, &config);
  274. assert!(res.is_ok());
  275. let page = res.unwrap();
  276. assert_eq!(page.path, "hello-world/");
  277. assert_eq!(page.components, vec!["hello-world"]);
  278. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  279. }
  280. #[test]
  281. fn can_make_url_from_path() {
  282. let content = r#"
  283. +++
  284. path = "hello-world"
  285. +++
  286. Hello world"#;
  287. let config = Config::default();
  288. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  289. assert!(res.is_ok());
  290. let page = res.unwrap();
  291. assert_eq!(page.path, "hello-world/");
  292. assert_eq!(page.components, vec!["hello-world"]);
  293. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  294. }
  295. #[test]
  296. fn can_make_url_from_path_starting_slash() {
  297. let content = r#"
  298. +++
  299. path = "/hello-world"
  300. +++
  301. Hello world"#;
  302. let config = Config::default();
  303. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  304. assert!(res.is_ok());
  305. let page = res.unwrap();
  306. assert_eq!(page.path, "hello-world/");
  307. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  308. }
  309. #[test]
  310. fn errors_on_invalid_front_matter_format() {
  311. // missing starting +++
  312. let content = r#"
  313. title = "Hello"
  314. description = "hey there"
  315. slug = "hello-world"
  316. +++
  317. Hello world"#;
  318. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  319. assert!(res.is_err());
  320. }
  321. #[test]
  322. fn can_make_slug_from_non_slug_filename() {
  323. let config = Config::default();
  324. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  325. assert!(res.is_ok());
  326. let page = res.unwrap();
  327. assert_eq!(page.slug, "file-with-space");
  328. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  329. }
  330. #[test]
  331. fn can_specify_summary() {
  332. let config = Config::default();
  333. let content = r#"
  334. +++
  335. +++
  336. Hello world
  337. <!-- more -->"#.to_string();
  338. let res = Page::parse(Path::new("hello.md"), &content, &config);
  339. assert!(res.is_ok());
  340. let mut page = res.unwrap();
  341. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None).unwrap();
  342. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  343. }
  344. #[test]
  345. fn page_with_assets_gets_right_info() {
  346. let tmp_dir = TempDir::new("example").expect("create temp dir");
  347. let path = tmp_dir.path();
  348. create_dir(&path.join("content")).expect("create content temp dir");
  349. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  350. let nested_path = path.join("content").join("posts").join("with-assets");
  351. create_dir(&nested_path).expect("create nested temp dir");
  352. let mut f = File::create(nested_path.join("index.md")).unwrap();
  353. f.write_all(b"+++\n+++\n").unwrap();
  354. File::create(nested_path.join("example.js")).unwrap();
  355. File::create(nested_path.join("graph.jpg")).unwrap();
  356. File::create(nested_path.join("fail.png")).unwrap();
  357. let res = Page::from_file(
  358. nested_path.join("index.md").as_path(),
  359. &Config::default()
  360. );
  361. assert!(res.is_ok());
  362. let page = res.unwrap();
  363. assert_eq!(page.file.parent, path.join("content").join("posts"));
  364. assert_eq!(page.slug, "with-assets");
  365. assert_eq!(page.assets.len(), 3);
  366. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  367. }
  368. #[test]
  369. fn page_with_assets_and_slug_overrides_path() {
  370. let tmp_dir = TempDir::new("example").expect("create temp dir");
  371. let path = tmp_dir.path();
  372. create_dir(&path.join("content")).expect("create content temp dir");
  373. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  374. let nested_path = path.join("content").join("posts").join("with-assets");
  375. create_dir(&nested_path).expect("create nested temp dir");
  376. let mut f = File::create(nested_path.join("index.md")).unwrap();
  377. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  378. File::create(nested_path.join("example.js")).unwrap();
  379. File::create(nested_path.join("graph.jpg")).unwrap();
  380. File::create(nested_path.join("fail.png")).unwrap();
  381. let res = Page::from_file(
  382. nested_path.join("index.md").as_path(),
  383. &Config::default()
  384. );
  385. assert!(res.is_ok());
  386. let page = res.unwrap();
  387. assert_eq!(page.file.parent, path.join("content").join("posts"));
  388. assert_eq!(page.slug, "hey");
  389. assert_eq!(page.assets.len(), 3);
  390. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  391. }
  392. #[test]
  393. fn page_with_ignored_assets_filters_out_correct_files() {
  394. let tmp_dir = TempDir::new("example").expect("create temp dir");
  395. let path = tmp_dir.path();
  396. create_dir(&path.join("content")).expect("create content temp dir");
  397. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  398. let nested_path = path.join("content").join("posts").join("with-assets");
  399. create_dir(&nested_path).expect("create nested temp dir");
  400. let mut f = File::create(nested_path.join("index.md")).unwrap();
  401. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  402. File::create(nested_path.join("example.js")).unwrap();
  403. File::create(nested_path.join("graph.jpg")).unwrap();
  404. File::create(nested_path.join("fail.png")).unwrap();
  405. let mut gsb = GlobSetBuilder::new();
  406. gsb.add(Glob::new("*.{js,png}").unwrap());
  407. let mut config = Config::default();
  408. config.ignored_content_globber = Some(gsb.build().unwrap());
  409. let res = Page::from_file(
  410. nested_path.join("index.md").as_path(),
  411. &config
  412. );
  413. assert!(res.is_ok());
  414. let page = res.unwrap();
  415. assert_eq!(page.assets.len(), 1);
  416. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  417. }
  418. }