Skip to main content

vtcode_core/tools/ripgrep_installer/
mod.rs

1//! Ripgrep availability detection and explicit installation management.
2//!
3//! This module handles detecting if ripgrep is available and installing it on
4//! demand through `vtcode dependencies install ripgrep`.
5
6mod platform;
7mod state;
8
9use crate::tools::install_support::run_version_probe;
10use crate::tools::ripgrep_binary::RIPGREP_INSTALL_COMMAND;
11use anyhow::{Result, anyhow};
12use std::process::Command;
13
14use self::platform::{install_with_smart_detection, manual_install_guide};
15use self::state::{InstallLockGuard, InstallationCache};
16
17/// Manual install steps for CLI fallback messages (issue #802).
18pub fn ripgrep_manual_install_guide() -> &'static str {
19    manual_install_guide()
20}
21
22/// Result of ripgrep availability check
23#[derive(Debug, Clone, PartialEq)]
24pub enum RipgrepStatus {
25    /// Ripgrep is available and working
26    Available { version: String },
27    /// Ripgrep is not installed
28    NotFound,
29    /// Ripgrep exists but returned an error
30    Error { reason: String },
31}
32
33impl RipgrepStatus {
34    /// Check if ripgrep is currently available
35    pub fn check() -> Self {
36        debug_log("Checking ripgrep availability...");
37        let mut command = Command::new("rg");
38        command.arg("--version");
39        match run_version_probe(command) {
40            Ok(output) => {
41                if output.status.success() {
42                    let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
43                    if version.is_empty() {
44                        debug_log("ripgrep found but returned empty version");
45                        RipgrepStatus::Error {
46                            reason: "rg --version returned empty output".to_string(),
47                        }
48                    } else {
49                        debug_log(&format!("ripgrep available: {version}"));
50                        RipgrepStatus::Available { version }
51                    }
52                } else {
53                    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
54                    debug_log(&format!("ripgrep check failed: {stderr}"));
55                    RipgrepStatus::Error {
56                        reason: if stderr.is_empty() {
57                            "rg exited with error".to_string()
58                        } else {
59                            stderr
60                        },
61                    }
62                }
63            }
64            Err(err) => {
65                if err.kind() == std::io::ErrorKind::NotFound {
66                    debug_log("ripgrep not found in PATH");
67                    RipgrepStatus::NotFound
68                } else {
69                    debug_log(&format!("ripgrep check error: {err}"));
70                    RipgrepStatus::Error { reason: err.to_string() }
71                }
72            }
73        }
74    }
75
76    /// Attempt to install ripgrep for the current platform.
77    /// Uses smart installer detection to try available tools first.
78    pub fn install() -> Result<()> {
79        debug_log("Installation attempt started");
80
81        if matches!(Self::check(), RipgrepStatus::Available { .. }) {
82            debug_log("ripgrep already available; skipping installation");
83            return Ok(());
84        }
85
86        if std::env::var("VTCODE_RIPGREP_NO_INSTALL").is_ok() {
87            debug_log("Auto-install disabled via VTCODE_RIPGREP_NO_INSTALL");
88            return Err(anyhow!("Ripgrep auto-installation disabled via VTCODE_RIPGREP_NO_INSTALL"));
89        }
90
91        if InstallLockGuard::is_install_in_progress() {
92            debug_log("Another installation is already in progress, skipping");
93            return Err(anyhow!("Ripgrep installation already in progress"));
94        }
95
96        let _lock = InstallLockGuard::acquire()?;
97        debug_log("Installation lock acquired");
98
99        if !InstallationCache::is_stale()
100            && let Ok(cache) = InstallationCache::load()
101            && cache.status == "failed"
102        {
103            let reason = cache.failure_reason.as_deref().unwrap_or("unknown reason");
104            debug_log(&format!("Cache shows previous failure: {reason}"));
105            if reason.contains("manually") {
106                return Err(anyhow!("Previous installation attempt failed ({reason}). Not retrying for 24 hours."));
107            }
108            return Err(anyhow!(
109                "Previous installation attempt failed ({reason}). Not retrying for 24 hours.\n{}",
110                manual_install_guide()
111            ));
112        }
113
114        let result = install_with_smart_detection();
115
116        match result {
117            Ok(()) => match Self::check() {
118                RipgrepStatus::Available { .. } => {
119                    debug_log("Installation verified successfully");
120                    InstallationCache::mark_success("auto-detected");
121                    Ok(())
122                }
123                status => {
124                    let msg = format!("Installation verification failed: {status:?}");
125                    debug_log(&msg);
126                    InstallationCache::mark_failed("auto-detected", &msg);
127                    Err(anyhow!(msg))
128                }
129            },
130            Err(err) => {
131                let msg = err.to_string();
132                debug_log(&format!("Installation failed: {msg}"));
133                InstallationCache::mark_failed("all-methods", &msg);
134                Err(anyhow!(msg))
135            }
136        }
137    }
138
139    /// Check if ripgrep is available, installing it if the caller explicitly requests that flow.
140    pub fn ensure_available() -> Result<Self> {
141        match Self::check() {
142            status @ RipgrepStatus::Available { .. } => Ok(status),
143            RipgrepStatus::NotFound => {
144                tracing::warn!("ripgrep not found, run `{RIPGREP_INSTALL_COMMAND}` to install");
145                Self::install()?;
146                Ok(Self::check())
147            }
148            status => Ok(status),
149        }
150    }
151}
152
153pub(super) fn debug_log(message: &str) {
154    if std::env::var("VTCODE_DEBUG_RIPGREP").is_ok() {
155        tracing::debug!(message, "ripgrep");
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn test_ripgrep_status_check() {
165        let status = RipgrepStatus::check();
166        tracing::debug!(?status, "Ripgrep status");
167    }
168
169    #[test]
170    fn manual_guide_covers_all_platforms() {
171        let guide = ripgrep_manual_install_guide();
172        // "manually" is the marker the install-cache dedup checks for.
173        assert!(guide.contains("manually"), "{guide}");
174        assert!(guide.contains("apt install -y ripgrep"), "{guide}");
175        assert!(guide.contains("brew install ripgrep"), "{guide}");
176        assert!(guide.contains("cargo install ripgrep"), "{guide}");
177        assert!(guide.contains("BurntSushi/ripgrep/releases"), "{guide}");
178        assert!(guide.contains("vtcode dependencies status ripgrep"), "{guide}");
179    }
180}