ask-please 0.4.8

Agent Skills Kit — download version-specific library docs for AI coding agents (Rust port of @pleaseai/ask).
Documentation
//! Ecosystem resolvers — map a package name + version to a GitHub `owner/repo`
//! plus a git ref, over the injectable [`crate::http::HttpClient`]. Rust port of
//! `packages/cli/src/resolvers/`.
//!
//! Resolvers are orthogonal to sources: they only do metadata lookups and hand
//! the resolved `repo` + `ref` to the github source. The npm/pypi/pub resolvers
//! parse JSON; maven walks the Search API + POM XML.

mod maven;
mod npm;
mod pub_dev;
mod pypi;

use std::sync::LazyLock;

use regex::Regex;

use crate::http::HttpClient;

/// Result of resolving an ecosystem package to a GitHub repository. Always
/// handed off to the github source for download (port of `ResolveResult`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolveResult {
    /// GitHub `owner/repo`.
    pub repo: String,
    /// Primary git ref to try first (tag or branch).
    pub ref_: String,
    /// Fallback refs to try if the primary ref doesn't exist (empty = none).
    pub fallback_refs: Vec<String>,
    /// Resolved version string (e.g. `4.17.21`).
    pub resolved_version: String,
}

/// An ecosystem resolver function: `(client, name, version) -> ResolveResult`.
pub type ResolverFn = fn(&dyn HttpClient, &str, &str) -> anyhow::Result<ResolveResult>;

/// Return the resolver for the given ecosystem, or `None` if unsupported
/// (port of `getResolver`).
pub fn get_resolver(ecosystem: &str) -> Option<ResolverFn> {
    match ecosystem {
        "maven" => Some(maven::resolve),
        "npm" => Some(npm::resolve),
        "pypi" => Some(pypi::resolve),
        "pub" => Some(pub_dev::resolve),
        _ => None,
    }
}

// `github.com` followed by `/` or `:`, then owner (no `/`), `/`, then repo up to
// the first `/`, `#`, `?`, or whitespace. Mirrors the TS `RE_GITHUB_URL`.
static RE_GITHUB_URL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"github\.com[/:]([^/]+)/([^/#?\s]+)").unwrap());

/// Parse a repository URL into `owner/repo` form (port of `parseRepoUrl`).
///
/// Handles `git+https://…`, `https://…`, `git://…`, `ssh://git@…`,
/// `github.com/owner/repo`, and URLs with extra path segments. A trailing
/// `.git` on the repo is stripped. Returns `None` for non-GitHub or empty input.
pub fn parse_repo_url(url: Option<&str>) -> Option<String> {
    let url = url?;
    if url.is_empty() {
        return None;
    }
    let caps = RE_GITHUB_URL.captures(url)?;
    let owner = caps.get(1)?.as_str();
    let repo = caps.get(2)?.as_str();
    let repo = repo.strip_suffix(".git").unwrap_or(repo);
    Some(format!("{owner}/{repo}"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_common_github_url_forms() {
        let cases = [
            "git+https://github.com/owner/repo.git",
            "https://github.com/owner/repo",
            "git://github.com/owner/repo.git",
            "ssh://git@github.com/owner/repo.git",
            "github.com/owner/repo",
            "https://github.com/owner/repo/tree/main",
        ];
        for url in cases {
            assert_eq!(
                parse_repo_url(Some(url)).as_deref(),
                Some("owner/repo"),
                "url: {url}"
            );
        }
    }

    #[test]
    fn strips_only_trailing_dot_git() {
        // `.git` mid-repo (unusual) is not stripped; only the trailing suffix.
        assert_eq!(
            parse_repo_url(Some("https://github.com/owner/repo.github.io")).as_deref(),
            Some("owner/repo.github.io")
        );
    }

    #[test]
    fn rejects_non_github_and_empty() {
        assert_eq!(parse_repo_url(Some("https://gitlab.com/owner/repo")), None);
        assert_eq!(parse_repo_url(Some("")), None);
        assert_eq!(parse_repo_url(None), None);
        assert_eq!(parse_repo_url(Some("not a url")), None);
    }
}