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.

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