Skip to main content

ask/resolvers/
mod.rs

1//! Ecosystem resolvers — map a package name + version to a GitHub `owner/repo`
2//! plus a git ref, over the injectable [`crate::http::HttpClient`]. Rust port of
3//! `packages/cli/src/resolvers/`.
4//!
5//! Resolvers are orthogonal to sources: they only do metadata lookups and hand
6//! the resolved `repo` + `ref` to the github source. The npm/pypi/pub resolvers
7//! parse JSON; maven walks the Search API + POM XML.
8
9mod maven;
10mod npm;
11mod pub_dev;
12mod pypi;
13
14use std::sync::LazyLock;
15
16use regex::Regex;
17
18use crate::http::HttpClient;
19
20/// Result of resolving an ecosystem package to a GitHub repository. Always
21/// handed off to the github source for download (port of `ResolveResult`).
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct ResolveResult {
24    /// GitHub `owner/repo`.
25    pub repo: String,
26    /// Primary git ref to try first (tag or branch).
27    pub ref_: String,
28    /// Fallback refs to try if the primary ref doesn't exist (empty = none).
29    pub fallback_refs: Vec<String>,
30    /// Resolved version string (e.g. `4.17.21`).
31    pub resolved_version: String,
32}
33
34/// An ecosystem resolver function: `(client, name, version) -> ResolveResult`.
35pub type ResolverFn = fn(&dyn HttpClient, &str, &str) -> anyhow::Result<ResolveResult>;
36
37/// Return the resolver for the given ecosystem, or `None` if unsupported
38/// (port of `getResolver`).
39pub 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
49// `github.com` followed by `/` or `:`, then owner (no `/`), `/`, then repo up to
50// the first `/`, `#`, `?`, or whitespace. Mirrors the TS `RE_GITHUB_URL`.
51static RE_GITHUB_URL: LazyLock<Regex> =
52    LazyLock::new(|| Regex::new(r"github\.com[/:]([^/]+)/([^/#?\s]+)").unwrap());
53
54/// Parse a repository URL into `owner/repo` form (port of `parseRepoUrl`).
55///
56/// Handles `git+https://…`, `https://…`, `git://…`, `ssh://git@…`,
57/// `github.com/owner/repo`, and URLs with extra path segments. A trailing
58/// `.git` on the repo is stripped. Returns `None` for non-GitHub or empty input.
59pub 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        // `.git` mid-repo (unusual) is not stripped; only the trailing suffix.
97        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}