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