paths.rs

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