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