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.

page.rs 15KB

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