Skip to main content

ask/sources/
github.rs

1//! GitHub source — shallow-clone a ref into the global store (tar.gz fallback),
2//! with ref-candidate fallbacks and token auth. Rust port of `sources/github.ts`.
3//!
4//! Clones happen via a `git` SHELL-OUT (not a git library) so the opensrc
5//! `authenticated_clone_url` token injection + `redact_token` scrubbing port
6//! verbatim, including the #66 host-confusion fix.
7
8use std::io::Cursor;
9use std::path::Path;
10use std::process::Command;
11use std::sync::LazyLock;
12
13use anyhow::{bail, Result};
14use flate2::read::GzDecoder;
15use regex::Regex;
16use url::Url;
17
18use super::{extract_docs_from_dir, FetchMeta, FetchResult, GITHUB_DOC_CANDIDATES};
19use crate::http::HttpClient;
20use crate::store::{
21    acquire_entry_lock, cp_dir_atomic, github_store_path, quarantine_entry, stamp_entry,
22    verify_entry,
23};
24
25const DEFAULT_GITHUB_HOST: &str = "github.com";
26
27// ASCII-only classes to match the JS `\w` (`[A-Za-z0-9_]`), not Rust's
28// unicode-aware `\w`.
29static RE_SAFE_REPO: LazyLock<Regex> =
30    LazyLock::new(|| Regex::new(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$").unwrap());
31static RE_SAFE_REF: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[A-Za-z0-9._/@-]+$").unwrap());
32static RE_SHA40: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[0-9a-f]{40}$").unwrap());
33
34/// Default-branch fallbacks tried (after `main`) when neither tag nor branch was
35/// given.
36const DEFAULT_BRANCH_FALLBACKS: &[&str] = &["master"];
37
38/// Options for a github fetch (port of `GithubSourceOptions`).
39#[derive(Debug, Clone, Default)]
40pub struct GithubOptions {
41    pub name: String,
42    pub version: String,
43    pub repo: String,
44    pub branch: Option<String>,
45    pub tag: Option<String>,
46    pub docs_path: Option<String>,
47    pub fallback_refs: Vec<String>,
48    pub remote_url: Option<String>,
49    pub skip_doc_extraction: bool,
50}
51
52/// The `GITHUB_TOKEN` from the environment, empty string treated as absent.
53pub fn github_token() -> Option<String> {
54    std::env::var("GITHUB_TOKEN").ok().filter(|t| !t.is_empty())
55}
56
57/// Rewrite an HTTPS GitHub clone URL to embed `x-access-token:<token>` auth, but
58/// ONLY on an exact `github.com` host over `https` (opensrc #66: prefix/suffix-
59/// confusable hosts, subdomains, non-https schemes, and ssh remotes pass through
60/// unchanged). The result carries the secret — use it only as a git argument,
61/// never in logs.
62pub fn authenticated_clone_url(url: &str, token: Option<&str>) -> String {
63    let token = match token {
64        Some(t) if !t.is_empty() => t,
65        _ => return url.to_string(),
66    };
67    let Ok(mut parsed) = Url::parse(url) else {
68        return url.to_string();
69    };
70    if parsed.scheme() != "https" {
71        return url.to_string();
72    }
73    if parsed.host_str().map(str::to_ascii_lowercase).as_deref() != Some(DEFAULT_GITHUB_HOST) {
74        return url.to_string();
75    }
76    if parsed.set_username("x-access-token").is_err() || parsed.set_password(Some(token)).is_err() {
77        return url.to_string();
78    }
79    parsed.to_string()
80}
81
82/// Replace every occurrence of the token with `***` before logging/throwing.
83fn redact_token(msg: &str, token: Option<&str>) -> String {
84    match token {
85        Some(t) if !t.is_empty() => msg.replace(t, "***"),
86        _ => msg.to_string(),
87    }
88}
89
90/// Build the ref candidate chain: the ref as-is, plus `v<ref>` when it isn't
91/// already `v`-prefixed. `extra` (monorepo tags) prepend; `tail` (default-branch
92/// fallbacks) append; duplicates dropped (first wins).
93fn ref_candidates(reference: &str, extra: &[String], tail: &[String]) -> Vec<String> {
94    let base: Vec<String> = if reference.starts_with('v') {
95        vec![reference.to_string()]
96    } else {
97        vec![reference.to_string(), format!("v{reference}")]
98    };
99    if extra.is_empty() && tail.is_empty() {
100        return base;
101    }
102    let mut seen = std::collections::HashSet::new();
103    let mut result = Vec::new();
104    for c in extra.iter().chain(base.iter()).chain(tail.iter()) {
105        if seen.insert(c.clone()) {
106            result.push(c.clone());
107        }
108    }
109    result
110}
111
112fn has_git() -> bool {
113    Command::new("git")
114        .arg("--version")
115        .stdout(std::process::Stdio::null())
116        .stderr(std::process::Stdio::null())
117        .status()
118        .map(|s| s.success())
119        .unwrap_or(false)
120}
121
122/// Remove the contents of `dir` (keeping `dir`) so a failed clone can be retried.
123fn clear_dir_contents(dir: &Path) {
124    if let Ok(entries) = std::fs::read_dir(dir) {
125        for entry in entries.flatten() {
126            let _ = std::fs::remove_dir_all(entry.path())
127                .or_else(|_| std::fs::remove_file(entry.path()));
128        }
129    }
130}
131
132/// Shallow-clone a single candidate ref into `tmp_dir`, capture the commit SHA,
133/// then strip `.git/`. Returns the commit SHA or an error (token-redacted).
134fn shallow_clone_ref(
135    remote_url: &str,
136    candidate: &str,
137    tmp_dir: &Path,
138    token: Option<&str>,
139) -> Result<String> {
140    clear_dir_contents(tmp_dir);
141    let auth_url = authenticated_clone_url(remote_url, token);
142    let output = Command::new("git")
143        .args([
144            "clone",
145            "--depth",
146            "1",
147            "--branch",
148            candidate,
149            "--single-branch",
150        ])
151        .arg(&auth_url)
152        .arg(tmp_dir)
153        .stdin(std::process::Stdio::null())
154        .stdout(std::process::Stdio::null())
155        .stderr(std::process::Stdio::piped())
156        .output()?;
157    if !output.status.success() {
158        let stderr = String::from_utf8_lossy(&output.stderr);
159        bail!("{}", redact_token(stderr.trim(), token));
160    }
161
162    let rev = Command::new("git")
163        .args(["-C"])
164        .arg(tmp_dir)
165        .args(["rev-parse", "HEAD"])
166        .output()?;
167    let commit = String::from_utf8_lossy(&rev.stdout).trim().to_string();
168    if !RE_SHA40.is_match(&commit) {
169        bail!("git rev-parse returned invalid SHA '{commit}'");
170    }
171
172    let _ = std::fs::remove_dir_all(tmp_dir.join(".git"));
173    Ok(commit)
174}
175
176/// Probe `git ls-remote --tags` for a tag containing `version`, preferring an
177/// exact `@<version>` / `@v<version>` (changesets) suffix.
178fn probe_remote_tag(
179    remote_url: &str,
180    version: &str,
181    token: Option<&str>,
182) -> Option<(String, Vec<String>)> {
183    let auth_url = authenticated_clone_url(remote_url, token);
184    let output = Command::new("git")
185        .args(["ls-remote", "--tags"])
186        .arg(&auth_url)
187        .stderr(std::process::Stdio::null())
188        .output()
189        .ok()?;
190    if !output.status.success() {
191        return None;
192    }
193    let text = String::from_utf8_lossy(&output.stdout);
194    let mut seen = std::collections::HashSet::new();
195    let mut matching = Vec::new();
196    for line in text.lines() {
197        // Strip everything up to and including `refs/tags/`, and a peeled `^{}`.
198        let Some(idx) = line.find("refs/tags/") else {
199            continue;
200        };
201        let tag = line[idx + "refs/tags/".len()..].trim_end_matches("^{}");
202        if tag.is_empty() || !tag.contains(version) {
203            continue;
204        }
205        if seen.insert(tag.to_string()) {
206            matching.push(tag.to_string());
207        }
208    }
209    if matching.is_empty() {
210        return None;
211    }
212    let exact = matching
213        .iter()
214        .find(|t| t.ends_with(&format!("@{version}")) || t.ends_with(&format!("@v{version}")))
215        .cloned();
216    Some((exact.unwrap_or_else(|| matching[0].clone()), matching))
217}
218
219/// Try each ref candidate; on total failure probe remote tags (tag requests
220/// only). Returns `(commit, winning_candidate)`.
221fn clone_at_tag(
222    remote_url: &str,
223    reference: &str,
224    tmp_dir: &Path,
225    extra: &[String],
226    tag_only: bool,
227    tail: &[String],
228    token: Option<&str>,
229) -> Result<(String, String)> {
230    let candidates = ref_candidates(reference, extra, tail);
231    let mut last_err = String::from("no candidates");
232    for candidate in &candidates {
233        match shallow_clone_ref(remote_url, candidate, tmp_dir, token) {
234            Ok(commit) => return Ok((commit, candidate.clone())),
235            Err(e) => last_err = e.to_string(),
236        }
237    }
238
239    if !tag_only {
240        bail!(
241            "Failed to clone {remote_url} at {reference} (tried: {}): {last_err}",
242            candidates.join(", ")
243        );
244    }
245
246    let version_for_probe = reference.strip_prefix('v').unwrap_or(reference);
247    if let Some((discovered, all_matching)) = probe_remote_tag(remote_url, version_for_probe, token)
248    {
249        match shallow_clone_ref(remote_url, &discovered, tmp_dir, token) {
250            Ok(commit) => return Ok((commit, discovered)),
251            Err(clone_err) => bail!(
252                "Failed to clone {remote_url} at {reference} (tried: {}). Available tags matching \
253                 '{version_for_probe}': {}. Clone error: {clone_err}. Retry with: \
254                 ask src github:<repo>@{discovered}",
255                candidates.join(", "),
256                all_matching.join(", ")
257            ),
258        }
259    }
260
261    bail!(
262        "Failed to clone {remote_url} at {reference} (tried: {}): {last_err}",
263        candidates.join(", ")
264    );
265}
266
267/// Fetch docs for a github entry, materializing the checkout into the store.
268pub fn fetch(
269    client: &dyn HttpClient,
270    opts: &GithubOptions,
271    ask_home: &Path,
272) -> Result<FetchResult> {
273    let is_default_ref = opts.tag.is_none() && opts.branch.is_none();
274    let reference = opts
275        .tag
276        .clone()
277        .or_else(|| opts.branch.clone())
278        .unwrap_or_else(|| "main".into());
279    let (owner, repo_name) = opts
280        .repo
281        .split_once('/')
282        .ok_or_else(|| anyhow::anyhow!("Invalid repo '{}': must be owner/repo", opts.repo))?;
283
284    if !RE_SAFE_REPO.is_match(&opts.repo) {
285        bail!(
286            "Invalid repo '{}': must be owner/repo with safe characters",
287            opts.repo
288        );
289    }
290    if !RE_SAFE_REF.is_match(&reference) {
291        bail!("Invalid ref '{reference}': must contain only [A-Za-z0-9._/@-]");
292    }
293
294    let tag_version = opts
295        .tag
296        .as_deref()
297        .map(|t| t.strip_prefix('v').unwrap_or(t).to_string());
298    let resolved_version = tag_version.unwrap_or_else(|| opts.version.clone());
299    let tail: Vec<String> = if is_default_ref {
300        DEFAULT_BRANCH_FALLBACKS
301            .iter()
302            .map(|s| s.to_string())
303            .collect()
304    } else {
305        Vec::new()
306    };
307
308    // Store-hit path: check each candidate key, verify, quarantine on tamper.
309    for candidate in ref_candidates(&reference, &opts.fallback_refs, &tail) {
310        let store_dir =
311            github_store_path(ask_home, DEFAULT_GITHUB_HOST, owner, repo_name, &candidate)?;
312        if !store_dir.exists() {
313            continue;
314        }
315        if verify_entry(&store_dir) {
316            let files = if opts.skip_doc_extraction {
317                Vec::new()
318            } else {
319                extract_docs_from_dir(
320                    &store_dir,
321                    &opts.repo,
322                    &reference,
323                    opts.docs_path.as_deref(),
324                    GITHUB_DOC_CANDIDATES,
325                )?
326            };
327            return Ok(FetchResult {
328                files,
329                resolved_version,
330                store_path: Some(store_dir),
331                store_subpath: opts.docs_path.clone(),
332                from_store_cache: true,
333                meta: FetchMeta {
334                    ref_: Some(reference.clone()),
335                    ..Default::default()
336                },
337            });
338        }
339        quarantine_entry(ask_home, &store_dir);
340    }
341
342    let remote_url = opts
343        .remote_url
344        .clone()
345        .unwrap_or_else(|| format!("https://github.com/{}.git", opts.repo));
346
347    if has_git() {
348        match fetch_via_shallow_clone(
349            opts,
350            owner,
351            repo_name,
352            &reference,
353            &resolved_version,
354            &remote_url,
355            ask_home,
356            &tail,
357        ) {
358            Ok(result) => return Ok(result),
359            Err(e) => {
360                eprintln!(
361                    "  Warning: git clone failed for {}@{reference}: {e}. Falling back to tar.gz download.",
362                    opts.repo
363                );
364            }
365        }
366    }
367
368    fetch_from_tar_gz(
369        client,
370        opts,
371        owner,
372        repo_name,
373        &reference,
374        &resolved_version,
375        ask_home,
376        &tail,
377    )
378}
379
380#[allow(clippy::too_many_arguments)]
381fn fetch_via_shallow_clone(
382    opts: &GithubOptions,
383    owner: &str,
384    repo_name: &str,
385    reference: &str,
386    resolved_version: &str,
387    remote_url: &str,
388    ask_home: &Path,
389    tail: &[String],
390) -> Result<FetchResult> {
391    let token = github_token();
392    let tmp = tempfile::Builder::new().prefix("ask-gh-clone-").tempdir()?;
393    let (commit, winning) = clone_at_tag(
394        remote_url,
395        reference,
396        tmp.path(),
397        &opts.fallback_refs,
398        opts.tag.is_some(),
399        tail,
400        token.as_deref(),
401    )?;
402    let store_dir = github_store_path(ask_home, DEFAULT_GITHUB_HOST, owner, repo_name, &winning)?;
403
404    if let Some(lock) = acquire_entry_lock(&store_dir)? {
405        if let Some(parent) = store_dir.parent() {
406            std::fs::create_dir_all(parent)?;
407        }
408        cp_dir_atomic(tmp.path(), &store_dir)?;
409        stamp_entry(&store_dir)?;
410        drop(lock);
411    }
412
413    let files = if opts.skip_doc_extraction {
414        Vec::new()
415    } else {
416        extract_docs_from_dir(
417            &store_dir,
418            &opts.repo,
419            reference,
420            opts.docs_path.as_deref(),
421            GITHUB_DOC_CANDIDATES,
422        )?
423    };
424    Ok(FetchResult {
425        files,
426        resolved_version: resolved_version.to_string(),
427        store_path: Some(store_dir),
428        store_subpath: opts.docs_path.clone(),
429        from_store_cache: false,
430        meta: FetchMeta {
431            commit: Some(commit),
432            ref_: Some(winning),
433            ..Default::default()
434        },
435    })
436}
437
438#[allow(clippy::too_many_arguments)]
439fn fetch_from_tar_gz(
440    client: &dyn HttpClient,
441    opts: &GithubOptions,
442    owner: &str,
443    repo_name: &str,
444    reference: &str,
445    resolved_version: &str,
446    ask_home: &Path,
447    tail: &[String],
448) -> Result<FetchResult> {
449    let token = github_token();
450    let candidates = ref_candidates(reference, &opts.fallback_refs, tail);
451    let tmp = tempfile::Builder::new().prefix("ask-gh-tar-").tempdir()?;
452    let mut last_err = String::from("no candidates");
453
454    for candidate in &candidates {
455        let is_tag_candidate = opts.tag.is_some() && !tail.iter().any(|t| t == candidate);
456        let archive_url = if token.is_some() {
457            format!(
458                "https://api.github.com/repos/{}/tarball/{candidate}",
459                opts.repo
460            )
461        } else {
462            let kind = if is_tag_candidate { "tags" } else { "heads" };
463            format!(
464                "https://github.com/{}/archive/refs/{kind}/{candidate}.tar.gz",
465                opts.repo
466            )
467        };
468        let auth_header = token
469            .as_ref()
470            .map(|t| ("Authorization", format!("Bearer {t}")));
471        let headers: Vec<(&str, &str)> = auth_header
472            .as_ref()
473            .map(|(k, v)| vec![(*k, v.as_str())])
474            .unwrap_or_default();
475
476        let response = match client.get_bytes(&archive_url, &headers) {
477            Ok(r) => r,
478            Err(e) => {
479                last_err = e.to_string();
480                continue;
481            }
482        };
483        if !response.ok() {
484            last_err = format!("Failed to download {archive_url}: HTTP {}", response.status);
485            continue;
486        }
487
488        clear_dir_contents(tmp.path());
489        if let Err(e) = unpack_tar_gz(&response.body, tmp.path()) {
490            last_err = format!("tar extraction failed for {}@{candidate}: {e}", opts.repo);
491            clear_dir_contents(tmp.path());
492            continue;
493        }
494        let extracted_dir = match std::fs::read_dir(tmp.path())?.flatten().next() {
495            Some(entry) => entry.path(),
496            None => bail!("Failed to extract archive from {}@{candidate}", opts.repo),
497        };
498
499        let store_dir =
500            github_store_path(ask_home, DEFAULT_GITHUB_HOST, owner, repo_name, candidate)?;
501        if let Some(lock) = acquire_entry_lock(&store_dir)? {
502            if let Some(parent) = store_dir.parent() {
503                std::fs::create_dir_all(parent)?;
504            }
505            cp_dir_atomic(&extracted_dir, &store_dir)?;
506            stamp_entry(&store_dir)?;
507            drop(lock);
508        }
509
510        let files = if opts.skip_doc_extraction {
511            Vec::new()
512        } else {
513            extract_docs_from_dir(
514                &store_dir,
515                &opts.repo,
516                candidate,
517                opts.docs_path.as_deref(),
518                GITHUB_DOC_CANDIDATES,
519            )?
520        };
521        return Ok(FetchResult {
522            files,
523            resolved_version: resolved_version.to_string(),
524            store_path: Some(store_dir),
525            store_subpath: opts.docs_path.clone(),
526            from_store_cache: false,
527            meta: FetchMeta {
528                ref_: Some(candidate.clone()),
529                ..Default::default()
530            },
531        });
532    }
533
534    bail!(
535        "Failed to download tar.gz for {}@{reference} (tried: {}): {last_err}",
536        opts.repo,
537        candidates.join(", ")
538    );
539}
540
541fn unpack_tar_gz(bytes: &[u8], dest: &Path) -> Result<()> {
542    let decoder = GzDecoder::new(Cursor::new(bytes));
543    let mut archive = tar::Archive::new(decoder);
544    archive.unpack(dest)?;
545    Ok(())
546}
547
548#[cfg(test)]
549mod tests {
550    use super::*;
551
552    const TOKEN: &str = "ghp_test_token";
553
554    // ── authenticated_clone_url (opensrc #52 + #66 parity) ──────────
555
556    #[test]
557    fn auth_url_injects_on_exact_github_host() {
558        assert_eq!(
559            authenticated_clone_url("https://github.com/owner/repo.git", Some(TOKEN)),
560            format!("https://x-access-token:{TOKEN}@github.com/owner/repo.git")
561        );
562    }
563
564    #[test]
565    fn auth_url_case_insensitive_host() {
566        assert!(
567            authenticated_clone_url("https://GitHub.com/owner/repo.git", Some(TOKEN))
568                .contains(&format!("x-access-token:{TOKEN}@"))
569        );
570    }
571
572    #[test]
573    fn auth_url_no_token_unchanged() {
574        assert_eq!(
575            authenticated_clone_url("https://github.com/owner/repo.git", None),
576            "https://github.com/owner/repo.git"
577        );
578        assert_eq!(
579            authenticated_clone_url("https://github.com/owner/repo.git", Some("")),
580            "https://github.com/owner/repo.git"
581        );
582    }
583
584    #[test]
585    fn auth_url_rejects_host_confusion_and_schemes() {
586        for url in [
587            "https://github.com.evil.com/owner/repo.git",
588            "https://evilgithub.com/owner/repo.git",
589            "https://gist.github.com/owner/repo.git",
590            "http://github.com/owner/repo.git",
591            "git://github.com/owner/repo.git",
592            "git@github.com:owner/repo.git",
593            "not a url",
594        ] {
595            assert_eq!(authenticated_clone_url(url, Some(TOKEN)), url, "{url}");
596        }
597    }
598
599    #[test]
600    fn redact_token_scrubs_all_occurrences() {
601        assert_eq!(
602            redact_token("a ghp_x b ghp_x", Some("ghp_x")),
603            "a *** b ***"
604        );
605        assert_eq!(
606            redact_token("no token here", Some("ghp_x")),
607            "no token here"
608        );
609        assert_eq!(redact_token("keep ghp_x", None), "keep ghp_x");
610    }
611
612    // ── ref_candidates ───────────────────────────────────────────────
613
614    #[test]
615    fn ref_candidates_base_chain() {
616        assert_eq!(ref_candidates("1.0.0", &[], &[]), vec!["1.0.0", "v1.0.0"]);
617        assert_eq!(ref_candidates("v1.0.0", &[], &[]), vec!["v1.0.0"]);
618    }
619
620    #[test]
621    fn ref_candidates_dedup_extra_and_tail() {
622        let extra = vec!["ai@6.0.0".to_string()];
623        let tail = vec!["master".to_string()];
624        assert_eq!(
625            ref_candidates("main", &extra, &tail),
626            vec!["ai@6.0.0", "main", "vmain", "master"]
627        );
628        // Duplicate across extra/base is dropped (first wins).
629        assert_eq!(ref_candidates("v1", &["v1".to_string()], &[]), vec!["v1"]);
630    }
631
632    // ── end-to-end clone against a local git repo (offline) ─────────
633
634    fn git(args: &[&str], cwd: &Path) {
635        let status = Command::new("git")
636            .args(args)
637            .current_dir(cwd)
638            .stdout(std::process::Stdio::null())
639            .stderr(std::process::Stdio::null())
640            .status()
641            .unwrap();
642        assert!(status.success(), "git {args:?} failed");
643    }
644
645    /// Build a local bare repo with tags v1.0.0, v2.0.0, and a bare 3.0.0, each
646    /// with a `docs/guide.md`. Returns the bare repo path (a valid clone remote).
647    fn create_local_remote(tmp: &Path) -> std::path::PathBuf {
648        let work = tmp.join("work");
649        let bare = tmp.join("local-remote.git");
650        std::fs::create_dir_all(&work).unwrap();
651        git(&["init", "-b", "main", "."], &work);
652        git(&["config", "user.email", "t@t.com"], &work);
653        git(&["config", "user.name", "T"], &work);
654        git(&["config", "commit.gpgsign", "false"], &work);
655        git(&["config", "tag.gpgsign", "false"], &work);
656        std::fs::write(work.join("README.md"), "# Test Repo\n").unwrap();
657        std::fs::create_dir_all(work.join("docs")).unwrap();
658
659        std::fs::write(work.join("docs/guide.md"), "# Guide v1\n").unwrap();
660        git(&["add", "-A"], &work);
661        git(&["commit", "-m", "initial"], &work);
662        git(&["tag", "v1.0.0"], &work);
663
664        std::fs::write(work.join("docs/guide.md"), "# Guide v2\n").unwrap();
665        git(&["add", "-A"], &work);
666        git(&["commit", "-m", "update"], &work);
667        git(&["tag", "v2.0.0"], &work);
668
669        std::fs::write(work.join("docs/guide.md"), "# Guide v3\n").unwrap();
670        git(&["add", "-A"], &work);
671        git(&["commit", "-m", "bare-tag"], &work);
672        git(&["tag", "3.0.0"], &work);
673
674        git(
675            &[
676                "clone",
677                "--bare",
678                work.to_str().unwrap(),
679                bare.to_str().unwrap(),
680            ],
681            tmp,
682        );
683        bare
684    }
685
686    fn no_client() -> crate::http::mock::MockClient {
687        crate::http::mock::MockClient::new()
688    }
689
690    #[test]
691    fn clone_materializes_v_prefixed_tag_into_nested_store() {
692        if !has_git() {
693            return;
694        }
695        let tmp = tempfile::tempdir().unwrap();
696        let remote = create_local_remote(tmp.path());
697        let ask_home = tmp.path().join("ask-home");
698        let opts = GithubOptions {
699            name: "test-repo".into(),
700            version: "1.0.0".into(),
701            repo: "test/repo".into(),
702            tag: Some("v1.0.0".into()),
703            docs_path: Some("docs".into()),
704            remote_url: Some(remote.to_string_lossy().into_owned()),
705            ..Default::default()
706        };
707        let result = fetch(&no_client(), &opts, &ask_home).unwrap();
708
709        let expected = ask_home.join("github/github.com/test/repo/v1.0.0");
710        assert_eq!(result.store_path.as_deref(), Some(expected.as_path()));
711        assert_eq!(result.store_subpath.as_deref(), Some("docs"));
712        assert!(expected.join("README.md").exists());
713        assert_eq!(
714            std::fs::read_to_string(expected.join("docs/guide.md")).unwrap(),
715            "# Guide v1\n"
716        );
717        // .git stripped, commit captured, entry verifies.
718        assert!(!expected.join(".git").exists());
719        assert!(RE_SHA40.is_match(result.meta.commit.as_deref().unwrap()));
720        assert!(verify_entry(&expected));
721        assert_eq!(result.files.len(), 1);
722    }
723
724    #[test]
725    fn clone_bare_tag_via_v_fallback_lands_under_requested_key() {
726        if !has_git() {
727            return;
728        }
729        let tmp = tempfile::tempdir().unwrap();
730        let remote = create_local_remote(tmp.path());
731        let ask_home = tmp.path().join("ask-home");
732        // Request `3.0.0`; only a bare `3.0.0` tag exists (no `v3.0.0`), so the
733        // as-is candidate wins and the store key is `3.0.0`.
734        let opts = GithubOptions {
735            name: "r".into(),
736            version: "3.0.0".into(),
737            repo: "test/repo".into(),
738            tag: Some("3.0.0".into()),
739            docs_path: Some("docs".into()),
740            remote_url: Some(remote.to_string_lossy().into_owned()),
741            ..Default::default()
742        };
743        let result = fetch(&no_client(), &opts, &ask_home).unwrap();
744        assert!(result
745            .store_path
746            .as_deref()
747            .unwrap()
748            .ends_with("test/repo/3.0.0"));
749        assert_eq!(
750            std::fs::read_to_string(result.store_path.unwrap().join("docs/guide.md")).unwrap(),
751            "# Guide v3\n"
752        );
753    }
754
755    #[test]
756    fn second_fetch_hits_the_store_cache() {
757        if !has_git() {
758            return;
759        }
760        let tmp = tempfile::tempdir().unwrap();
761        let remote = create_local_remote(tmp.path());
762        let ask_home = tmp.path().join("ask-home");
763        let opts = GithubOptions {
764            name: "r".into(),
765            version: "1.0.0".into(),
766            repo: "test/repo".into(),
767            tag: Some("v1.0.0".into()),
768            docs_path: Some("docs".into()),
769            remote_url: Some(remote.to_string_lossy().into_owned()),
770            ..Default::default()
771        };
772        fetch(&no_client(), &opts, &ask_home).unwrap();
773        // Second call: remote_url pointed at a now-removed path would fail a
774        // fresh clone, so a success proves the store-cache short-circuit fired.
775        std::fs::remove_dir_all(&remote).unwrap();
776        let second = fetch(&no_client(), &opts, &ask_home).unwrap();
777        assert!(second.from_store_cache);
778        assert_eq!(second.files.len(), 1);
779    }
780
781    #[test]
782    fn invalid_repo_and_ref_rejected() {
783        let ask_home = tempfile::tempdir().unwrap();
784        let bad_repo = GithubOptions {
785            repo: "not-a-repo".into(),
786            ..Default::default()
787        };
788        assert!(fetch(&no_client(), &bad_repo, ask_home.path()).is_err());
789    }
790}