Skip to main content

lux_lib/git/remote/
shorthand.rs

1use std::{fmt::Display, str::FromStr};
2
3use super::url::{self, Url};
4use chumsky::{prelude::*, Parser};
5use miette::Diagnostic;
6use serde::{de, Deserialize, Deserializer};
7use thiserror::Error;
8
9const GITHUB: &str = "github";
10const GITLAB: &str = "gitlab";
11const SOURCEHUT: &str = "sourcehut";
12const CODEBERG: &str = "codeberg";
13
14#[derive(Debug, Error, Diagnostic)]
15#[error("error parsing git source: {0:#?}")]
16pub struct Error(Vec<String>);
17
18/// Helper for parsing Git URLs from shorthands, e.g. "gitlab:owner/repo"
19#[derive(Debug, Clone)]
20pub struct Shorthand(Url);
21
22impl Shorthand {
23    pub fn parse_with_prefix(s: &str) -> Result<Self, Error> {
24        prefix_parser()
25            .parse(s)
26            .into_result()
27            .map_err(|err| Error(err.into_iter().map(|e| e.to_string()).collect()))
28    }
29    pub fn repo_name() {}
30}
31
32impl FromStr for Shorthand {
33    type Err = Error;
34
35    fn from_str(s: &str) -> Result<Self, Self::Err> {
36        match parser()
37            .parse(s)
38            .into_result()
39            .map_err(|err| Error(err.into_iter().map(|e| e.to_string()).collect()))
40        {
41            Ok(url) => Ok(url),
42            Err(err) => match s.parse() {
43                // fall back to parsing the URL directly
44                Ok(url) => Ok(Self(url)),
45                Err(_) => Err(err),
46            },
47        }
48    }
49}
50
51impl<'de> Deserialize<'de> for Shorthand {
52    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
53    where
54        D: Deserializer<'de>,
55    {
56        String::deserialize(deserializer)?
57            .parse()
58            .map_err(de::Error::custom)
59    }
60}
61
62impl From<Url> for Shorthand {
63    fn from(value: Url) -> Self {
64        Self(value)
65    }
66}
67
68impl From<Shorthand> for Url {
69    fn from(value: Shorthand) -> Self {
70        value.0
71    }
72}
73
74#[derive(Debug, Default)]
75enum GitHost {
76    #[default]
77    Github,
78    Gitlab,
79    Sourcehut,
80    Codeberg,
81}
82
83fn url_from_git_host(host: GitHost, owner: String, repo: String) -> Result<Shorthand, url::Error> {
84    let url_str = match host {
85        GitHost::Github => format!("https://github.com/{owner}/{repo}.git"),
86        GitHost::Gitlab => format!("https://gitlab.com/{owner}/{repo}.git"),
87        GitHost::Sourcehut => format!("https://git.sr.ht/~{owner}/{repo}"),
88        GitHost::Codeberg => format!("https://codeberg.org/~{owner}/{repo}.git"),
89    };
90    let url = url_str.parse()?;
91    Ok(Shorthand(url))
92}
93
94fn to_tuple<T>(v: Vec<T>) -> (T, T)
95where
96    T: Clone,
97{
98    (v[0].clone(), v[1].clone())
99}
100
101// A parser that expects a prefix
102fn prefix_parser<'a>() -> impl Parser<'a, &'a str, Shorthand, chumsky::extra::Err<Rich<'a, char>>> {
103    let git_host_prefix = just(GITHUB)
104        .or(just(GITLAB).or(just(SOURCEHUT).or(just(CODEBERG))))
105        .then_ignore(just(":"))
106        .map(|prefix| match prefix {
107            GITHUB => GitHost::Github,
108            GITLAB => GitHost::Gitlab,
109            SOURCEHUT => GitHost::Sourcehut,
110            CODEBERG => GitHost::Codeberg,
111            _ => unreachable!(),
112        })
113        .map_err(|err: Rich<'a, char>| {
114            let span = *err.span();
115            Rich::custom(span, "missing git host prefix. Expected 'github:', 'gitlab:', 'sourcehut:' or 'codeberg:'.")
116        });
117    let owner_repo = none_of('/')
118        .repeated()
119        .collect::<String>()
120        .separated_by(just('/'))
121        .exactly(2)
122        .collect::<Vec<String>>()
123        .map(to_tuple);
124    git_host_prefix
125        .then(owner_repo)
126        .try_map(|(host, (owner, repo)), span| {
127            let url = url_from_git_host(host, owner, repo).map_err(|err| {
128                Rich::custom(span, format!("error parsing git url shorthand: {err}"))
129            })?;
130            Ok(url)
131        })
132}
133
134// A parser for scp-style git URLs, converting them into ssh: URLs.
135fn scp_style_parser<'a>() -> impl Parser<'a, &'a str, Shorthand, chumsky::extra::Err<Rich<'a, char>>>
136{
137    none_of(":/")
138        .repeated()
139        .collect::<String>()
140        .then(
141            just(':')
142                .ignore_then(just("//").not())
143                .ignore_then(any().repeated().collect::<String>()),
144        )
145        .try_map(|(host, path), span| {
146            let inner = format!("ssh://{host}/{path}")
147                .parse::<Url>()
148                .map_err(|err| {
149                    Rich::custom(span, format!("error parsing scp style git url: {err}"))
150                })?;
151            Ok(Shorthand(inner))
152        })
153}
154
155// A parser that tries to parse as such:
156//
157// * If it can be parsed exactly as one of our shorthand prefixes, it is expanded into that host reference.
158// * If it can be parsed as a simple owner/repo pair, it is considered to be a github shorthand reference.
159// * If the string has at least one colon, and the first colon does not follow any slashes and is not immediately followed by two slashes, it is considered to be in scp style.
160fn parser<'a>() -> impl Parser<'a, &'a str, Shorthand, chumsky::extra::Err<Rich<'a, char>>> {
161    let owner_repo = none_of(":/")
162        .repeated()
163        .collect::<String>()
164        .separated_by(just('/'))
165        .exactly(2)
166        .collect::<Vec<String>>()
167        .map(to_tuple);
168    owner_repo
169        .try_map(|(owner, repo), span| {
170            let url = url_from_git_host(GitHost::default(), owner, repo).map_err(|err| {
171                Rich::custom(span, format!("error parsing git url shorthand: {err}"))
172            })?;
173            Ok(url)
174        })
175        .or(prefix_parser())
176        .or(scp_style_parser())
177}
178
179impl Display for Shorthand {
180    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181        match (self.0.url.host_str(), self.0.owner()) {
182            (Some("github.com"), Some(owner)) => {
183                format!("{}:{}/{}", GITHUB, owner, self.0.repo())
184            }
185            (Some("gitlab.com"), Some(owner)) => {
186                format!("{}:{}/{}", GITLAB, owner, self.0.repo())
187            }
188            (Some("git.sr.ht"), Some(owner)) => {
189                format!("{}:{}/{}", SOURCEHUT, owner.replace('~', ""), self.0.repo())
190            }
191            (Some("codeberg.org"), Some(owner)) => {
192                format!("{}:{}/{}", CODEBERG, owner.replace('~', ""), self.0.repo())
193            }
194            _ => {
195                format!("{}", self.0)
196            }
197        }
198        .fmt(f)
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[tokio::test]
207    async fn owner_repo_shorthand() {
208        let url_shorthand: Shorthand = "lumen-oss/lux".parse().unwrap();
209        assert_eq!(url_shorthand.0.owner(), Some("lumen-oss"));
210        assert_eq!(url_shorthand.0.repo(), "lux");
211    }
212
213    #[tokio::test]
214    async fn github_shorthand() {
215        let url_shorthand_str = "github:lumen-oss/lux";
216        let url_shorthand: Shorthand = url_shorthand_str.parse().unwrap();
217        assert_eq!(url_shorthand.0.url.host_str(), Some("github.com"));
218        assert_eq!(url_shorthand.0.owner(), Some("lumen-oss"));
219        assert_eq!(url_shorthand.0.repo(), "lux");
220        assert_eq!(url_shorthand.to_string(), url_shorthand_str.to_string());
221    }
222
223    #[tokio::test]
224    async fn gitlab_shorthand() {
225        let url_shorthand_str = "gitlab:lumen-oss/lux";
226        let url_shorthand: Shorthand = url_shorthand_str.parse().unwrap();
227        assert_eq!(url_shorthand.0.url.host_str(), Some("gitlab.com"));
228        assert_eq!(url_shorthand.0.owner(), Some("lumen-oss"));
229        assert_eq!(url_shorthand.0.repo(), "lux");
230        assert_eq!(url_shorthand.to_string(), url_shorthand_str.to_string());
231    }
232
233    #[tokio::test]
234    async fn sourcehut_shorthand() {
235        let url_shorthand_str = "sourcehut:lumen-oss/lux";
236        let url_shorthand: Shorthand = url_shorthand_str.parse().unwrap();
237        assert_eq!(url_shorthand.0.url.host_str(), Some("git.sr.ht"));
238        assert_eq!(url_shorthand.0.owner(), Some("~lumen-oss"));
239        assert_eq!(url_shorthand.0.repo(), "lux");
240        assert_eq!(url_shorthand.to_string(), url_shorthand_str.to_string());
241    }
242
243    #[tokio::test]
244    async fn codeberg_shorthand() {
245        let url_shorthand_str = "codeberg:lumen-oss/lux";
246        let url_shorthand: Shorthand = url_shorthand_str.parse().unwrap();
247        assert_eq!(url_shorthand.0.url.host_str(), Some("codeberg.org"));
248        assert_eq!(url_shorthand.0.owner(), Some("~lumen-oss"));
249        assert_eq!(url_shorthand.0.repo(), "lux");
250        assert_eq!(url_shorthand.to_string(), url_shorthand_str.to_string());
251    }
252
253    #[tokio::test]
254    async fn regular_https_url() {
255        let url_shorthand: Shorthand = "https://github.com/lumen-oss/lux.git".parse().unwrap();
256        assert_eq!(url_shorthand.0.url.host_str(), Some("github.com"));
257        assert_eq!(url_shorthand.0.owner(), Some("lumen-oss"));
258        assert_eq!(url_shorthand.0.repo(), "lux");
259        assert_eq!(
260            url_shorthand.to_string(),
261            "github:lumen-oss/lux".to_string()
262        );
263    }
264
265    #[tokio::test]
266    async fn regular_http_url() {
267        let url_shorthand: Shorthand = "http://github.com/lumen-oss/lux.git".parse().unwrap();
268        assert_eq!(url_shorthand.0.url.host_str(), Some("github.com"));
269        assert_eq!(url_shorthand.0.owner(), Some("lumen-oss"));
270        assert_eq!(url_shorthand.0.repo(), "lux");
271        assert_eq!(
272            url_shorthand.to_string(),
273            "github:lumen-oss/lux".to_string()
274        );
275    }
276
277    #[tokio::test]
278    async fn regular_ssh_url() {
279        let url_shorthand: Shorthand = "ssh://git@github.com/lumen-oss/lux.git".parse().unwrap();
280        assert_eq!(url_shorthand.0.url.host_str(), Some("github.com"));
281        assert_eq!(url_shorthand.0.owner(), Some("lumen-oss"));
282        assert_eq!(url_shorthand.0.repo(), "lux");
283        assert_eq!(
284            url_shorthand.to_string(),
285            "github:lumen-oss/lux".to_string()
286        );
287    }
288
289    #[tokio::test]
290    async fn regular_ftp_url() {
291        let url_shorthand: Shorthand = "ftp://github.com/lumen-oss/lux.git".parse().unwrap();
292        assert_eq!(url_shorthand.0.url.host_str(), Some("github.com"));
293        assert_eq!(url_shorthand.0.owner(), Some("lumen-oss"));
294        assert_eq!(url_shorthand.0.repo(), "lux");
295        assert_eq!(
296            url_shorthand.to_string(),
297            "github:lumen-oss/lux".to_string()
298        );
299    }
300
301    #[tokio::test]
302    async fn regular_ftps_url() {
303        let url_shorthand: Shorthand = "ftps://github.com/lumen-oss/lux.git".parse().unwrap();
304        assert_eq!(url_shorthand.0.url.host_str(), Some("github.com"));
305        assert_eq!(url_shorthand.0.owner(), Some("lumen-oss"));
306        assert_eq!(url_shorthand.0.repo(), "lux");
307        assert_eq!(
308            url_shorthand.to_string(),
309            "github:lumen-oss/lux".to_string()
310        );
311    }
312
313    #[tokio::test]
314    async fn illegal_scheme_url() {
315        Shorthand::from_str("git+https://github.com/lumen-oss/lux.git")
316            .expect_err("git+ handling should be done in an outer layer.");
317        Shorthand::from_str("file:///lumen-oss/lux.git")
318            .expect_err("local filesystems are not supported as a Remote URL.");
319        Shorthand::from_str("xyz:///lumen-oss/lux.git").expect_err("Unknown schemes are rejected");
320    }
321
322    #[tokio::test]
323    async fn git_scheme_url() {
324        let url_shorthand: Shorthand = "git://git@github.com/lumen-oss/lux.git".parse().unwrap();
325        assert_eq!(url_shorthand.0.url.host_str(), Some("github.com"));
326        assert_eq!(url_shorthand.0.owner(), Some("lumen-oss"));
327        assert_eq!(url_shorthand.0.repo(), "lux");
328        assert_eq!(
329            url_shorthand.to_string(),
330            "github:lumen-oss/lux".to_string()
331        );
332    }
333
334    #[tokio::test]
335    async fn scp_style_url() {
336        let url_str = "git@github.com:lumen-oss/lux.git";
337        let url_shorthand: Shorthand = url_str.parse().unwrap();
338        assert_eq!(url_shorthand.0.url.host_str(), Some("github.com"));
339        assert_eq!(url_shorthand.0.owner(), Some("lumen-oss"));
340        assert_eq!(url_shorthand.0.repo(), "lux");
341    }
342
343    #[tokio::test]
344    async fn parse_with_prefix() {
345        Shorthand::parse_with_prefix("lumen-oss/lux").unwrap_err();
346        Shorthand::parse_with_prefix("github:lumen-oss/lux").unwrap();
347        Shorthand::parse_with_prefix("gitlab:lumen-oss/lux").unwrap();
348        Shorthand::parse_with_prefix("sourcehut:lumen-oss/lux").unwrap();
349        Shorthand::parse_with_prefix("codeberg:lumen-oss/lux").unwrap();
350        Shorthand::parse_with_prefix("bla:lumen-oss/lux").unwrap_err();
351    }
352}