autolink 0.3.0

HTML auto-linking
Documentation
extern crate regex;
use regex::Regex;

/// Wrap URLs in text with HTML A tags.
///
/// # Examples
///
/// ```
///   use autolink::auto_link;
///
///   let before = "Share code on https://crates.io";
///   let after = "Share code on <a href=\"https://crates.io\" target=\"_blank\">https://crates.io</a>";
///   assert!(auto_link(before, &vec!["target=\"_blank\""]) == after)
/// ```
pub fn auto_link(text: &str, attrs: &[&str]) -> String {
    if text.len() == 0 {
        return String::new();
    }

    let re = Regex::new(
        r"(?ix)
        \b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))
    ",
    )
    .unwrap();

    let attr_str = match attrs.len() {
        0 => "".to_string(),
        _ => " ".to_string() + &(attrs.join(" ")),
    };
    let replace_str = format!("<a href=\"$0\"{}>$0</a>", attr_str);

    re.replace_all(text, &replace_str as &str).to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_string() {
        assert!(auto_link("", &[]) == "")
    }

    #[test]
    fn test_string_without_urls() {
        let src = "<p>Some HTML</p>";
        assert!(auto_link(src, &[]) == src)
    }

    #[test]
    fn test_string_with_http_urls() {
        let src = "Check this out: https://doc.rust-lang.org/\n
               https://fr.wikipedia.org/wiki/Caf%C3%A9ine";
        let linked = "Check this out: <a href=\"https://doc.rust-lang.org/\">https://doc.rust-lang.org/</a>\n
               <a href=\"https://fr.wikipedia.org/wiki/Caf%C3%A9ine\">https://fr.wikipedia.org/wiki/Caf%C3%A9ine</a>";
        assert!(auto_link(src, &[]) == linked)
    }

    #[test]
    fn test_string_with_blank_target() {
        let src = "Check this out: https://doc.rust-lang.org/\n
               https://fr.wikipedia.org/wiki/Caf%C3%A9ine";
        let linked = "Check this out: <a href=\"https://doc.rust-lang.org/\" target=\"_blank\">https://doc.rust-lang.org/</a>\n
               <a href=\"https://fr.wikipedia.org/wiki/Caf%C3%A9ine\" target=\"_blank\">https://fr.wikipedia.org/wiki/Caf%C3%A9ine</a>";
        assert!(auto_link(src, &vec!["target=\"_blank\""]) == linked)
    }

    #[test]
    fn test_string_with_mailto_urls() {
        let src = "Send spam to mailto://oz@cypr.io";
        assert!(
            auto_link(src, &[])
                == "Send spam to <a href=\"mailto://oz@cypr.io\">mailto://oz@cypr.io</a>"
        )
    }

    #[test]
    fn test_string_with_trailing_chars() {
        let src = "I love https://cat-bounce.com!\n
            Have you seen https://en.wikipedia.org/wiki/Cat_(disambiguation)?";
        let linked = "I love <a href=\"https://cat-bounce.com\">https://cat-bounce.com</a>!\n
            Have you seen <a href=\"https://en.wikipedia.org/wiki/Cat_(disambiguation)\">https://en.wikipedia.org/wiki/Cat_(disambiguation)</a>?";
        assert!(auto_link(src, &[]) == linked)
    }
}