Skip to main content

ask/commands/
src.rs

1//! `ask src <spec>` — print the absolute path to a cached library source tree,
2//! fetching on cache miss unless `--no-fetch`. Rust port of `commands/src.ts`.
3//!
4//! `run_src` returns the exact stdout string on success and an error on failure;
5//! the thin CLI wrapper prints it and maps any error to a non-zero exit. This
6//! keeps the resolution logic unit-testable without process exits or real I/O.
7
8use std::path::PathBuf;
9
10use anyhow::Result;
11use serde::Serialize;
12
13use crate::commands::ensure_checkout::{
14    ensure_checkout, EnsureCheckoutDeps, EnsureCheckoutOptions,
15};
16use crate::http::HttpClient;
17
18/// Options for [`run_src`].
19#[derive(Debug, Clone)]
20pub struct RunSrcOptions {
21    pub spec: String,
22    pub project_dir: PathBuf,
23    pub no_fetch: bool,
24    pub json: bool,
25}
26
27/// `ask src <spec> --json` output — the stable machine-readable handoff that
28/// downstream tools (e.g. csp) consume. `checkout_dir` is the version-pinned,
29/// content-stable store path they index. Mirrors `SrcModelSchema`.
30#[derive(Debug, Serialize, PartialEq, Eq)]
31pub struct SrcModel {
32    pub spec: String,
33    pub owner: String,
34    pub repo: String,
35    #[serde(rename = "ref")]
36    pub reference: String,
37    #[serde(rename = "resolvedVersion")]
38    pub resolved_version: String,
39    #[serde(rename = "checkoutDir")]
40    pub checkout_dir: String,
41    #[serde(rename = "npmPackageName")]
42    pub npm_package_name: Option<String>,
43}
44
45/// Resolve `spec` via the shared checkout helper and return the text to print:
46/// the checkout path (default) or a JSON [`SrcModel`] (`json`). On a
47/// `NoCacheError` or any resolver failure this returns an error whose message
48/// the CLI writes to stderr before exiting non-zero — matching the TS behaviour
49/// where both cases route through `error()` + `exit(1)`.
50pub fn run_src(client: &dyn HttpClient, options: &RunSrcOptions) -> Result<String> {
51    run_src_with(client, options, &EnsureCheckoutDeps::default())
52}
53
54/// [`run_src`] with injectable checkout deps (tests pass an offline fetcher /
55/// overridden ASK home).
56pub fn run_src_with(
57    client: &dyn HttpClient,
58    options: &RunSrcOptions,
59    deps: &EnsureCheckoutDeps,
60) -> Result<String> {
61    let result = ensure_checkout(
62        client,
63        &EnsureCheckoutOptions {
64            spec: options.spec.clone(),
65            project_dir: options.project_dir.clone(),
66            no_fetch: options.no_fetch,
67        },
68        deps,
69    )?;
70
71    if options.json {
72        let model = SrcModel {
73            spec: options.spec.clone(),
74            owner: result.owner,
75            repo: result.repo,
76            reference: result.reference,
77            resolved_version: result.resolved_version,
78            checkout_dir: result.checkout_dir.to_string_lossy().into_owned(),
79            npm_package_name: result.npm_package_name,
80        };
81        Ok(serde_json::to_string_pretty(&model)?)
82    } else {
83        Ok(result.checkout_dir.to_string_lossy().into_owned())
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90    use crate::commands::ensure_checkout::NoCacheError;
91    use crate::http::mock::MockClient;
92    use crate::store::github_store_path;
93
94    fn deps_home(home: &std::path::Path) -> EnsureCheckoutDeps<'static> {
95        EnsureCheckoutDeps {
96            ask_home: Some(home.to_path_buf()),
97            fetcher: None,
98        }
99    }
100
101    #[test]
102    fn prints_checkout_dir_on_cache_hit() {
103        let home = tempfile::tempdir().unwrap();
104        let proj = tempfile::tempdir().unwrap();
105        let dir =
106            github_store_path(home.path(), "github.com", "facebook", "react", "v18.2.0").unwrap();
107        std::fs::create_dir_all(&dir).unwrap();
108        let out = run_src_with(
109            &MockClient::new(),
110            &RunSrcOptions {
111                spec: "github:facebook/react@v18.2.0".into(),
112                project_dir: proj.path().to_path_buf(),
113                no_fetch: false,
114                json: false,
115            },
116            &deps_home(home.path()),
117        )
118        .unwrap();
119        assert_eq!(out, dir.to_string_lossy());
120    }
121
122    #[test]
123    fn json_output_matches_schema_field_names() {
124        let home = tempfile::tempdir().unwrap();
125        let proj = tempfile::tempdir().unwrap();
126        let dir =
127            github_store_path(home.path(), "github.com", "facebook", "react", "v18.2.0").unwrap();
128        std::fs::create_dir_all(&dir).unwrap();
129        let out = run_src_with(
130            &MockClient::new(),
131            &RunSrcOptions {
132                spec: "github:facebook/react@v18.2.0".into(),
133                project_dir: proj.path().to_path_buf(),
134                no_fetch: false,
135                json: true,
136            },
137            &deps_home(home.path()),
138        )
139        .unwrap();
140        assert!(out.contains(r#""ref": "v18.2.0""#));
141        assert!(out.contains(r#""resolvedVersion": "v18.2.0""#));
142        assert!(out.contains(r#""npmPackageName": null"#));
143        assert!(out.contains(r#""checkoutDir""#));
144    }
145
146    #[test]
147    fn no_cache_error_propagates() {
148        let home = tempfile::tempdir().unwrap();
149        let proj = tempfile::tempdir().unwrap();
150        let err = run_src_with(
151            &MockClient::new(),
152            &RunSrcOptions {
153                spec: "github:owner/repo@v1.2.3".into(),
154                project_dir: proj.path().to_path_buf(),
155                no_fetch: true,
156                json: false,
157            },
158            &deps_home(home.path()),
159        )
160        .unwrap_err();
161        assert!(err.downcast_ref::<NoCacheError>().is_some());
162    }
163}