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.

471 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. // From a TOML datetime to a String first
  201. let date = match self.meta.date {
  202. Some(ref d) => Some(d.to_string()),
  203. None => None,
  204. };
  205. state.serialize_field("date", &date)?;
  206. state.serialize_field("slug", &self.slug)?;
  207. state.serialize_field("path", &self.path)?;
  208. state.serialize_field("components", &self.components)?;
  209. state.serialize_field("permalink", &self.permalink)?;
  210. state.serialize_field("summary", &self.summary)?;
  211. state.serialize_field("tags", &self.meta.tags)?;
  212. state.serialize_field("category", &self.meta.category)?;
  213. state.serialize_field("extra", &self.meta.extra)?;
  214. let (word_count, reading_time) = get_reading_analytics(&self.raw_content);
  215. state.serialize_field("word_count", &word_count)?;
  216. state.serialize_field("reading_time", &reading_time)?;
  217. state.serialize_field("previous", &self.previous)?;
  218. state.serialize_field("next", &self.next)?;
  219. state.serialize_field("toc", &self.toc)?;
  220. state.serialize_field("draft", &self.is_draft())?;
  221. state.end()
  222. }
  223. }
  224. #[cfg(test)]
  225. mod tests {
  226. use std::collections::HashMap;
  227. use std::io::Write;
  228. use std::fs::{File, create_dir};
  229. use std::path::Path;
  230. use tera::Tera;
  231. use tempdir::TempDir;
  232. use globset::{Glob, GlobSetBuilder};
  233. use config::Config;
  234. use super::Page;
  235. use front_matter::InsertAnchor;
  236. #[test]
  237. fn test_can_parse_a_valid_page() {
  238. let content = r#"
  239. +++
  240. title = "Hello"
  241. description = "hey there"
  242. slug = "hello-world"
  243. +++
  244. Hello world"#;
  245. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  246. assert!(res.is_ok());
  247. let mut page = res.unwrap();
  248. page.render_markdown(&HashMap::default(), &Tera::default(), &Config::default(), InsertAnchor::None).unwrap();
  249. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  250. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  251. assert_eq!(page.raw_content, "Hello world".to_string());
  252. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  253. }
  254. #[test]
  255. fn test_can_make_url_from_sections_and_slug() {
  256. let content = r#"
  257. +++
  258. slug = "hello-world"
  259. +++
  260. Hello world"#;
  261. let mut conf = Config::default();
  262. conf.base_url = "http://hello.com/".to_string();
  263. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  264. assert!(res.is_ok());
  265. let page = res.unwrap();
  266. assert_eq!(page.path, "posts/intro/hello-world/");
  267. assert_eq!(page.components, vec!["posts", "intro", "hello-world"]);
  268. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  269. }
  270. #[test]
  271. fn can_make_url_from_slug_only() {
  272. let content = r#"
  273. +++
  274. slug = "hello-world"
  275. +++
  276. Hello world"#;
  277. let config = Config::default();
  278. let res = Page::parse(Path::new("start.md"), content, &config);
  279. assert!(res.is_ok());
  280. let page = res.unwrap();
  281. assert_eq!(page.path, "hello-world/");
  282. assert_eq!(page.components, vec!["hello-world"]);
  283. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  284. }
  285. #[test]
  286. fn can_make_url_from_path() {
  287. let content = r#"
  288. +++
  289. path = "hello-world"
  290. +++
  291. Hello world"#;
  292. let config = Config::default();
  293. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  294. assert!(res.is_ok());
  295. let page = res.unwrap();
  296. assert_eq!(page.path, "hello-world/");
  297. assert_eq!(page.components, vec!["hello-world"]);
  298. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  299. }
  300. #[test]
  301. fn can_make_url_from_path_starting_slash() {
  302. let content = r#"
  303. +++
  304. path = "/hello-world"
  305. +++
  306. Hello world"#;
  307. let config = Config::default();
  308. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  309. assert!(res.is_ok());
  310. let page = res.unwrap();
  311. assert_eq!(page.path, "hello-world/");
  312. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  313. }
  314. #[test]
  315. fn errors_on_invalid_front_matter_format() {
  316. // missing starting +++
  317. let content = r#"
  318. title = "Hello"
  319. description = "hey there"
  320. slug = "hello-world"
  321. +++
  322. Hello world"#;
  323. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  324. assert!(res.is_err());
  325. }
  326. #[test]
  327. fn can_make_slug_from_non_slug_filename() {
  328. let config = Config::default();
  329. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  330. assert!(res.is_ok());
  331. let page = res.unwrap();
  332. assert_eq!(page.slug, "file-with-space");
  333. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  334. }
  335. #[test]
  336. fn can_specify_summary() {
  337. let config = Config::default();
  338. let content = r#"
  339. +++
  340. +++
  341. Hello world
  342. <!-- more -->"#.to_string();
  343. let res = Page::parse(Path::new("hello.md"), &content, &config);
  344. assert!(res.is_ok());
  345. let mut page = res.unwrap();
  346. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None).unwrap();
  347. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  348. }
  349. #[test]
  350. fn page_with_assets_gets_right_info() {
  351. let tmp_dir = TempDir::new("example").expect("create temp dir");
  352. let path = tmp_dir.path();
  353. create_dir(&path.join("content")).expect("create content temp dir");
  354. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  355. let nested_path = path.join("content").join("posts").join("with-assets");
  356. create_dir(&nested_path).expect("create nested temp dir");
  357. let mut f = File::create(nested_path.join("index.md")).unwrap();
  358. f.write_all(b"+++\n+++\n").unwrap();
  359. File::create(nested_path.join("example.js")).unwrap();
  360. File::create(nested_path.join("graph.jpg")).unwrap();
  361. File::create(nested_path.join("fail.png")).unwrap();
  362. let res = Page::from_file(
  363. nested_path.join("index.md").as_path(),
  364. &Config::default()
  365. );
  366. assert!(res.is_ok());
  367. let page = res.unwrap();
  368. assert_eq!(page.file.parent, path.join("content").join("posts"));
  369. assert_eq!(page.slug, "with-assets");
  370. assert_eq!(page.assets.len(), 3);
  371. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  372. }
  373. #[test]
  374. fn page_with_assets_and_slug_overrides_path() {
  375. let tmp_dir = TempDir::new("example").expect("create temp dir");
  376. let path = tmp_dir.path();
  377. create_dir(&path.join("content")).expect("create content temp dir");
  378. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  379. let nested_path = path.join("content").join("posts").join("with-assets");
  380. create_dir(&nested_path).expect("create nested temp dir");
  381. let mut f = File::create(nested_path.join("index.md")).unwrap();
  382. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  383. File::create(nested_path.join("example.js")).unwrap();
  384. File::create(nested_path.join("graph.jpg")).unwrap();
  385. File::create(nested_path.join("fail.png")).unwrap();
  386. let res = Page::from_file(
  387. nested_path.join("index.md").as_path(),
  388. &Config::default()
  389. );
  390. assert!(res.is_ok());
  391. let page = res.unwrap();
  392. assert_eq!(page.file.parent, path.join("content").join("posts"));
  393. assert_eq!(page.slug, "hey");
  394. assert_eq!(page.assets.len(), 3);
  395. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  396. }
  397. #[test]
  398. fn page_with_ignored_assets_filters_out_correct_files() {
  399. let tmp_dir = TempDir::new("example").expect("create temp dir");
  400. let path = tmp_dir.path();
  401. create_dir(&path.join("content")).expect("create content temp dir");
  402. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  403. let nested_path = path.join("content").join("posts").join("with-assets");
  404. create_dir(&nested_path).expect("create nested temp dir");
  405. let mut f = File::create(nested_path.join("index.md")).unwrap();
  406. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  407. File::create(nested_path.join("example.js")).unwrap();
  408. File::create(nested_path.join("graph.jpg")).unwrap();
  409. File::create(nested_path.join("fail.png")).unwrap();
  410. let mut gsb = GlobSetBuilder::new();
  411. gsb.add(Glob::new("*.{js,png}").unwrap());
  412. let mut config = Config::default();
  413. config.ignored_content_globber = Some(gsb.build().unwrap());
  414. let res = Page::from_file(
  415. nested_path.join("index.md").as_path(),
  416. &config
  417. );
  418. assert!(res.is_ok());
  419. let page = res.unwrap();
  420. assert_eq!(page.assets.len(), 1);
  421. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  422. }
  423. }