From 4f1f73fe563b9253adbca15df5da876c0dca74b5 Mon Sep 17 00:00:00 2001 From: Vincent Prouillet Date: Tue, 7 Mar 2017 12:42:14 +0900 Subject: [PATCH] Add summary --- src/page.rs | 59 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 53 insertions(+), 6 deletions(-) diff --git a/src/page.rs b/src/page.rs index e6c36785..52da0a72 100644 --- a/src/page.rs +++ b/src/page.rs @@ -19,6 +19,14 @@ use front_matter::{FrontMatter}; lazy_static! { static ref PAGE_RE: Regex = Regex::new(r"^\n?\+\+\+\n((?s).*(?-s))\+\+\+\n((?s).*(?-s))$").unwrap(); + static ref SUMMARY_RE: Regex = Regex::new(r"").unwrap(); +} + +fn markdown_to_html(content: &str) -> String { + let mut html = String::new(); + let parser = cmark::Parser::new(content); + cmark::html::push_html(&mut html, parser); + html } @@ -50,6 +58,10 @@ pub struct Page { pub url: String, /// The full URL for that page pub permalink: String, + /// The summary for the article, defaults to empty string + /// When is found in the text, will take the content up to that part + /// as summary + pub summary: String, /// The previous page, by date pub previous: Option>, @@ -69,6 +81,7 @@ impl Page { slug: "".to_string(), url: "".to_string(), permalink: "".to_string(), + summary: "".to_string(), meta: meta, previous: None, next: None, @@ -107,12 +120,16 @@ impl Page { let mut page = Page::new(meta); page.filepath = filepath.to_string(); page.raw_content = content.to_string(); - page.content = { - let mut html = String::new(); - let parser = cmark::Parser::new(&page.raw_content); - cmark::html::push_html(&mut html, parser); - html - }; + page.content = markdown_to_html(&page.raw_content); + + + if page.raw_content.contains("") { + page.summary = { + let summary = SUMMARY_RE.split(&page.raw_content).collect::>()[0]; + markdown_to_html(summary) + } + } + let path = Path::new(filepath); page.filename = path.file_stem().expect("Couldn't get filename").to_string_lossy().to_string(); page.slug = { @@ -398,4 +415,34 @@ Hello world"#.to_string(); assert_eq!(word_count, 2002); assert_eq!(reading_time, 10); } + + #[test] + fn test_automatic_summary_is_empty_string() { + let content = r#" ++++ +title = "Hello" +description = "hey there" ++++ +Hello world"#.to_string(); + let res = Page::parse("hello.md", &content, &Config::default()); + assert!(res.is_ok()); + let page = res.unwrap(); + assert_eq!(page.summary, ""); + } + + #[test] + fn test_can_specify_summary() { + let content = r#" ++++ +title = "Hello" +description = "hey there" ++++ +Hello world + +"#.to_string(); + let res = Page::parse("hello.md", &content, &Config::default()); + assert!(res.is_ok()); + let page = res.unwrap(); + assert_eq!(page.summary, "

Hello world

\n"); + } }