Skip to main content

lux_lib/git/
url.rs

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