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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#![deny(warnings)]

//! url_path
//! Manipulate url paths without requiring the file to exist in the server or OS
//! This is useful for manipulating location urls
//! Example usage:
//! ```rust
//! use url_path::UrlPath;
//!
//! fn main(){
//!     let url_path1 = UrlPath::new("src/md/./../../README.md");
//!     let normalized_path1 = url_path1.normalize();
//!     assert_eq!("README.md", normalized_path1);
//!
//!     let url_path2 = UrlPath::new("./README.md");
//!     let normalized_path2 = url_path2.normalize();
//!     assert_eq!("README.md", normalized_path2);
//! }
//! ```
pub enum UrlPath {
    Path {
        parent: Option<String>,
        /// the last element of the url when split with `/`
        last: Option<String>,
        is_absolute: bool,
    },
    External(String),
}

impl UrlPath {
    pub fn new(path: &str) -> Self {
        let (parent, last) = Self::canonicalize(path);
        let is_external = path.starts_with("http:") || path.starts_with("https:");

        let is_absolute = path.starts_with("/");

        if is_external {
            UrlPath::External(path.to_string())
        } else {
            UrlPath::Path {
                parent,
                last,
                is_absolute,
            }
        }
    }

    pub fn is_absolute(&self) -> bool {
        match self {
            UrlPath::Path {
                ref is_absolute, ..
            } => *is_absolute,
            UrlPath::External(_) => false,
        }
    }

    pub fn is_external(&self) -> bool {
        match self {
            UrlPath::External(_) => true,
            UrlPath::Path { .. } => false,
        }
    }

    /// use own implementation of canonicalize since fs::canonicalize
    /// requires the file to be there
    fn canonicalize(path: &str) -> (Option<String>, Option<String>) {
        let segments: Vec<&str> = path.split("/").collect();
        let mut path: Vec<String> = vec![];
        let segments2: Vec<&str> = segments
            .into_iter()
            .filter(|s| !(s.is_empty() || *s == "."))
            .collect();
        let _filtered: Vec<&str> = segments2
            .into_iter()
            .inspect(|s| {
                if *s == ".." {
                    path.pop();
                } else {
                    path.push(s.to_string())
                }
            })
            .collect();
        let filename = path.pop();
        let parent = path.join("/");
        let parent = if parent.is_empty() {
            None
        } else {
            Some(parent)
        };
        (parent, filename)
    }

    pub fn last(&self) -> Option<String> {
        match self {
            UrlPath::Path { last, .. } => last.clone(),
            UrlPath::External(_) => None,
        }
    }

    pub fn parent(&self) -> Option<String> {
        match self {
            UrlPath::Path { parent, .. } => parent.clone(),
            UrlPath::External(_) => None,
        }
    }

    /// return the extension (ie: html, md, txt ) of the path if there is
    pub fn extension(&self) -> Option<String> {
        if let Some(last) = self.last() {
            let splinters: Vec<&str> = last.split(".").collect();
            if splinters.len() > 0 {
                let last = splinters[splinters.len() - 1];
                Some(last.to_string())
            } else {
                None
            }
        } else {
            None
        }
    }

    /// returns true if the extension of this path matched the argument extension `ext`
    pub fn is_extension(&self, ext: &str) -> bool {
        if let Some(ex) = self.extension() {
            ex == ext
        } else {
            false
        }
    }

    /// return the constructed file
    pub fn normalize(&self) -> String {
        match self {
            UrlPath::Path {
                parent,
                last,
                is_absolute,
            } => {
                let full_path = if let Some(ref parent) = parent {
                    if let Some(ref file) = last {
                        format!("{}/{}", parent, file)
                    } else {
                        format!("{}", parent)
                    }
                } else if let Some(ref file) = last {
                    if let Some(ref parent) = parent {
                        format!("{}/{}", parent, file)
                    } else {
                        format!("{}", file)
                    }
                } else {
                    "".to_string()
                };

                if *is_absolute {
                    format!("/{}", full_path)
                } else {
                    full_path
                }
            }
            UrlPath::External(ref s) => s.to_string(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn it_works() {
        let url = "md/README.md";
        let path = UrlPath::new(url);
        let result = path.normalize();
        let expected = "md/README.md";
        assert_eq!(expected, result);
    }

    #[test]
    fn relative_file() {
        let url = "./README.md";
        let path = UrlPath::new(url);
        let result = path.normalize();
        let expected = "README.md";
        assert_eq!(expected, result);
    }

    #[test]
    fn external_link() {
        let url = "https://raw.githubusercontent.com/ivanceras/svgbob/master/TODO.md";
        let path = UrlPath::new(url);
        assert!(path.is_external());
        let result = path.normalize();
        let expected = "https://raw.githubusercontent.com/ivanceras/svgbob/master/TODO.md";
        assert_eq!(expected, result);
    }

    #[test]
    fn absolute() {
        let url = "/home/user/md/README.md";
        let path = UrlPath::new(url);
        let result = path.normalize();
        let expected = "/home/user/md/README.md";
        assert_eq!(expected, result);
    }

    #[test]
    fn absolute_with_dotdot() {
        let url = "/home/user/md/../../README.md";
        let path = UrlPath::new(url);
        let result = path.normalize();
        let expected = "/home/README.md";
        assert_eq!(expected, result);
    }

    #[test]
    fn normalize1() {
        let url = "md/more/../README.md";
        let path = UrlPath::new(url);
        let result = path.normalize();
        let expected = "md/README.md";
        assert_eq!(expected, result);
    }

    #[test]
    fn normalize2() {
        let url = "md/../README.md";
        let path = UrlPath::new(url);
        let result = path.normalize();
        let expected = "README.md";
        assert_eq!(expected, result);
    }

    #[test]
    fn no_parent() {
        let url = "README.md";
        let path = UrlPath::new(url);
        let last = "README.md";
        assert_eq!(Some(last.to_string()), path.last());
        assert_eq!(None, path.parent());
    }

    #[test]
    fn no_parent2() {
        let url = "md/../README.md";
        let path = UrlPath::new(url);
        let last = "README.md";
        assert_eq!(Some(last.to_string()), path.last());
        assert_eq!(None, path.parent());
    }

    #[test]
    fn normalize_no_more_back() {
        let url = "../../README.md";
        let path = UrlPath::new(url);
        let result = path.normalize();
        let expected = "README.md";
        assert_eq!(expected, result);
    }

    #[test]
    fn md_extension() {
        let url = "../../README.md";
        let path = UrlPath::new(url);
        let result = path.extension();
        let expected = Some("md".to_string());
        assert_eq!(expected, result);
    }

    #[test]
    fn html_extension() {
        let url = "index.html";
        let path = UrlPath::new(url);
        let result = path.extension();
        let expected = Some("html".to_string());
        assert_eq!(expected, result);
    }
}