cargo/util/
into_url.rs

1use std::path::{Path, PathBuf};
2
3use url::Url;
4
5use crate::util::CargoResult;
6
7/// A type that can be converted to a Url
8pub trait IntoUrl {
9    /// Performs the conversion
10    fn into_url(self) -> CargoResult<Url>;
11}
12
13impl<'a> IntoUrl for &'a str {
14    fn into_url(self) -> CargoResult<Url> {
15        Url::parse(self).map_err(|s| {
16            if self.starts_with("git@") {
17                anyhow::format_err!(
18                    "invalid url `{}`: {}; try using `{}` instead",
19                    self,
20                    s,
21                    format_args!("ssh://{}", self.replacen(':', "/", 1))
22                )
23            } else {
24                anyhow::format_err!("invalid url `{}`: {}", self, s)
25            }
26        })
27    }
28}
29
30impl<'a> IntoUrl for &'a Path {
31    fn into_url(self) -> CargoResult<Url> {
32        Url::from_file_path(self)
33            .map_err(|()| anyhow::format_err!("invalid path url `{}`", self.display()))
34    }
35}
36
37impl<'a> IntoUrl for &'a PathBuf {
38    fn into_url(self) -> CargoResult<Url> {
39        self.as_path().into_url()
40    }
41}