Skip to main content

ask/commands/
docs.rs

1//! `ask docs <spec>` — print candidate documentation paths from `node_modules`
2//! and the cached source tree. Rust port of `commands/docs.ts`.
3//!
4//! Resolves the spec via the shared `ensure_checkout` helper, then emits doc-like
5//! paths (one per line, or a JSON `DocsModel` with `--json`). A persisted
6//! `docsPaths` override in ask.json, when present and non-stale, restricts output
7//! to those paths (resolved against both node_modules and the checkout).
8
9use std::path::{Path, PathBuf};
10
11use anyhow::Result;
12use serde::Serialize;
13
14use crate::commands::ensure_checkout::{
15    ensure_checkout, EnsureCheckoutDeps, EnsureCheckoutOptions,
16};
17use crate::commands::find_doc_paths::find_doc_like_paths;
18use crate::http::HttpClient;
19use crate::io::{find_entry, read_ask_json};
20use crate::store::assert_contained;
21
22/// Options for [`run_docs`].
23#[derive(Debug, Clone)]
24pub struct RunDocsOptions {
25    pub spec: String,
26    pub project_dir: PathBuf,
27    pub no_fetch: bool,
28    pub json: bool,
29}
30
31/// Which source root a candidate path came from.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
33#[serde(rename_all = "snake_case")]
34pub enum DocsRoot {
35    NodeModules,
36    Checkout,
37}
38
39/// One documentation candidate path (matches `DocsCandidateSchema`).
40#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
41pub struct DocsCandidate {
42    pub path: String,
43    pub root: DocsRoot,
44}
45
46/// `ask docs <spec> --json` output (matches `DocsModelSchema`).
47#[derive(Debug, Serialize, PartialEq, Eq)]
48pub struct DocsModel {
49    pub spec: String,
50    #[serde(rename = "npmPackageName")]
51    pub npm_package_name: Option<String>,
52    #[serde(rename = "checkoutDir")]
53    pub checkout_dir: String,
54    #[serde(rename = "storedOverride")]
55    pub stored_override: bool,
56    pub paths: Vec<DocsCandidate>,
57}
58
59/// What [`run_docs`] produces: text to print plus any non-fatal stderr warnings
60/// (e.g. all stored docsPaths were stale). The CLI prints `stdout`, writes
61/// `warnings` to stderr, and exits 0 — only a hard error (NoCacheError, resolver
62/// failure) surfaces as `Err` and maps to exit 1.
63#[derive(Debug, Default, PartialEq, Eq)]
64pub struct DocsRun {
65    pub stdout: String,
66    pub warnings: Vec<String>,
67}
68
69fn candidate_at(p: &Path, root: DocsRoot) -> DocsCandidate {
70    DocsCandidate {
71        path: p.to_string_lossy().into_owned(),
72        root,
73    }
74}
75
76/// Resolve `spec` and collect documentation candidate paths.
77pub fn run_docs(client: &dyn HttpClient, options: &RunDocsOptions) -> Result<DocsRun> {
78    run_docs_with(client, options, &EnsureCheckoutDeps::default())
79}
80
81/// [`run_docs`] with injectable checkout deps.
82pub fn run_docs_with(
83    client: &dyn HttpClient,
84    options: &RunDocsOptions,
85    deps: &EnsureCheckoutDeps,
86) -> Result<DocsRun> {
87    let result = ensure_checkout(
88        client,
89        &EnsureCheckoutOptions {
90            spec: options.spec.clone(),
91            project_dir: options.project_dir.clone(),
92            no_fetch: options.no_fetch,
93        },
94        deps,
95    )?;
96
97    let mut run = DocsRun::default();
98    let mut paths: Vec<DocsCandidate> = Vec::new();
99
100    let nm_path = result
101        .npm_package_name
102        .as_ref()
103        .map(|pkg| options.project_dir.join("node_modules").join(pkg));
104
105    // Persisted docsPaths override: emit ONLY the stored paths (resolved against
106    // both roots that `ask add` probed). Falls back to the unfiltered walk when
107    // every stored path is stale — silent empty output would be worse.
108    // Propagate an invalid ask.json rather than masking it: TS `ask docs` calls
109    // readAskJson directly (no try/catch), so a broken config surfaces a parse
110    // error instead of silently emitting the unfiltered candidate list.
111    let stored: Option<Vec<String>> = match read_ask_json(&options.project_dir)? {
112        Some(aj) => find_entry(&aj, &options.spec).and_then(|e| e.docs_paths().map(|d| d.to_vec())),
113        None => None,
114    };
115    let mut stored_override = false;
116
117    if let Some(stored) = stored.as_ref().filter(|s| !s.is_empty()) {
118        // Roots in priority order: node_modules (if present) then checkout.
119        let mut roots: Vec<(PathBuf, DocsRoot)> = Vec::new();
120        if let Some(nm) = nm_path.as_ref().filter(|p| p.exists()) {
121            roots.push((nm.clone(), DocsRoot::NodeModules));
122        }
123        roots.push((result.checkout_dir.clone(), DocsRoot::Checkout));
124
125        for rel in stored {
126            for (root, kind) in &roots {
127                // Containment guard: a `..`/absolute docsPaths entry must not
128                // escape its root. `join` mirrors path.resolve (absolute rel
129                // replaces root); assert_contained rejects escapes.
130                let candidate = root.join(rel);
131                let Ok(abs) = assert_contained(root, &candidate) else {
132                    continue;
133                };
134                if abs.exists() {
135                    paths.push(candidate_at(&abs, *kind));
136                    break;
137                }
138            }
139        }
140
141        if !paths.is_empty() {
142            stored_override = true;
143        } else {
144            run.warnings.push(format!(
145                "ask: stored docsPaths for {} are all stale; emitting all candidates",
146                options.spec
147            ));
148            // fall through to the default walk
149        }
150    }
151
152    if !stored_override {
153        // node_modules/<pkg>/ first when the spec is an npm package and it is
154        // actually installed. Non-npm / missing installs are silently skipped.
155        if let Some(nm) = nm_path.as_ref().filter(|p| p.exists()) {
156            for p in find_doc_like_paths(nm) {
157                paths.push(candidate_at(&p, DocsRoot::NodeModules));
158            }
159        }
160        // The cached source tree. Always emits the root as the first line even
161        // when no /doc/i subdirs are found.
162        for p in find_doc_like_paths(&result.checkout_dir) {
163            paths.push(candidate_at(&p, DocsRoot::Checkout));
164        }
165    }
166
167    run.stdout = if options.json {
168        let model = DocsModel {
169            spec: options.spec.clone(),
170            npm_package_name: result.npm_package_name.clone(),
171            checkout_dir: result.checkout_dir.to_string_lossy().into_owned(),
172            stored_override,
173            paths,
174        };
175        serde_json::to_string_pretty(&model)?
176    } else {
177        paths
178            .iter()
179            .map(|c| c.path.as_str())
180            .collect::<Vec<_>>()
181            .join("\n")
182    };
183    Ok(run)
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189    use crate::commands::ensure_checkout::NoCacheError;
190    use crate::http::mock::MockClient;
191    use crate::store::github_store_path;
192
193    fn deps_home(home: &Path) -> EnsureCheckoutDeps<'static> {
194        EnsureCheckoutDeps {
195            ask_home: Some(home.to_path_buf()),
196            fetcher: None,
197        }
198    }
199
200    /// Pre-warm a github checkout and return (home, proj, checkout_dir).
201    fn warmed() -> (tempfile::TempDir, tempfile::TempDir, PathBuf) {
202        let home = tempfile::tempdir().unwrap();
203        let proj = tempfile::tempdir().unwrap();
204        let dir = github_store_path(home.path(), "github.com", "owner", "repo", "v1.0.0").unwrap();
205        std::fs::create_dir_all(&dir).unwrap();
206        (home, proj, dir)
207    }
208
209    fn opts(spec: &str, proj: &Path, json: bool) -> RunDocsOptions {
210        RunDocsOptions {
211            spec: spec.to_string(),
212            project_dir: proj.to_path_buf(),
213            no_fetch: false,
214            json,
215        }
216    }
217
218    #[test]
219    fn emits_doc_subdir_from_checkout() {
220        let (home, proj, dir) = warmed();
221        std::fs::create_dir_all(dir.join("docs")).unwrap();
222        let run = run_docs_with(
223            &MockClient::new(),
224            &opts("github:owner/repo@v1.0.0", proj.path(), false),
225            &deps_home(home.path()),
226        )
227        .unwrap();
228        assert!(run.stdout.contains("docs"));
229        assert!(run.warnings.is_empty());
230    }
231
232    #[test]
233    fn readme_only_checkout_emits_root() {
234        let (home, proj, dir) = warmed();
235        std::fs::write(dir.join("README.md"), "x").unwrap();
236        let run = run_docs_with(
237            &MockClient::new(),
238            &opts("github:owner/repo@v1.0.0", proj.path(), false),
239            &deps_home(home.path()),
240        )
241        .unwrap();
242        assert_eq!(run.stdout, dir.to_string_lossy());
243    }
244
245    #[test]
246    fn json_model_has_schema_fields() {
247        let (home, proj, dir) = warmed();
248        std::fs::write(dir.join("README.md"), "x").unwrap();
249        let run = run_docs_with(
250            &MockClient::new(),
251            &opts("github:owner/repo@v1.0.0", proj.path(), true),
252            &deps_home(home.path()),
253        )
254        .unwrap();
255        assert!(run.stdout.contains(r#""storedOverride": false"#));
256        assert!(run.stdout.contains(r#""npmPackageName": null"#));
257        assert!(run.stdout.contains(r#""root": "checkout""#));
258        assert!(run.stdout.contains(r#""checkoutDir""#));
259    }
260
261    #[test]
262    fn stored_docs_paths_override_restricts_output() {
263        let (home, proj, dir) = warmed();
264        std::fs::create_dir_all(dir.join("docs")).unwrap();
265        std::fs::create_dir_all(dir.join("guides")).unwrap();
266        std::fs::write(dir.join("guides/intro.md"), "x").unwrap();
267        // ask.json pins docsPaths to guides/intro.md only.
268        std::fs::write(
269            proj.path().join("ask.json"),
270            r#"{"libraries":[{"spec":"github:owner/repo@v1.0.0","docsPaths":["guides/intro.md"]}]}"#,
271        )
272        .unwrap();
273        let run = run_docs_with(
274            &MockClient::new(),
275            &opts("github:owner/repo@v1.0.0", proj.path(), true),
276            &deps_home(home.path()),
277        )
278        .unwrap();
279        assert!(run.stdout.contains(r#""storedOverride": true"#));
280        assert!(run.stdout.contains("guides/intro.md"));
281        // Exactly one candidate — the override restricted output to the pin,
282        // so the unfiltered `docs` subdir walk did not run.
283        assert_eq!(run.stdout.matches(r#""path""#).count(), 1);
284    }
285
286    #[test]
287    fn stale_stored_paths_warn_and_fall_through() {
288        let (home, proj, dir) = warmed();
289        std::fs::write(dir.join("README.md"), "x").unwrap();
290        std::fs::write(
291            proj.path().join("ask.json"),
292            r#"{"libraries":[{"spec":"github:owner/repo@v1.0.0","docsPaths":["nonexistent/gone.md"]}]}"#,
293        )
294        .unwrap();
295        let run = run_docs_with(
296            &MockClient::new(),
297            &opts("github:owner/repo@v1.0.0", proj.path(), false),
298            &deps_home(home.path()),
299        )
300        .unwrap();
301        assert_eq!(run.warnings.len(), 1);
302        assert!(run.warnings[0].contains("all stale"));
303        // Fell through to the unfiltered walk → root emitted.
304        assert_eq!(run.stdout, dir.to_string_lossy());
305    }
306
307    #[test]
308    fn containment_guard_rejects_traversal() {
309        let (home, proj, dir) = warmed();
310        std::fs::write(dir.join("README.md"), "x").unwrap();
311        // A `..` escape must be rejected, so the override yields nothing → stale.
312        std::fs::write(
313            proj.path().join("ask.json"),
314            r#"{"libraries":[{"spec":"github:owner/repo@v1.0.0","docsPaths":["../../../etc/hosts"]}]}"#,
315        )
316        .unwrap();
317        let run = run_docs_with(
318            &MockClient::new(),
319            &opts("github:owner/repo@v1.0.0", proj.path(), false),
320            &deps_home(home.path()),
321        )
322        .unwrap();
323        assert_eq!(run.warnings.len(), 1);
324        assert!(!run.stdout.contains("etc/hosts"));
325    }
326
327    #[test]
328    fn no_cache_error_propagates() {
329        let home = tempfile::tempdir().unwrap();
330        let proj = tempfile::tempdir().unwrap();
331        let err = run_docs_with(
332            &MockClient::new(),
333            &RunDocsOptions {
334                spec: "github:owner/repo@v9.9.9".into(),
335                project_dir: proj.path().to_path_buf(),
336                no_fetch: true,
337                json: false,
338            },
339            &deps_home(home.path()),
340        )
341        .unwrap_err();
342        assert!(err.downcast_ref::<NoCacheError>().is_some());
343    }
344}