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
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
//!# URLTemplate
//! Utility that enables URLs with placeholders, i.e. `https://www.mozilla.org/?utm_source={source}&utm_medium={medium}
//!# Usage
//! ```
//! extern crate urltemplate;
//!
//! use urltemplate::UrlTemplate;
//! use std::collections::HashMap;
//!
//! let mut params = HashMap::new();
//! params.insert("source".to_string(), "url-template-crate-❤".to_string());
//! let url_with_placeholders = UrlTemplate::from("https://www.mozilla.org/?utm_source={source}");
//! let url =  url_with_placeholders.substitute_str(&params).expect("valid url");
//! assert_eq!(url, "https://www.mozilla.org/?utm_source=url-template-crate-❤")
//! ```
use url::Url;

use std::fmt;

use std::collections::{HashMap};
use std::error::{self, Error};

use std::ops::Add;



#[derive(Debug, Clone)]
pub struct UrlTemplate(pub String);


#[derive(Debug)]
#[derive(PartialEq)]
pub enum UrlTemplateErrorKind {
    /// provided String is not an URL
    IsNotAnUrl,
    /// provided URL scheme is differ from expected `http` or `https`
    InvalidScheme,
    /// provided pattern has incorrect syntax
    InvalidPattern
}


#[derive(Debug)]
#[derive(PartialEq)]
pub struct UrlTemplateError {
    position: usize,
    kind: UrlTemplateErrorKind
}

impl From<(UrlTemplateErrorKind, usize)> for UrlTemplateError {
    fn from((kind, position): (UrlTemplateErrorKind, usize)) -> UrlTemplateError {
        UrlTemplateError {
            kind: kind,
            position: position
        }
    }
}

impl From<UrlTemplateErrorKind> for UrlTemplateError {
    fn from(kind: UrlTemplateErrorKind) -> UrlTemplateError {
        UrlTemplateError {
            kind: kind,
            position: 0
        }
    }
}

impl fmt::Display for UrlTemplateError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.kind {
            UrlTemplateErrorKind::IsNotAnUrl => {
                write!(f, "Provided pattern is not a valid URL.")
            }
            UrlTemplateErrorKind::InvalidScheme => {
                write!(f, "URL scheme is differ from expected `http` or `https`.")
            }
            UrlTemplateErrorKind::InvalidPattern => {
                write!(f, "The pattern has invalid syntax.")
            }
        }
    }
}

impl error::Error for UrlTemplateError {
    fn cause(&self) -> Option<&Error> { None }
    fn source(&self) -> Option<&(Error + 'static)> { None }
}


impl From<String> for UrlTemplate {
    fn from(s: String) -> UrlTemplate {
        UrlTemplate(s)
    }
}

impl From<&str> for UrlTemplate {
    fn from(s: &str) -> UrlTemplate {
        UrlTemplate(String::from(s))
    }
}

impl Into<String> for UrlTemplate {
    fn into(self) -> String {
        self.0.clone()
    }
}

impl PartialEq for UrlTemplate {
    fn eq(&self, other: &UrlTemplate) -> bool {
        let s: String = other.into();
        self.0 == s
    }
}

impl ToString for UrlTemplate {
    fn to_string(&self) -> String {
        self.0.clone()
    }
}

impl From<&UrlTemplate> for String {
    fn from(tpl: &UrlTemplate) -> String { tpl.to_string() }
}

impl UrlTemplate {
    pub fn substitute(&self, values: &HashMap<String, String>) -> Result<Url, UrlTemplateError> {
        match self.substitute_str(values) {
            Ok(url_string) => {
                Ok(Url::parse(url_string.as_str()).expect("Valid URL string"))
            }
            Err(e) => {
                Err(e)
            }
        }
    }

    pub fn substitute_str(&self, values: &HashMap<String, String>) -> Result<String, UrlTemplateError> {
        // sanity check
        match Url::parse(self.0.as_str()) {
            Ok(parsed) => {
                let scheme_valid = parsed.scheme() == "http" || parsed.scheme() == "https";
                if !scheme_valid {
                    return Err(UrlTemplateError::from(UrlTemplateErrorKind::InvalidScheme));
                }
            }
            _ => {
                return Err(UrlTemplateError::from(UrlTemplateErrorKind::IsNotAnUrl));
            }
        }

        let mut chars = self.0.char_indices();
        let mut out = String::new();

        let mut current_placeholder = String::new();
        let mut inside_placeholder = false;

        loop{
            match chars.next() {
                None => {
                    break
                }
                Some((charnum, '{')) => {
                    if inside_placeholder {
                        return Err(UrlTemplateError::from((UrlTemplateErrorKind::InvalidPattern, charnum)));
                    }
                    current_placeholder = String::new();
                    inside_placeholder = true;
                }
                Some((charnum, '}')) => {
                    if !inside_placeholder {
                        return Err(UrlTemplateError::from((UrlTemplateErrorKind::InvalidPattern, charnum)));
                    }

                    match values.get(&current_placeholder) {
                        Some(s) => {
                            out = out.add(s);
                        }
                        None => {
                            out = out.add("");
                        }
                    }
                    inside_placeholder = false;
                }
                Some((_charnum, ch)) => {
                    if inside_placeholder {
                        current_placeholder.push(ch);
                    } else {
                        out.push(ch);
                    }
                }
            }
        }

        if inside_placeholder {
            return Err(UrlTemplateError::from((UrlTemplateErrorKind::InvalidPattern, self.0.len() - 1)));
        }

        Ok(out)

    }
}