Skip to main content

ask/commands/
fetch.rs

1//! `ask fetch <spec...>` — warm the source cache for one or more specs without
2//! printing paths. Rust port of `commands/fetch.ts` (itself ported from
3//! opensrc's `opensrc fetch`, vercel-labs/opensrc#53).
4//!
5//! Per-spec failures are reported and the remaining specs still run; the CLI
6//! exits non-zero at the end if any spec failed. `run_fetch` returns a
7//! structured report so the streaming/exit behaviour is unit-testable offline.
8
9use std::path::PathBuf;
10
11use crate::commands::ensure_checkout::{
12    ensure_checkout, EnsureCheckoutDeps, EnsureCheckoutOptions,
13};
14use crate::http::HttpClient;
15
16/// Options for [`run_fetch`].
17#[derive(Debug, Clone)]
18pub struct RunFetchOptions {
19    pub specs: Vec<String>,
20    pub project_dir: PathBuf,
21    pub quiet: bool,
22}
23
24/// Outcome of [`run_fetch`]. The CLI writes `stdout` lines to stdout, `stderr`
25/// lines to stderr, and exits non-zero when `had_errors`.
26#[derive(Debug, Default, PartialEq, Eq)]
27pub struct FetchReport {
28    pub stdout: Vec<String>,
29    pub stderr: Vec<String>,
30    pub had_errors: bool,
31}
32
33/// Warm the cache for each spec via the shared checkout helper.
34pub fn run_fetch(client: &dyn HttpClient, options: &RunFetchOptions) -> FetchReport {
35    run_fetch_with(client, options, &EnsureCheckoutDeps::default())
36}
37
38/// [`run_fetch`] with injectable checkout deps.
39pub fn run_fetch_with(
40    client: &dyn HttpClient,
41    options: &RunFetchOptions,
42    deps: &EnsureCheckoutDeps,
43) -> FetchReport {
44    let mut report = FetchReport::default();
45    let mut fetched = 0usize;
46    let mut cached = 0usize;
47
48    for spec in &options.specs {
49        match ensure_checkout(
50            client,
51            &EnsureCheckoutOptions {
52                spec: spec.clone(),
53                project_dir: options.project_dir.clone(),
54                no_fetch: false,
55            },
56            deps,
57        ) {
58            Ok(result) => {
59                // Avoid `spec@ref` duplication when the user already pinned the
60                // ref in the spec itself (e.g. `github:owner/repo@v1.2.3`).
61                let suffix = format!("@{}", result.reference);
62                let display = if spec.ends_with(&suffix) {
63                    spec.clone()
64                } else {
65                    format!("{spec}{suffix}")
66                };
67                let path = result.checkout_dir.to_string_lossy();
68                if result.from_cache {
69                    cached += 1;
70                    if !options.quiet {
71                        report
72                            .stdout
73                            .push(format!("  ✓ {display} already cached ({path})"));
74                    }
75                } else {
76                    fetched += 1;
77                    if !options.quiet {
78                        report
79                            .stdout
80                            .push(format!("  ✓ Fetched {display} ({path})"));
81                    }
82                }
83            }
84            Err(err) => {
85                report.had_errors = true;
86                report.stderr.push(format!("  ✗ {spec}: {err}"));
87            }
88        }
89    }
90
91    if !options.quiet {
92        let mut parts: Vec<String> = Vec::new();
93        if fetched > 0 {
94            parts.push(format!("{fetched} fetched"));
95        }
96        if cached > 0 {
97            parts.push(format!("{cached} already cached"));
98        }
99        if !parts.is_empty() {
100            report.stdout.push(format!("\n{}", parts.join(", ")));
101        }
102    }
103
104    report
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::http::mock::MockClient;
111    use crate::store::github_store_path;
112
113    fn deps_home(home: &std::path::Path) -> EnsureCheckoutDeps<'static> {
114        EnsureCheckoutDeps {
115            ask_home: Some(home.to_path_buf()),
116            fetcher: None,
117        }
118    }
119
120    #[test]
121    fn reports_already_cached_without_duplicating_ref() {
122        let home = tempfile::tempdir().unwrap();
123        let proj = tempfile::tempdir().unwrap();
124        let dir = github_store_path(home.path(), "github.com", "owner", "repo", "v1.2.3").unwrap();
125        std::fs::create_dir_all(&dir).unwrap();
126        let report = run_fetch_with(
127            &MockClient::new(),
128            &RunFetchOptions {
129                specs: vec!["github:owner/repo@v1.2.3".into()],
130                project_dir: proj.path().to_path_buf(),
131                quiet: false,
132            },
133            &deps_home(home.path()),
134        );
135        assert!(!report.had_errors);
136        // The spec already ends with @v1.2.3 — no `@v1.2.3@v1.2.3` duplication.
137        assert!(report.stdout[0].contains("github:owner/repo@v1.2.3 already cached"));
138        assert!(!report.stdout[0].contains("v1.2.3@v1.2.3"));
139        assert!(report.stdout.last().unwrap().contains("1 already cached"));
140    }
141
142    #[test]
143    fn per_spec_failure_sets_error_and_continues() {
144        let home = tempfile::tempdir().unwrap();
145        let proj = tempfile::tempdir().unwrap();
146        // First spec resolves (cache hit); second is an unsupported ecosystem.
147        let dir = github_store_path(home.path(), "github.com", "owner", "repo", "v1.0.0").unwrap();
148        std::fs::create_dir_all(&dir).unwrap();
149        let report = run_fetch_with(
150            &MockClient::new(),
151            &RunFetchOptions {
152                specs: vec![
153                    "github:owner/repo@v1.0.0".into(),
154                    "cargo:serde".into(), // no resolver for cargo
155                ],
156                project_dir: proj.path().to_path_buf(),
157                quiet: false,
158            },
159            &deps_home(home.path()),
160        );
161        assert!(report.had_errors);
162        assert_eq!(report.stderr.len(), 1);
163        assert!(report.stderr[0].contains("cargo:serde"));
164        // The good spec still succeeded.
165        assert!(report.stdout.iter().any(|l| l.contains("already cached")));
166    }
167
168    #[test]
169    fn quiet_suppresses_stdout_but_keeps_errors() {
170        let home = tempfile::tempdir().unwrap();
171        let proj = tempfile::tempdir().unwrap();
172        let report = run_fetch_with(
173            &MockClient::new(),
174            &RunFetchOptions {
175                specs: vec!["cargo:serde".into()],
176                project_dir: proj.path().to_path_buf(),
177                quiet: true,
178            },
179            &deps_home(home.path()),
180        );
181        assert!(report.had_errors);
182        assert!(report.stdout.is_empty());
183        assert_eq!(report.stderr.len(), 1);
184    }
185}