Skip to main content

vtcode_core/tools/
path_env.rs

1use hashbrown::HashSet;
2use std::ffi::{OsStr, OsString};
3use std::path::{Path, PathBuf};
4
5use regex::Regex;
6use std::sync::LazyLock;
7
8/// Regex pattern for Unix-style environment variables: $VAR or ${VAR}
9///
10/// # Panics
11///
12/// Panics at first access if the regex pattern fails to compile. The pattern
13/// is a string literal validated by tests; a panic here indicates a typo
14/// in the pattern itself, not a runtime failure.
15static UNIX_ENV_PATTERN: LazyLock<Regex> =
16    LazyLock::new(|| match Regex::new(r"\$([A-Za-z_][A-Za-z0-9_]*)|\$\{([A-Za-z_][A-Za-z0-9_]*)\}") {
17        Ok(regex) => regex,
18        Err(error) => panic!("valid unix env regex must compile: {error}"),
19    });
20
21/// Regex pattern for Windows-style environment variables: %VAR%
22///
23/// # Panics
24///
25/// Panics at first access if the regex pattern fails to compile. The pattern
26/// is a string literal validated by tests; a panic here indicates a typo
27/// in the pattern itself, not a runtime failure.
28static WINDOWS_ENV_PATTERN: LazyLock<Regex> = LazyLock::new(|| match Regex::new(r"%([A-Za-z_][A-Za-z0-9_]*)%") {
29    Ok(regex) => regex,
30    Err(error) => panic!("valid windows env regex must compile: {error}"),
31});
32
33/// Expand environment variables and home directory within a path entry.
34fn expand_entry(entry: &str, workspace_root: &Path) -> Option<PathBuf> {
35    let trimmed = entry.trim();
36    if trimmed.is_empty() {
37        return None;
38    }
39
40    let expanded_env = expand_environment_variables(trimmed);
41    let mut path = if let Some(rest) = expanded_env.strip_prefix("~/") {
42        dirs::home_dir().map(|home| home.join(rest))?
43    } else if expanded_env == "~" {
44        dirs::home_dir()?
45    } else {
46        PathBuf::from(expanded_env)
47    };
48
49    if path.is_relative() {
50        path = workspace_root.join(path);
51    }
52
53    path.is_dir().then_some(path)
54}
55
56fn expand_environment_variables(input: &str) -> String {
57    let unix_expanded = UNIX_ENV_PATTERN
58        .replace_all(input, |caps: &regex::Captures<'_>| {
59            let var_name = caps.get(1).or_else(|| caps.get(2)).map(|m| m.as_str()).unwrap_or_default();
60            // Try to get the environment variable, with special handling for HOME
61            match var_name {
62                "HOME" => std::env::var("HOME")
63                    .or_else(|_| std::env::var("USERPROFILE"))
64                    .unwrap_or_else(|_| dirs::home_dir().map(|p| p.display().to_string()).unwrap_or_default()),
65                _ => std::env::var(var_name).unwrap_or_default(),
66            }
67        })
68        .into_owned();
69
70    WINDOWS_ENV_PATTERN
71        .replace_all(&unix_expanded, |caps: &regex::Captures<'_>| {
72            let var_name = &caps[1];
73            // Try to get the environment variable, with special handling for HOME/USERPROFILE
74            match var_name {
75                "HOME" | "USERPROFILE" => std::env::var("USERPROFILE")
76                    .or_else(|_| std::env::var("HOME"))
77                    .unwrap_or_else(|_| dirs::home_dir().map(|p| p.display().to_string()).unwrap_or_default()),
78                _ => std::env::var(var_name).unwrap_or_default(),
79            }
80        })
81        .into_owned()
82}
83
84/// Compute the list of additional search paths for command execution.
85pub(crate) fn compute_extra_search_paths(entries: &[String], workspace_root: &Path) -> Vec<PathBuf> {
86    let mut results = Vec::new();
87    let mut seen = HashSet::new();
88
89    for entry in entries {
90        if let Some(path) = expand_entry(entry, workspace_root)
91            && seen.insert(path.clone())
92        {
93            results.push(path);
94        }
95    }
96
97    results
98}
99
100/// Attempt to resolve a program against the provided path iterator.
101#[allow(dead_code, reason = "Intentional compatibility, platform, or test-only suppression.")] // Function is deprecated but kept for explicit path iteration tests
102pub(crate) fn resolve_program_path_from_paths(program: &str, paths: impl Iterator<Item = PathBuf>) -> Option<String> {
103    for path_dir in paths {
104        let full_path = path_dir.join(program);
105        if full_path.is_file() {
106            return Some(full_path.to_string_lossy().into_owned());
107        }
108    }
109    None
110}
111
112// NOTE: Static resolution of program paths is intentionally deprecated in favor of
113// always executing commands through the user's login shell (via `resolve_fallback_shell`).
114// The `resolve_program_path_from_paths` helper remains for explicit path iteration tests.
115
116/// Merge additional search paths into an existing PATH environment value.
117pub(crate) fn merge_path_env(current: Option<&OsStr>, extra_paths: &[PathBuf]) -> Option<OsString> {
118    if extra_paths.is_empty() && current.is_none() {
119        return None;
120    }
121
122    let mut combined: Vec<PathBuf> = current.map(|value| std::env::split_paths(value).collect()).unwrap_or_default();
123
124    // Ensure common development tool paths are included for fallback
125    // These paths are often added by shell initialization files but we include them
126    // to ensure development tools work even if shell initialization is incomplete
127    let fallback_paths = [
128        "~/.cargo/bin",               // Rust toolchain (cargo, rustc)
129        "~/.local/bin",               // User-installed binaries
130        "~/.nvm/versions/node/*/bin", // Node Version Manager
131        "~/.bun/bin",                 // Bun package manager
132        "/opt/homebrew/bin",          // Homebrew on Apple Silicon
133        "/usr/local/bin",             // Local binaries
134        "/opt/local/bin",             // MacPorts
135    ];
136
137    for fallback_path_pattern in &fallback_paths {
138        // Expand tilde to home directory
139        if let Some(home) = dirs::home_dir() {
140            let expanded = fallback_path_pattern.replace("~", &home.display().to_string());
141
142            // For glob patterns like nvm, just add the base directory if home/nvm exists
143            if expanded.contains('*') {
144                let base_pattern = expanded.split('*').next().unwrap_or("");
145                let base_path = PathBuf::from(base_pattern.trim_end_matches('/'));
146                if base_path.exists() && !combined.iter().any(|existing| existing == &base_path) {
147                    combined.push(base_path);
148                }
149            } else {
150                let path = PathBuf::from(expanded);
151                if path.exists() && !combined.iter().any(|existing| existing == &path) {
152                    combined.push(path);
153                }
154            }
155        }
156    }
157
158    for path in extra_paths.iter().rev() {
159        if !combined.iter().any(|existing| existing == path) {
160            combined.insert(0, path.clone());
161        }
162    }
163
164    if combined.is_empty() {
165        return None;
166    }
167
168    std::env::join_paths(combined).ok()
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn compute_extra_search_paths_expands_home_and_env() {
177        let workspace = std::env::current_dir().expect("workspace");
178        let home_dir = PathBuf::from(std::env::var("HOME").expect("HOME"));
179        let entries = vec!["~/does/not/exist".to_string(), "$HOME".to_string()];
180        let resolved = compute_extra_search_paths(&entries, &workspace);
181        assert_eq!(resolved, vec![home_dir]);
182    }
183
184    #[test]
185    fn merge_path_env_preprends_extra_entries() {
186        let extra = vec![PathBuf::from("/extra/bin"), PathBuf::from("/another/bin")];
187        let current = Some(OsStr::new("/usr/bin:/bin"));
188        let merged = merge_path_env(current, &extra).expect("merged path");
189        let paths: Vec<PathBuf> = std::env::split_paths(&merged).collect();
190        assert_eq!(paths[0], PathBuf::from("/extra/bin"));
191        assert_eq!(paths[1], PathBuf::from("/another/bin"));
192        assert_eq!(paths[2], PathBuf::from("/usr/bin"));
193    }
194
195    #[test]
196    fn resolve_program_path_uses_extra_dirs() {
197        let temp_dir = tempfile::tempdir().expect("tempdir");
198        let bin_dir = temp_dir.path();
199        let fake = bin_dir.join("fake-tool");
200        std::fs::write(&fake, b"#!/bin/sh\n").expect("write fake tool");
201        #[cfg(unix)]
202        {
203            use std::os::unix::fs::PermissionsExt;
204            let mut perms = std::fs::metadata(&fake).expect("metadata").permissions();
205            perms.set_mode(0o755);
206            std::fs::set_permissions(&fake, perms).expect("set perms");
207        }
208
209        let resolved = resolve_program_path_from_paths("fake-tool", [bin_dir.to_path_buf()].into_iter());
210        assert_eq!(resolved, Some(fake.to_string_lossy().into_owned()))
211    }
212}
213
214#[cfg(test)]
215mod regex_validation_tests {
216    #[test]
217    fn unix_env_regex_pattern_compiles() {
218        // Validates that the UNIX_ENV_PATTERN regex string literal is a valid
219        // regex. A failure here indicates a typo in the pattern, which would
220        // otherwise panic at first access in production.
221        let _ = &*super::UNIX_ENV_PATTERN;
222    }
223
224    #[test]
225    fn windows_env_regex_pattern_compiles() {
226        // Validates that the WINDOWS_ENV_PATTERN regex string literal is a valid
227        // regex. A failure here indicates a typo in the pattern, which would
228        // otherwise panic at first access in production.
229        let _ = &*super::WINDOWS_ENV_PATTERN;
230    }
231}