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
use crate::util::{CargoResult, IntoUrl};
use url::Url;
pub trait IntoUrlWithBase {
fn into_url_with_base<U: IntoUrl>(self, base: Option<U>) -> CargoResult<Url>;
}
impl<'a> IntoUrlWithBase for &'a str {
fn into_url_with_base<U: IntoUrl>(self, base: Option<U>) -> CargoResult<Url> {
let base_url = match base {
Some(base) => Some(
base.into_url()
.map_err(|s| anyhow::format_err!("invalid url `{}`: {}", self, s))?,
),
None => None,
};
Url::options()
.base_url(base_url.as_ref())
.parse(self)
.map_err(|s| anyhow::format_err!("invalid url `{}`: {}", self, s))
}
}
#[cfg(test)]
mod tests {
use crate::util::IntoUrlWithBase;
#[test]
fn into_url_with_base() {
assert_eq!(
"rel/path"
.into_url_with_base(Some("file:///abs/path/"))
.unwrap()
.to_string(),
"file:///abs/path/rel/path"
);
assert_eq!(
"rel/path"
.into_url_with_base(Some("file:///abs/path/popped-file"))
.unwrap()
.to_string(),
"file:///abs/path/rel/path"
);
}
}