Skip to main content

caixa_resolver/
url.rs

1//! URL shorthand expansion.
2//!
3//! Accepts the same shorthand Nix flakes do, plus friendly aliases:
4//!   - `github:<org>/<repo>`  → `https://github.com/<org>/<repo>.git`
5//!   - `gitlab:<org>/<repo>`  → `https://gitlab.com/<org>/<repo>.git`
6//!   - `codeberg:<org>/<repo>` → `https://codeberg.org/<org>/<repo>.git`
7//!   - already-explicit URLs (`https://…`, `ssh://…`, `git@…:…`) pass through.
8
9/// Expand a shorthand to a concrete `git clone`-ready URL.
10#[must_use]
11pub fn expand_shorthand(repo: &str) -> String {
12    if repo.contains("://")
13        || repo.starts_with("git@")
14        || repo.starts_with('/')
15        || repo.starts_with('.')
16    {
17        return repo.to_string();
18    }
19    if let Some((prefix, path)) = repo.split_once(':') {
20        match prefix {
21            "github" => return format!("https://github.com/{path}.git"),
22            "gitlab" => return format!("https://gitlab.com/{path}.git"),
23            "codeberg" => return format!("https://codeberg.org/{path}.git"),
24            "sourcehut" | "sr.ht" => return format!("https://git.sr.ht/~{path}"),
25            _ => {}
26        }
27    }
28    repo.to_string()
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn github_expands() {
37        assert_eq!(
38            expand_shorthand("github:pleme-io/caixa"),
39            "https://github.com/pleme-io/caixa.git"
40        );
41    }
42
43    #[test]
44    fn gitlab_expands() {
45        assert_eq!(
46            expand_shorthand("gitlab:my-org/proj"),
47            "https://gitlab.com/my-org/proj.git"
48        );
49    }
50
51    #[test]
52    fn https_passes_through() {
53        let url = "https://github.com/pleme-io/caixa.git";
54        assert_eq!(expand_shorthand(url), url);
55    }
56
57    #[test]
58    fn ssh_passes_through() {
59        let url = "git@github.com:pleme-io/caixa.git";
60        assert_eq!(expand_shorthand(url), url);
61    }
62
63    #[test]
64    fn local_path_passes_through() {
65        assert_eq!(expand_shorthand("../caixa-teia"), "../caixa-teia");
66        assert_eq!(expand_shorthand("/abs/path"), "/abs/path");
67    }
68}