Skip to main content

vtcode_commons/paths/
canonicalize.rs

1use anyhow::{Result, anyhow};
2use std::path::{Path, PathBuf};
3use tracing::warn;
4
5/// Canonicalize a filesystem path without the Windows `\\?\` verbatim prefix.
6///
7/// `std::fs::canonicalize` returns verbatim (`\\?\`) paths on Windows, which
8/// break path comparisons, round-tripping through user config, and some APIs
9/// that reject verbatim paths. `dunce::canonicalize` strips the prefix when it
10/// is safe to do so and is a perfect drop-in on non-Windows platforms.
11///
12/// This is the single canonical entry point for path canonicalization in the
13/// workspace. All call sites should use this (or `canonicalize_workspace`) rather
14/// than `std::fs::canonicalize` / `Path::canonicalize`, which are banned by
15/// `clippy.toml`'s `disallowed-methods`.
16pub fn canonicalize(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
17    dunce::canonicalize(path)
18}
19
20/// Async canonicalize via `dunce`, using `spawn_blocking` to avoid blocking the
21/// runtime. Equivalent to `tokio::fs::canonicalize` but without the Windows
22/// `\\?\` verbatim prefix. Use this in async contexts instead of the sync
23/// [`canonicalize`] when the path may require I/O.
24pub async fn canonicalize_async(path: impl AsRef<Path> + Send) -> std::io::Result<PathBuf> {
25    let path = path.as_ref().to_path_buf();
26    match tokio::task::spawn_blocking(move || dunce::canonicalize(&path)).await {
27        Ok(inner) => inner,
28        Err(join_error) => Err(std::io::Error::other(join_error)),
29    }
30}
31
32/// Canonicalize a path with fallback to the original path if canonicalization fails.
33pub fn canonicalize_workspace(workspace_root: &Path) -> PathBuf {
34    canonicalize(workspace_root).unwrap_or_else(|error| {
35        warn!(
36            path = %workspace_root.display(),
37            %error,
38            "Failed to canonicalize workspace root; falling back to provided path"
39        );
40        workspace_root.to_path_buf()
41    })
42}
43
44/// Canonicalize a path, walking up to find the nearest existing ancestor for new files.
45///
46/// This function handles paths to files that may not yet exist by finding the
47/// nearest existing parent directory, canonicalizing that, and then appending
48/// the remaining path components.
49///
50/// # Security
51/// This function is critical for security. It prevents symlink escapes by:
52/// 1. Finding the nearest existing ancestor directory
53/// 2. Canonicalizing that directory (resolves symlinks)
54/// 3. Appending the remaining path components
55///
56/// # Arguments
57/// * `normalized` - A normalized path (output from `normalize_path`)
58///
59/// # Returns
60/// The canonical path, or the normalized path if no parent exists
61pub async fn canonicalize_allow_missing(normalized: &Path) -> Result<PathBuf> {
62    // If the path exists, canonicalize it directly
63    if tokio::fs::try_exists(normalized).await.unwrap_or(false) {
64        return canonicalize_async(normalized)
65            .await
66            .map_err(|e| anyhow!("Failed to resolve canonical path for '{}': {}", normalized.display(), e));
67    }
68
69    // Walk up the directory tree to find the nearest existing ancestor
70    let mut current = normalized.to_path_buf();
71    while let Some(parent) = current.parent() {
72        if tokio::fs::try_exists(parent).await.unwrap_or(false) {
73            // Canonicalize the existing parent
74            let canonical_parent = canonicalize_async(parent)
75                .await
76                .map_err(|e| anyhow!("Failed to resolve canonical path for '{}': {}", parent.display(), e))?;
77
78            // Get the remaining path components
79            let remainder = normalized.strip_prefix(parent).unwrap_or_else(|_| Path::new(""));
80
81            // Return the canonical parent + remaining components
82            return if remainder.as_os_str().is_empty() {
83                Ok(canonical_parent)
84            } else {
85                Ok(canonical_parent.join(remainder))
86            };
87        }
88        current = parent.to_path_buf();
89    }
90
91    // No existing parent found, return normalized path as-is
92    Ok(normalized.to_path_buf())
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[tokio::test]
100    async fn test_canonicalize_existing_file() {
101        // Create a temporary directory and file
102        let temp_dir = std::env::temp_dir();
103        let test_file = temp_dir.join("vtcode_test_existing.txt");
104        tokio::fs::write(&test_file, b"test").await.unwrap();
105
106        let canonical = canonicalize_allow_missing(&test_file).await.unwrap();
107
108        // Should get the canonical path
109        assert!(canonical.is_absolute());
110        assert!(canonical.exists());
111
112        // Cleanup
113        drop(tokio::fs::remove_file(&test_file).await);
114    }
115
116    #[tokio::test]
117    async fn test_canonicalize_missing_file() {
118        // Use a path that doesn't exist but has an existing parent
119        let temp_dir = std::env::temp_dir();
120        let missing_file = temp_dir.join("vtcode_test_missing_dir/missing_file.txt");
121
122        let canonical = canonicalize_allow_missing(&missing_file).await.unwrap();
123
124        // Should get canonical parent + missing components
125        assert!(canonical.is_absolute());
126        assert!(canonical.to_string_lossy().contains("missing_file.txt"));
127    }
128
129    #[tokio::test]
130    async fn test_canonicalize_deeply_missing_path() {
131        // Use a path with multiple missing parent directories
132        let temp_dir = std::env::temp_dir();
133        let deep_missing = temp_dir.join("vtcode_test_a/b/c/d/file.txt");
134
135        let canonical = canonicalize_allow_missing(&deep_missing).await.unwrap();
136
137        // Should get canonical temp_dir + missing components
138        assert!(canonical.is_absolute());
139        assert!(canonical.to_string_lossy().contains("vtcode_test_a"));
140    }
141
142    #[tokio::test]
143    async fn test_canonicalize_missing_file_with_existing_parent() {
144        // Create a parent directory
145        let temp_dir = std::env::temp_dir();
146        let test_dir = temp_dir.join("vtcode_test_parent");
147        tokio::fs::create_dir_all(&test_dir).await.unwrap();
148
149        let missing_file = test_dir.join("missing.txt");
150        let canonical = canonicalize_allow_missing(&missing_file).await.unwrap();
151
152        // Should get canonical parent + missing filename
153        assert!(canonical.is_absolute());
154        assert!(canonical.to_string_lossy().ends_with("missing.txt"));
155
156        // Cleanup
157        drop(tokio::fs::remove_dir(&test_dir).await);
158    }
159}