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                                    maybe_col_str.split_once(':').unwrap_or((maybe_col_str, ""));
210                                match maybe_col_str.parse::<u32>() {
211                                    Ok(col) => Ok(Self {
212                                        path_like: parse_path_like_str(path_like_str)?,
213                                        row: Some(row),
214                                        column: Some(col),
215                                    }),
216                                    Err(_) => Ok(Self {
217                                        path_like: parse_path_like_str(path_like_str)?,
218                                        row: Some(row),
219                                        column: None,
220                                    }),
221                                }
222                            }
223                        }
224                        Err(_) => Ok(Self {
225                            path_like: parse_path_like_str(path_like_str)?,
226                            row: None,
227                            column: None,
228                        }),
229                    }
230                }
231            }
232            None => fallback(s),
233        }
234    }
235
236    pub fn map_path_like<P2, E>(
237        self,
238        mapping: impl FnOnce(P) -> Result<P2, E>,
239    ) -> Result<PathLikeWithPosition<P2>, E> {
240        Ok(PathLikeWithPosition {
241            path_like: mapping(self.path_like)?,
242            row: self.row,
243            column: self.column,
244        })
245    }
246
247    pub fn to_string(&self, path_like_to_string: impl Fn(&P) -> String) -> String {
248        let path_like_string = path_like_to_string(&self.path_like);
249        if let Some(row) = self.row {
250            if let Some(column) = self.column {
251                format!("{path_like_string}:{row}:{column}")
252            } else {
253                format!("{path_like_string}:{row}")
254            }
255        } else {
256            path_like_string
257        }
258    }
259}
260
261#[derive(Clone, Debug)]
262pub struct PathMatcher {
263    maybe_path: PathBuf,
264    glob: GlobMatcher,
265}
266
267impl std::fmt::Display for PathMatcher {
268    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269        self.maybe_path.to_string_lossy().fmt(f)
270    }
271}
272
273impl PartialEq for PathMatcher {
274    fn eq(&self, other: &Self) -> bool {
275        self.maybe_path.eq(&other.maybe_path)
276    }
277}
278
279impl Eq for PathMatcher {}
280
281impl PathMatcher {
282    pub fn new(maybe_glob: &str) -> Result<Self, globset::Error> {
283        Ok(PathMatcher {
284            glob: Glob::new(maybe_glob)?.compile_matcher(),
285            maybe_path: PathBuf::from(maybe_glob),
286        })
287    }
288
289    pub fn is_match<P: AsRef<Path>>(&self, other: P) -> bool {
290        let other_path = other.as_ref();
291        other_path.starts_with(&self.maybe_path)
292            || other_path.ends_with(&self.maybe_path)
293            || self.glob.is_match(other_path)
294            || self.check_with_end_separator(other_path)
295    }
296
297    fn check_with_end_separator(&self, path: &Path) -> bool {
298        let path_str = path.to_string_lossy();
299        let separator = std::path::MAIN_SEPARATOR_STR;
300        if path_str.ends_with(separator) {
301            self.glob.is_match(path)
302        } else {
303            self.glob.is_match(path_str.to_string() + separator)
304        }
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    type TestPath = PathLikeWithPosition<String>;
313
314    fn parse_str(s: &str) -> TestPath {
315        TestPath::parse_str(s, |s| Ok::<_, std::convert::Infallible>(s.to_string()))
316            .expect("infallible")
317    }
318
319    #[test]
320    fn path_with_position_parsing_positive() {
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                "test_file.rs:1:2",
340                PathLikeWithPosition {
341                    path_like: "test_file.rs".to_string(),
342                    row: Some(1),
343                    column: Some(2),
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 positive case input str '{input}', got a parse mismatch"
353            );
354        }
355    }
356
357    #[test]
358    fn path_with_position_parsing_negative() {
359        for (input, row, column) in [
360            ("test_file.rs:a", None, None),
361            ("test_file.rs:a:b", None, None),
362            ("test_file.rs::", None, None),
363            ("test_file.rs::1", None, None),
364            ("test_file.rs:1::", Some(1), None),
365            ("test_file.rs::1:2", None, None),
366            ("test_file.rs:1::2", Some(1), None),
367            ("test_file.rs:1:2:3", Some(1), Some(2)),
368        ] {
369            let actual = parse_str(input);
370            assert_eq!(
371                actual,
372                PathLikeWithPosition {
373                    path_like: "test_file.rs".to_string(),
374                    row,
375                    column,
376                },
377                "For negative case input str '{input}', got a parse mismatch"
378            );
379        }
380    }
381
382    // Trim off trailing `:`s for otherwise valid input.
383    #[test]
384    fn path_with_position_parsing_special() {
385        let input_and_expected = [
386            (
387                "test_file.rs:",
388                PathLikeWithPosition {
389                    path_like: "test_file.rs".to_string(),
390                    row: None,
391                    column: None,
392                },
393            ),
394            (
395                "test_file.rs:1:",
396                PathLikeWithPosition {
397                    path_like: "test_file.rs".to_string(),
398                    row: Some(1),
399                    column: None,
400                },
401            ),
402            (
403                "crates/file_finder/src/file_finder.rs:1902:13:",
404                PathLikeWithPosition {
405                    path_like: "crates/file_finder/src/file_finder.rs".to_string(),
406                    row: Some(1902),
407                    column: Some(13),
408                },
409            ),
410        ];
411
412        for (input, expected) in input_and_expected {
413            let actual = parse_str(input);
414            assert_eq!(
415                actual, expected,
416                "For special case input str '{input}', got a parse mismatch"
417            );
418        }
419    }
420
421    #[test]
422    fn test_path_compact() {
423        let path: PathBuf = [
424            HOME.to_string_lossy().to_string(),
425            "some_file.txt".to_string(),
426        ]
427        .iter()
428        .collect();
429        if cfg!(target_os = "linux") || cfg!(target_os = "macos") {
430            assert_eq!(path.compact().to_str(), Some("~/some_file.txt"));
431        } else {
432            assert_eq!(path.compact().to_str(), path.to_str());
433        }
434    }
435
436    #[test]
437    fn test_icon_stem_or_suffix() {
438        // No dots 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        // Single dot in name
443        let path = Path::new("/a/b/c/file.name.rs");
444        assert_eq!(path.icon_stem_or_suffix(), Some("rs"));
445
446        // No suffix
447        let path = Path::new("/a/b/c/file");
448        assert_eq!(path.icon_stem_or_suffix(), Some("file"));
449
450        // Multiple dots in name
451        let path = Path::new("/a/b/c/long.file.name.rs");
452        assert_eq!(path.icon_stem_or_suffix(), Some("rs"));
453
454        // Hidden file, no extension
455        let path = Path::new("/a/b/c/.gitignore");
456        assert_eq!(path.icon_stem_or_suffix(), Some("gitignore"));
457
458        // Hidden file, with extension
459        let path = Path::new("/a/b/c/.eslintrc.js");
460        assert_eq!(path.icon_stem_or_suffix(), Some("eslintrc.js"));
461    }
462
463    #[test]
464    fn test_extension_or_hidden_file_name() {
465        // No dots 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        // Single dot in name
470        let path = Path::new("/a/b/c/file.name.rs");
471        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
472
473        // Multiple dots in name
474        let path = Path::new("/a/b/c/long.file.name.rs");
475        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
476
477        // Hidden file, no extension
478        let path = Path::new("/a/b/c/.gitignore");
479        assert_eq!(path.extension_or_hidden_file_name(), Some("gitignore"));
480
481        // Hidden file, with extension
482        let path = Path::new("/a/b/c/.eslintrc.js");
483        assert_eq!(path.extension_or_hidden_file_name(), Some("js"));
484    }
485
486    #[test]
487    fn edge_of_glob() {
488        let path = Path::new("/work/node_modules");
489        let path_matcher = PathMatcher::new("**/node_modules/**").unwrap();
490        assert!(
491            path_matcher.is_match(path),
492            "Path matcher {path_matcher} should match {path:?}"
493        );
494    }
495
496    #[test]
497    fn project_search() {
498        let path = Path::new("/Users/someonetoignore/work/zed/zed.dev/node_modules");
499        let path_matcher = PathMatcher::new("**/node_modules/**").unwrap();
500        assert!(
501            path_matcher.is_match(path),
502            "Path matcher {path_matcher} should match {path:?}"
503        );
504    }
505}