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