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