1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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)
        (?: ((?:ed2k|ftp|http|https|irc|mailto|news|gopher|nntp|telnet|webcal|xmpp|callto|feed|svn|urn|aim|rsync|tag|ssh|sftp|rtsp|afs|file):)// | www\. )
        [^\s<\x{00A0}\x{0022}]+
    ").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)
}

#[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>")
    }
}