1mod maven;
10mod npm;
11mod pub_dev;
12mod pypi;
13
14use std::sync::LazyLock;
15
16use regex::Regex;
17
18use crate::http::HttpClient;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct ResolveResult {
24 pub repo: String,
26 pub ref_: String,
28 pub fallback_refs: Vec<String>,
30 pub resolved_version: String,
32}
33
34pub type ResolverFn = fn(&dyn HttpClient, &str, &str) -> anyhow::Result<ResolveResult>;
36
37pub fn get_resolver(ecosystem: &str) -> Option<ResolverFn> {
40 match ecosystem {
41 "maven" => Some(maven::resolve),
42 "npm" => Some(npm::resolve),
43 "pypi" => Some(pypi::resolve),
44 "pub" => Some(pub_dev::resolve),
45 _ => None,
46 }
47}
48
49static RE_GITHUB_URL: LazyLock<Regex> =
52 LazyLock::new(|| Regex::new(r"github\.com[/:]([^/]+)/([^/#?\s]+)").unwrap());
53
54pub fn parse_repo_url(url: Option<&str>) -> Option<String> {
60 let url = url?;
61 if url.is_empty() {
62 return None;
63 }
64 let caps = RE_GITHUB_URL.captures(url)?;
65 let owner = caps.get(1)?.as_str();
66 let repo = caps.get(2)?.as_str();
67 let repo = repo.strip_suffix(".git").unwrap_or(repo);
68 Some(format!("{owner}/{repo}"))
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 #[test]
76 fn parses_common_github_url_forms() {
77 let cases = [
78 "git+https://github.com/owner/repo.git",
79 "https://github.com/owner/repo",
80 "git://github.com/owner/repo.git",
81 "ssh://git@github.com/owner/repo.git",
82 "github.com/owner/repo",
83 "https://github.com/owner/repo/tree/main",
84 ];
85 for url in cases {
86 assert_eq!(
87 parse_repo_url(Some(url)).as_deref(),
88 Some("owner/repo"),
89 "url: {url}"
90 );
91 }
92 }
93
94 #[test]
95 fn strips_only_trailing_dot_git() {
96 assert_eq!(
98 parse_repo_url(Some("https://github.com/owner/repo.github.io")).as_deref(),
99 Some("owner/repo.github.io")
100 );
101 }
102
103 #[test]
104 fn rejects_non_github_and_empty() {
105 assert_eq!(parse_repo_url(Some("https://gitlab.com/owner/repo")), None);
106 assert_eq!(parse_repo_url(Some("")), None);
107 assert_eq!(parse_repo_url(None), None);
108 assert_eq!(parse_repo_url(Some("not a url")), None);
109 }
110}