Skip to main content

lux_lib/git/remote/
url.rs

1use miette::Diagnostic;
2use serde::{de, Deserialize, Deserializer, Serialize};
3use std::{fmt::Display, hash::Hash, str::FromStr};
4use thiserror::Error;
5
6/// GitUrl represents an input url that is a url used by git
7#[derive(Debug, PartialEq, Eq, Hash, Clone)]
8pub struct Url {
9    pub(crate) url: url::Url,
10    host_str: String,
11    /// The raw URL string
12    url_str: String,
13}
14
15#[derive(Debug, Error, Diagnostic)]
16pub enum Error {
17    #[error("error parsing git URL")]
18    GitUrlParse(#[from] url::ParseError),
19    #[error("unsupported git remote scheme {scheme} in URL {url}")]
20    UnsupportedRemoteScheme { scheme: String, url: url::Url },
21    #[error("URL {0} missing host name")]
22    MissingHostName(url::Url),
23}
24
25impl Url {
26    /// Get the repo name, as the final component of the path, with any .git
27    /// suffix removed, or as the hostname, if there is no final path component,
28    /// or as a hash of the whole URL otherwise.
29    pub fn repo(&self) -> &str {
30        let url = &self.url;
31        url.path_segments()
32            .into_iter()
33            .flatten()
34            .next_back()
35            .map(|part| part.strip_suffix(".git").unwrap_or(part))
36            .unwrap_or(&self.host_str)
37    }
38    /// Get the repo owner, as second-final component of the path.
39    pub fn owner(&self) -> Option<&str> {
40        self.url.path_segments().into_iter().flatten().rev().nth(1)
41    }
42    /// Get the host name
43    pub fn host(&self) -> &str {
44        &self.host_str
45    }
46}
47
48impl FromStr for Url {
49    type Err = Error;
50
51    fn from_str(s: &str) -> Result<Self, Self::Err> {
52        let url: url::Url = match normalize_git_url(s) {
53            Some(url) => url.parse()?,
54            None => s.parse()?,
55        };
56        let scheme = url.scheme();
57        if !matches!(scheme, "ssh" | "git" | "http" | "https" | "ftp" | "ftps") {
58            return Err(Error::UnsupportedRemoteScheme {
59                scheme: scheme.into(),
60                url,
61            });
62        }
63        let Some(host_str) = url.host_str() else {
64            return Err(Error::MissingHostName(url));
65        };
66        Ok(Url {
67            host_str: String::from(host_str),
68            url,
69            url_str: String::from(s),
70        })
71    }
72}
73
74/// Converts a Git URL (`git@github.com:nvim-neorg/neorg`) into an `ssh://` URL.
75fn normalize_git_url(s: &str) -> Option<String> {
76    let (host, path) = s.split_once(':')?;
77    // Filter out false positives
78    if path.starts_with('/') || !(host.contains('.') || host.contains('@')) {
79        return None;
80    }
81    Some(format!("ssh://{host}/{path}"))
82}
83
84impl Display for Url {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        self.url_str.fmt(f)
87    }
88}
89
90impl<'de> Deserialize<'de> for Url {
91    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
92    where
93        D: Deserializer<'de>,
94    {
95        String::deserialize(deserializer)?
96            .parse()
97            .map_err(de::Error::custom)
98    }
99}
100
101impl Serialize for Url {
102    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
103    where
104        S: serde::Serializer,
105    {
106        self.to_string().serialize(serializer)
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn test_scp_like_url_ssh() {
116        let url: Url = "git@github.com:lumen-oss/lux.git".parse().unwrap();
117        assert_eq!(url.host(), "github.com");
118        assert_eq!(url.owner(), Some("lumen-oss"));
119        assert_eq!(url.repo(), "lux");
120        assert_eq!(url.to_string(), "git@github.com:lumen-oss/lux.git");
121        let url: Url = "github.com:lumen-oss/lux".parse().unwrap();
122        assert_eq!(url.host(), "github.com");
123        assert_eq!(url.repo(), "lux");
124    }
125
126    #[test]
127    fn test_regular_urls_still_parse() {
128        for raw in [
129            "https://github.com/lumen-oss/lux.git",
130            "ssh://git@github.com/lumen-oss/lux.git",
131        ] {
132            let url: Url = raw.parse().unwrap();
133            assert_eq!(url.host(), "github.com");
134            assert_eq!(url.repo(), "lux");
135        }
136    }
137}