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