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