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