paths.rs

  1use std::{
  2    ffi::OsStr,
  3    path::{Path, PathBuf},
  4};
  5
  6use globset::{Glob, GlobMatcher};
  7use serde::{Deserialize, Serialize};
  8
  9lazy_static::lazy_static! {
 10    pub static ref HOME: PathBuf = dirs::home_dir().expect("failed to determine home directory");
 11    pub static ref CONFIG_DIR: PathBuf = if cfg!(target_os = "windows") {
 12        dirs::config_dir()
 13            .expect("failed to determine RoamingAppData directory")
 14            .join("Zed")
 15    } else {
 16        HOME.join(".config").join("zed")
 17    };
 18    pub static ref CONVERSATIONS_DIR: PathBuf = CONFIG_DIR.join("conversations");
 19    pub static ref EMBEDDINGS_DIR: PathBuf = CONFIG_DIR.join("embeddings");
 20    pub static ref THEMES_DIR: PathBuf = CONFIG_DIR.join("themes");
 21    pub static ref LOGS_DIR: PathBuf = if cfg!(target_os = "macos") {
 22        HOME.join("Library/Logs/Zed")
 23    } else if cfg!(target_os = "windows") {
 24        dirs::data_local_dir()
 25            .expect("failed to determine LocalAppData directory")
 26            .join("Zed/logs")
 27    } else {
 28        CONFIG_DIR.join("logs")
 29    };
 30    pub static ref SUPPORT_DIR: PathBuf = if cfg!(target_os = "macos") {
 31        HOME.join("Library/Application Support/Zed")
 32    } else if cfg!(target_os = "windows") {
 33        dirs::config_dir()
 34            .expect("failed to determine RoamingAppData directory")
 35            .join("Zed")
 36    } else {
 37        CONFIG_DIR.clone()
 38    };
 39    pub static ref EXTENSIONS_DIR: PathBuf = SUPPORT_DIR.join("extensions");
 40    pub static ref LANGUAGES_DIR: PathBuf = SUPPORT_DIR.join("languages");
 41    pub static ref COPILOT_DIR: PathBuf = SUPPORT_DIR.join("copilot");
 42    pub static ref DEFAULT_PRETTIER_DIR: PathBuf = SUPPORT_DIR.join("prettier");
 43    pub static ref DB_DIR: PathBuf = SUPPORT_DIR.join("db");
 44    pub static ref CRASHES_DIR: PathBuf = if cfg!(target_os = "macos") {
 45        HOME.join("Library/Logs/DiagnosticReports")
 46    } else if cfg!(target_os = "windows") {
 47        dirs::data_local_dir()
 48            .expect("failed to determine LocalAppData directory")
 49            .join("Zed/crashes")
 50    } else {
 51        CONFIG_DIR.join("crashes")
 52    };
 53    pub static ref CRASHES_RETIRED_DIR: PathBuf = if cfg!(target_os = "macos") {
 54        HOME.join("Library/Logs/DiagnosticReports/Retired")
 55    } else {
 56        CRASHES_DIR.join("retired")
 57    };
 58    pub static ref SETTINGS: PathBuf = CONFIG_DIR.join("settings.json");
 59    pub static ref KEYMAP: PathBuf = CONFIG_DIR.join("keymap.json");
 60    pub static ref TASKS: PathBuf = CONFIG_DIR.join("tasks.json");
 61    pub static ref LAST_USERNAME: PathBuf = CONFIG_DIR.join("last-username.txt");
 62    pub static ref LOG: PathBuf = LOGS_DIR.join("Zed.log");
 63    pub static ref OLD_LOG: PathBuf = LOGS_DIR.join("Zed.log.old");
 64    pub static ref LOCAL_SETTINGS_RELATIVE_PATH: &'static Path = Path::new(".zed/settings.json");
 65    pub static ref LOCAL_TASKS_RELATIVE_PATH: &'static Path = Path::new(".zed/tasks.json");
 66    pub static ref LOCAL_VSCODE_TASKS_RELATIVE_PATH: &'static Path = Path::new(".vscode/tasks.json");
 67    pub static ref TEMP_DIR: PathBuf = if cfg!(target_os = "widows") {
 68        dirs::data_local_dir()
 69            .expect("failed to determine LocalAppData directory")
 70            .join("Temp/Zed")
 71    } else {
 72        HOME.join(".cache").join("zed")
 73    };
 74}
 75
 76pub trait PathExt {
 77    fn compact(&self) -> PathBuf;
 78    fn icon_stem_or_suffix(&self) -> Option<&str>;
 79    fn extension_or_hidden_file_name(&self) -> Option<&str>;
 80    fn try_from_bytes<'a>(bytes: &'a [u8]) -> anyhow::Result<Self>
 81    where
 82        Self: From<&'a Path>,
 83    {
 84        #[cfg(unix)]
 85        {
 86            use std::os::unix::prelude::OsStrExt;
 87            Ok(Self::from(Path::new(OsStr::from_bytes(bytes))))
 88        }
 89        #[cfg(windows)]
 90        {
 91            use anyhow::anyhow;
 92            use tendril::fmt::{Format, WTF8};
 93            WTF8::validate(bytes)
 94                .then(|| {
 95                    // Safety: bytes are valid WTF-8 sequence.
 96                    Self::from(Path::new(unsafe {
 97                        OsStr::from_encoded_bytes_unchecked(bytes)
 98                    }))
 99                })
100                .ok_or_else(|| anyhow!("Invalid WTF-8 sequence: {bytes:?}"))
101        }
102    }
103}
104
105impl<T: AsRef<Path>> PathExt for T {
106    /// Compacts a given file path by replacing the user's home directory
107    /// prefix with a tilde (`~`).
108    ///
109    /// # Returns
110    ///
111    /// * A `PathBuf` containing the compacted file path. If the input path
112    ///   does not have the user's home directory prefix, or if we are not on
113    ///   Linux or macOS, the original path is returned unchanged.
114    fn compact(&self) -> PathBuf {
115        if cfg!(target_os = "linux") || cfg!(target_os = "macos") {
116            match self.as_ref().strip_prefix(HOME.as_path()) {
117                Ok(relative_path) => {
118                    let mut shortened_path = PathBuf::new();
119                    shortened_path.push("~");
120                    shortened_path.push(relative_path);
121                    shortened_path
122                }
123                Err(_) => self.as_ref().to_path_buf(),
124            }
125        } else {
126            self.as_ref().to_path_buf()
127        }
128    }
129
130    /// Returns either the suffix if available, or the file stem otherwise to determine which file icon to use
131    fn icon_stem_or_suffix(&self) -> Option<&str> {
132        let path = self.as_ref();
133        let file_name = path.file_name()?.to_str()?;
134        if file_name.starts_with('.') {
135            return file_name.strip_prefix('.');
136        }
137
138        path.extension()
139            .and_then(|e| e.to_str())
140            .or_else(|| path.file_stem()?.to_str())
141    }
142
143    /// Returns a file's extension or, if the file is hidden, its name without the leading dot
144    fn extension_or_hidden_file_name(&self) -> Option<&str> {
145        if let Some(extension) = self.as_ref().extension() {
146            return extension.to_str();
147        }
148
149        self.as_ref().file_name()?.to_str()?.split('.').last()
150    }
151}
152
153/// A delimiter to use in `path_query:row_number:column_number` strings parsing.
154pub const FILE_ROW_COLUMN_DELIMITER: char = ':';
155
156/// A representation of a path-like string with optional row and column numbers.
157/// Matching values example: `te`, `test.rs:22`, `te:22:5`, etc.
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
159pub struct PathLikeWithPosition<P> {
160    pub path_like: P,
161    pub row: Option<u32>,
162    // Absent if row is absent.
163    pub column: Option<u32>,
164}
165
166impl<P> PathLikeWithPosition<P> {
167    /// Parses a string that possibly has `:row:column` suffix.
168    /// Ignores trailing `:`s, so `test.rs:22:` is parsed as `test.rs:22`.
169    /// If any of the row/column component parsing fails, the whole string is then parsed as a path like.
170    pub fn parse_str<E>(
171        s: &str,
172        parse_path_like_str: impl Fn(&str) -> Result<P, E>,
173    ) -> Result<Self, E> {
174        let fallback = |fallback_str| {
175            Ok(Self {
176                path_like: parse_path_like_str(fallback_str)?,
177                row: None,
178                column: None,
179            })
180        };
181
182        match s.trim().split_once(FILE_ROW_COLUMN_DELIMITER) {
183            Some((path_like_str, maybe_row_and_col_str)) => {
184                let path_like_str = path_like_str.trim();
185                let maybe_row_and_col_str = maybe_row_and_col_str.trim();
186                if path_like_str.is_empty() {
187                    fallback(s)
188                } else if maybe_row_and_col_str.is_empty() {
189                    fallback(path_like_str)
190                } else {
191                    let (row_parse_result, maybe_col_str) =
192                        match maybe_row_and_col_str.split_once(FILE_ROW_COLUMN_DELIMITER) {
193                            Some((maybe_row_str, maybe_col_str)) => {
194                                (maybe_row_str.parse::<u32>(), maybe_col_str.trim())
195                            }
196                            None => (maybe_row_and_col_str.parse::<u32>(), ""),
197                        };
198
199                    match row_parse_result {
200                        Ok(row) => {
201                            if maybe_col_str.is_empty() {
202                                Ok(Self {
203                                    path_like: parse_path_like_str(path_like_str)?,
204                                    row: Some(row),
205                                    column: None,
206                                })
207                            } else {
208                                let maybe_col_str =
209                                    if maybe_col_str.ends_with(FILE_ROW_COLUMN_DELIMITER) {
210                                        &maybe_col_str[..maybe_col_str.len() - 1]
211                                    } else {
212                                        maybe_col_str
213                                    };
214                                match maybe_col_str.parse::<u32>() {
215                                    Ok(col) => Ok(Self {
216                                        path_like: parse_path_like_str(path_like_str)?,
217                                        row: Some(row),
218                                        column: Some(col),
219                                    }),
220                                    Err(_) => fallback(s),
221                                }
222                            }
223                        }
224                        Err(_) => fallback(s),
225                    }
226                }
227            }
228            None => fallback(s),
229        }
230    }
231
232    pub fn map_path_like<P2, E>(
233        self,
234        mapping: impl FnOnce(P) -> Result<P2, E>,
235    ) -> Result<PathLikeWithPosition<P2>, E> {
236        Ok(PathLikeWithPosition {
237            path_like: mapping(self.path_like)?,
238            row: self.row,
239            column: self.column,
240        })
241    }
242
243    pub fn to_string(&self, path_like_to_string: impl Fn(&P) -> String) -> String {
244        let path_like_string = path_like_to_string(&self.path_like);
245        if let Some(row) = self.row {
246            if let Some(column) = self.column {
247                format!("{path_like_string}:{row}:{column}")
248            } else {
249                format!("{path_like_string}:{row}")
250            }
251        } else {
252            path_like_string
253        }
254    }
255}
256
257#[derive(Clone, Debug)]
258pub struct PathMatcher {
259    maybe_path: PathBuf,
260    glob: GlobMatcher,
261}
262
263impl std::fmt::Display for PathMatcher {
264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265        self.maybe_path.to_string_lossy().fmt(f)
266    }
267}
268
269impl PartialEq for PathMatcher {
270    fn eq(&self, other: &Self) -> bool {
271        self.maybe_path.eq(&other.maybe_path)
272    }
273}
274
275impl Eq for PathMatcher {}
276
277impl PathMatcher {
278    pub fn new(maybe_glob: &str) -> Result<Self, globset::Error> {
279        Ok(PathMatcher {
280            glob: Glob::new(maybe_glob)?.compile_matcher(),
281            maybe_path: PathBuf::from(maybe_glob),
282        })
283    }
284
285    pub fn is_match<P: AsRef<Path>>(&self, other: P) -> bool {
286        let other_path = other.as_ref();
287        other_path.starts_with(&self.maybe_path)
288            || other_path.ends_with(&self.maybe_path)
289            || self.glob.is_match(other_path)
290            || self.check_with_end_separator(other_path)
291    }
292
293    fn check_with_end_separator(&self, path: &Path) -> bool {
294        let path_str = path.to_string_lossy();
295        let separator = std::path::MAIN_SEPARATOR_STR;
296        if path_str.ends_with(separator) {
297            self.glob.is_match(path)
298        } else {
299            self.glob.is_match(path_str.to_string() + separator)
300        }
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307
308    type TestPath = PathLikeWithPosition<String>;
309
310    fn parse_str(s: &str) -> TestPath {
311        TestPath::parse_str(s, |s| Ok::<_, std::convert::Infallible>(s.to_string()))
312            .expect("infallible")
313    }
314
315    #[test]
316    fn path_with_position_parsing_positive() {
317        let input_and_expected = [
318            (
319                "test_file.rs",
320                PathLikeWithPosition {
321                    path_like: "test_file.rs".to_string(),
322                    row: None,
323                    column: None,
324                },
325            ),
326            (
327                "test_file.rs:1",
328                PathLikeWithPosition {
329                    path_like: "test_file.rs".to_string(),
330                    row: Some(1),
331                    column: None,
332                },
333            ),
334            (
335                "test_file.rs:1:2",
336                PathLikeWithPosition {
337                    path_like: "test_file.rs".to_string(),
338                    row: Some(1),
339                    column: Some(2),
340                },
341            ),
342        ];
343
344        for (input, expected) in input_and_expected {
345            let actual = parse_str(input);
346            assert_eq!(
347                actual, expected,
348                "For positive case input str '{input}', got a parse mismatch"
349            );
350        }
351    }
352
353    #[test]
354    fn path_with_position_parsing_negative() {
355        for input in [
356            "test_file.rs:a",
357            "test_file.rs:a:b",
358            "test_file.rs::",
359            "test_file.rs::1",
360            "test_file.rs:1::",
361            "test_file.rs::1:2",
362            "test_file.rs:1::2",
363            "test_file.rs:1:2:3",
364        ] {
365            let actual = parse_str(input);
366            assert_eq!(
367                actual,
368                PathLikeWithPosition {
369                    path_like: input.to_string(),
370                    row: None,
371                    column: None,
372                },
373                "For negative case input str '{input}', got a parse mismatch"
374            );
375        }
376    }
377
378    // Trim off trailing `:`s for otherwise valid input.
379    #[test]
380    fn path_with_position_parsing_special() {
381        let input_and_expected = [
382            (
383                "test_file.rs:",
384                PathLikeWithPosition {
385                    path_like: "test_file.rs".to_string(),
386                    row: None,
387                    column: None,
388                },
389            ),
390            (
391                "test_file.rs:1:",
392                PathLikeWithPosition {
393                    path_like: "test_file.rs".to_string(),
394                    row: Some(1),
395                    column: None,
396                },
397            ),
398            (
399                "crates/file_finder/src/file_finder.rs:1902:13:",
400                PathLikeWithPosition {
401                    path_like: "crates/file_finder/src/file_finder.rs".to_string(),
402                    row: Some(1902),
403                    column: Some(13),
404                },
405            ),
406        ];
407
408        for (input, expected) in input_and_expected {
409            let actual = parse_str(input);
410            assert_eq!(
411                actual, expected,
412                "For special case input str '{input}', got a parse mismatch"
413            );
414        }
415    }
416
417    #[test]
418    fn test_path_compact() {
419        let path: PathBuf = [
420            HOME.to_string_lossy().to_string(),
421            "some_file.txt".to_string(),
422        ]
423        .iter()
424        .collect();
425        if cfg!(target_os = "linux") || cfg!(target_os = "macos") {
426            assert_eq!(path.compact().to_str(), Some("~/some_file.txt"));
427        } else {
428            assert_eq!(path.compact().to_str(), path.to_str());
429        }
430    }
431
432    #[test]
433    fn test_icon_stem_or_suffix() {
434        // No dots in name
435        let path = Path::new("/a/b/c/file_name.rs");
436        assert_eq!(path.icon_stem_or_suffix(), Some("rs"));
437
438        // Single dot in name
439        let path = Path::new("/a/b/c/file.name.rs");
440        assert_eq!(path.icon_stem_or_suffix(), Some("rs"));
441
442        // No suffix
443        let path = Path::new("/a/b/c/file");
444        assert_eq!(path.icon_stem_or_suffix(), Some("file"));
445
446        // Multiple dots in name
447        let path = Path::new("/a/b/c/long.file.name.rs");
448        assert_eq!(path.icon_stem_or_suffix(), Some("rs"));
449
450        // Hidden file, no extension
451        let path = Path::new("/a/b/c/.gitignore");
452        assert_eq!(path.icon_stem_or_suffix(), Some("gitignore"));
453
454        // Hidden file, with extension
455        let path = Path::new("/a/b/c/.eslintrc.js");
456        assert_eq!(path.icon_stem_or_suffix(), Some("eslintrc.js"));
457    }
458
459    #[test]
460    fn test_extension_or_hidden_file_name() {
461        // No dots in name
462        let path = Path::new("/a/b/c/file_name.rs");
463        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
464
465        // Single dot in name
466        let path = Path::new("/a/b/c/file.name.rs");
467        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
468
469        // Multiple dots in name
470        let path = Path::new("/a/b/c/long.file.name.rs");
471        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
472
473        // Hidden file, no extension
474        let path = Path::new("/a/b/c/.gitignore");
475        assert_eq!(path.extension_or_hidden_file_name(), Some("gitignore"));
476
477        // Hidden file, with extension
478        let path = Path::new("/a/b/c/.eslintrc.js");
479        assert_eq!(path.extension_or_hidden_file_name(), Some("js"));
480    }
481
482    #[test]
483    fn edge_of_glob() {
484        let path = Path::new("/work/node_modules");
485        let path_matcher = PathMatcher::new("**/node_modules/**").unwrap();
486        assert!(
487            path_matcher.is_match(path),
488            "Path matcher {path_matcher} should match {path:?}"
489        );
490    }
491
492    #[test]
493    fn project_search() {
494        let path = Path::new("/Users/someonetoignore/work/zed/zed.dev/node_modules");
495        let path_matcher = PathMatcher::new("**/node_modules/**").unwrap();
496        assert!(
497            path_matcher.is_match(path),
498            "Path matcher {path_matcher} should match {path:?}"
499        );
500    }
501}