Added support for links in RST files

+ Added rst_parser.rs for future RST parsing operations
+ Added tests for RST parsing
This commit is contained in:
2020-03-01 20:06:14 -06:00
parent fafad80e47
commit e88d9d3179
6 changed files with 62 additions and 6 deletions
+9 -3
View File
@@ -3,8 +3,11 @@
#[macro_use] extern crate rocket;
#[macro_use] extern crate serde_derive;
use std::collections::HashMap;
mod tests;
mod rst_parser;
use rst_parser::parse_links;
use std::collections::HashMap;
use rocket::Request;
use rocket_contrib::templates::Template;
use rocket_contrib::serve::StaticFiles;
@@ -30,7 +33,6 @@ impl error::Error for PageNotFoundError {
}
}
#[derive(Serialize)]
struct SiteFile {
file_name: String,
@@ -162,7 +164,7 @@ fn rst_page(page: PathBuf) -> Template {
else {
// Else, render the RST page
let mut map = HashMap::new();
let mut contents = match fs::read_to_string(site_page.path) {
let contents = match fs::read_to_string(site_page.path) {
Ok(contents) => contents,
Err(_) => {
let mut map = HashMap::new();
@@ -171,6 +173,9 @@ fn rst_page(page: PathBuf) -> Template {
},
};
// Render links
let mut contents = parse_links(&contents);
// Ensure render will look good
contents = contents.replace("\n", "<br>");
contents = contents.replace(" ", "&nbsp;&nbsp;");
@@ -182,6 +187,7 @@ fn rst_page(page: PathBuf) -> Template {
}
/// Catches 404 errors and displays an error message
///
/// #Arguments
+33
View File
@@ -0,0 +1,33 @@
use regex::Regex;
use std::collections::HashMap;
/// Renders RST links as HTML links
///
/// # Arguments
///
/// * `string` - input RST string
///
pub fn parse_links(string: & String) -> String {
let re_link_ref = Regex::new(r"\n?.. _(.*): (.*)\n").unwrap();
let mut link_map: HashMap::<String, String> = HashMap::new();
for cap in re_link_ref.captures_iter(string.as_str()) {
link_map.insert(String::from(&cap[1]), String::from(&cap[2]));
}
let mut output: String = re_link_ref.replace_all(string, "").to_string();
let re_link = Regex::new(r"`(.*)`_").unwrap();
for cap in re_link.captures_iter(output.clone().as_ref()) {
let link = match link_map.get(&cap[1]) {
None => String::from(""),
Some(link) => link.to_owned()
};
output = output.replace(&cap[0],
format!("<a class=\"link\" href=\"{}\">{}</a>",
link, &cap[1]).as_str());
}
output
}
+13
View File
@@ -0,0 +1,13 @@
#[cfg(test)]
use super::*;
#[test]
fn test_link_parser() {
let mut input = String::from("This is a paragraph that contains `a link`_.
.. _a link: https://domain.invalida\n");
let output = parse_links(&mut input);
assert_eq!(output.trim_end(), "This is a paragraph that contains <a class=\"link\" href=\"https://domain.invalida\">a link</a>.")
}