Skip to main content

vtcode_core/tools/ast_grep_installer/
mod.rs

1mod archive;
2mod release;
3mod state;
4
5use std::path::PathBuf;
6
7use crate::tools::ast_grep_binary::{
8    AST_GREP_NO_INSTALL_ENV, managed_ast_grep_bin_dir, missing_ast_grep_message,
9    resolve_ast_grep_binary_from_env_and_fs,
10};
11use crate::tools::editing::patch::resolve_ast_grep_binary_path;
12use anyhow::{Context, Result, bail};
13
14use self::archive::{ast_grep_version, install_archive};
15use self::release::{
16    current_platform_asset_spec, download_release_asset, fetch_latest_release, manual_install_guide,
17    select_release_asset, verify_checksum_if_available,
18};
19use self::state::{InstallLockGuard, InstallPaths, InstallationCache};
20
21/// Manual install steps for CLI fallback messages (issue #802).
22pub fn ast_grep_manual_install_guide() -> &'static str {
23    manual_install_guide()
24}
25
26#[derive(Debug, Clone, PartialEq)]
27pub enum AstGrepStatus {
28    Available {
29        version: String,
30        binary: PathBuf,
31        managed: bool,
32    },
33    NotFound,
34    Error {
35        reason: String,
36    },
37}
38
39#[derive(Debug, Clone)]
40pub struct AstGrepInstallOutcome {
41    pub version: String,
42    pub binary_path: PathBuf,
43    pub alias_path: Option<PathBuf>,
44    pub managed_bin_dir: PathBuf,
45    pub warning: Option<String>,
46}
47
48impl AstGrepStatus {
49    pub fn check() -> Self {
50        let Some(binary) = resolve_ast_grep_binary_from_env_and_fs() else {
51            return Self::NotFound;
52        };
53
54        match ast_grep_version(&binary) {
55            Ok(version) => Self::Available {
56                version,
57                managed: managed_ast_grep_bin_dir().is_ok_and(|directory| binary.starts_with(directory)),
58                binary,
59            },
60            Err(err) => Self::Error { reason: format!("{err:#}") },
61        }
62    }
63
64    pub async fn install() -> Result<AstGrepInstallOutcome> {
65        let paths = InstallPaths::discover()?;
66        let _lock = InstallLockGuard::acquire(&paths)?;
67
68        if !InstallationCache::is_stale(&paths)
69            && let Ok(cache) = InstallationCache::load(&paths)
70            && cache.status == "failed"
71            && !cache.failure_reason.as_deref().is_some_and(should_retry_without_cooldown)
72        {
73            let reason = cache.failure_reason.as_deref().unwrap_or("unknown reason");
74            if reason.contains("manually") {
75                bail!("Previous ast-grep installation attempt failed ({reason}). Not retrying for 24 hours.");
76            }
77            bail!(
78                "Previous ast-grep installation attempt failed ({reason}). Not retrying for 24 hours.\n{}",
79                manual_install_guide()
80            );
81        }
82
83        let install_result: Result<AstGrepInstallOutcome> = async {
84            let client = reqwest::Client::builder()
85                .user_agent("vtcode-ast-grep-installer")
86                .build()
87                .context("Failed to create HTTP client")?;
88
89            let release = fetch_latest_release(&client).await?;
90            let platform = current_platform_asset_spec()?;
91            let selected_asset = select_release_asset(&release, &platform)?;
92            let archive_bytes = download_release_asset(&client, &selected_asset.asset).await?;
93            let warning = verify_checksum_if_available(&client, &release, &selected_asset, &archive_bytes).await?;
94
95            install_archive(&paths, &selected_asset.asset.name, &archive_bytes)?;
96            let version = ast_grep_version(&paths.binary_path).context("Installed ast-grep failed version check")?;
97            InstallationCache::mark_success(&paths, &selected_asset.tag_name);
98
99            Ok(AstGrepInstallOutcome {
100                version,
101                binary_path: paths.binary_path.clone(),
102                alias_path: paths.alias_path.clone(),
103                managed_bin_dir: paths.bin_dir.clone(),
104                warning,
105            })
106        }
107        .await;
108
109        match install_result {
110            Ok(outcome) => Ok(outcome),
111            Err(err) => {
112                InstallationCache::mark_failure(&paths, &err.to_string());
113                Err(err)
114            }
115        }
116    }
117
118    /// Resolve the ast-grep binary path, auto-installing on first use when the
119    /// binary is missing. Used by `structural` and `outline` search actions so
120    /// the model does not need to run `vtcode dependencies install ast-grep`
121    /// manually before the first structural/outline call.
122    ///
123    /// Skips auto-install (returns the standard "not available" error) when:
124    /// - the test override forces `Missing` (unit tests),
125    /// - `VTCODE_AST_GREP_NO_INSTALL` is set (user opt-out).
126    ///
127    /// On install failure, returns `"ast-grep is not available; auto-install
128    /// failed: {error}"` so the structural grep-fallback substring check
129    /// (`msg.contains("ast-grep") && msg.contains("not available")`) still
130    /// triggers for query/count workflows.
131    pub async fn resolve_or_install() -> std::result::Result<PathBuf, String> {
132        // Use an already-resolved binary regardless of the opt-out env var:
133        // `VTCODE_AST_GREP_NO_INSTALL` only disables auto-install, not usage of
134        // an already-present binary.
135        if let Ok(path) = resolve_ast_grep_binary_path() {
136            return Ok(path);
137        }
138
139        // No binary available. If the user opted out of auto-install, surface
140        // the missing-binary error immediately without attempting a download.
141        if std::env::var_os(AST_GREP_NO_INSTALL_ENV).is_some() {
142            return Err(missing_ast_grep_message("Auto-install disabled via VTCODE_AST_GREP_NO_INSTALL."));
143        }
144
145        // Skip auto-install in test mode when either override registry forces
146        // the binary to be missing. Both are checked because
147        // `resolve_ast_grep_binary_path` consults the patch (semantic) registry
148        // first and the `ast_grep_binary` registry second.
149        if crate::tools::ast_grep_binary::is_binary_override_missing()
150            || crate::tools::editing::patch::is_binary_override_missing()
151        {
152            return Err(missing_ast_grep_message("Auto-install skipped: test override forces missing binary."));
153        }
154
155        match Self::install().await {
156            Ok(_) => match resolve_ast_grep_binary_from_env_and_fs() {
157                Some(path) => Ok(path),
158                None => {
159                    Err(missing_ast_grep_message("Auto-install reported success but the binary could not be resolved."))
160                }
161            },
162            Err(err) => Err(format!(
163                "ast-grep is not available; auto-install failed: {err}. Run `{}` manually.",
164                crate::tools::ast_grep_binary::AST_GREP_INSTALL_COMMAND
165            )),
166        }
167    }
168}
169
170fn should_retry_without_cooldown(failure_reason: &str) -> bool {
171    failure_reason.contains("No ast-grep release asset matched the current platform")
172        || failure_reason.contains("Unsupported platform for VT Code-managed ast-grep install")
173}
174
175#[cfg(test)]
176mod tests {
177    use super::{AstGrepStatus, should_retry_without_cooldown};
178    use crate::tools::ast_grep_binary::AST_GREP_INSTALL_COMMAND;
179    use crate::tools::ast_grep_binary::set_ast_grep_binary_override_for_tests;
180    use serial_test::serial;
181    use vtcode_commons::env_lock;
182
183    #[cfg(unix)]
184    #[test]
185    #[serial]
186    fn status_check_preserves_version_and_bounded_probe_causes() {
187        use std::os::unix::fs::PermissionsExt;
188        for (body, expected) in [
189            ("printf ' ast-grep 0.44.0\\n'", Ok("ast-grep 0.44.0")),
190            (":", Err("returned empty output")),
191            ("exit 7", Err("exited with status exit status: 7")),
192            ("head -c 65537 /dev/zero", Err("stdout exceeded 65536 bytes")),
193            ("exec /bin/sleep 30", Err("version probe timed out")),
194        ] {
195            let directory = tempfile::tempdir().unwrap();
196            let binary = directory.path().join("ast-grep");
197            let script = format!(
198                "#!/bin/sh\n[ \"$1\" = \"--version\" ] && [ \"$2\" = \"--color\" ] && [ \"$3\" = \"never\" ] && [ \"$NO_COLOR\" = 1 ] && [ \"$CLICOLOR\" = 0 ] || exit 9\n{body}\n"
199            );
200            std::fs::write(&binary, script).unwrap();
201            std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
202            let _override = set_ast_grep_binary_override_for_tests(Some(binary));
203            match (expected, AstGrepStatus::check()) {
204                (Ok(expected), AstGrepStatus::Available { version, .. }) => assert_eq!(version, expected),
205                (Err(expected), AstGrepStatus::Error { reason }) => assert!(reason.contains(expected), "{reason}"),
206                (expected, actual) => panic!("expected {expected:?}, got {actual:?}"),
207            }
208        }
209        let _override = set_ast_grep_binary_override_for_tests(None);
210        assert_eq!(AstGrepStatus::check(), AstGrepStatus::NotFound);
211    }
212
213    #[test]
214    fn platform_mismatch_failures_do_not_enter_cooldown() {
215        assert!(should_retry_without_cooldown(
216            "No ast-grep release asset matched the current platform (aarch64-apple-darwin)"
217        ));
218        assert!(should_retry_without_cooldown(
219            "No ast-grep release asset matched the current platform (x86_64-unknown-linux-gnu) in 0.51.1 \
220             (available: app-x86_64-apple-darwin.zip).\nInstall ast-grep manually and rerun `vtcode dependencies status ast-grep`"
221        ));
222        assert!(should_retry_without_cooldown("Unsupported platform for VT Code-managed ast-grep install"));
223    }
224
225    #[test]
226    fn unrelated_failures_still_use_cooldown() {
227        assert!(!should_retry_without_cooldown("Failed to fetch ast-grep release metadata"));
228    }
229
230    #[tokio::test]
231    #[serial]
232    async fn resolve_or_install_skips_install_when_test_override_missing() {
233        let _guard = set_ast_grep_binary_override_for_tests(None);
234        let err = AstGrepStatus::resolve_or_install()
235            .await
236            .expect_err("should not install in test mode");
237        let text = err.to_string();
238        assert!(text.contains("ast-grep"), "{text}");
239        assert!(text.contains("not available"), "{text}");
240        assert!(text.contains(AST_GREP_INSTALL_COMMAND), "{text}");
241    }
242
243    #[tokio::test]
244    #[serial]
245    async fn resolve_or_install_mentions_env_optout_when_set() {
246        // Force the binary to be missing so `resolve_ast_grep_binary_path`
247        // fails and execution reaches the env-var check. The test override is
248        // checked AFTER the env var, so the env-var error wins. This keeps the
249        // test portable across machines that happen to have ast-grep installed.
250        let _override = set_ast_grep_binary_override_for_tests(None);
251        let env = env_lock::lock();
252        env.set_var("VTCODE_AST_GREP_NO_INSTALL", "1");
253        let err = AstGrepStatus::resolve_or_install()
254            .await
255            .expect_err("should not install when env opt-out is set");
256        env.remove_var("VTCODE_AST_GREP_NO_INSTALL");
257        assert!(err.contains("VTCODE_AST_GREP_NO_INSTALL"), "error should mention the env var: {err}");
258    }
259}