1use std::path::{Path, PathBuf};
2
3use serde::{Deserialize, Serialize};
4
5lazy_static::lazy_static! {
6 pub static ref HOME: PathBuf = dirs::home_dir().expect("failed to determine home directory");
7 pub static ref CONFIG_DIR: PathBuf = HOME.join(".config").join("zed");
8 pub static ref CONVERSATIONS_DIR: PathBuf = HOME.join(".config/zed/conversations");
9 pub static ref EMBEDDINGS_DIR: PathBuf = HOME.join(".config/zed/embeddings");
10 pub static ref LOGS_DIR: PathBuf = HOME.join("Library/Logs/Zed");
11 pub static ref SUPPORT_DIR: PathBuf = HOME.join("Library/Application Support/Zed");
12 pub static ref LANGUAGES_DIR: PathBuf = HOME.join("Library/Application Support/Zed/languages");
13 pub static ref COPILOT_DIR: PathBuf = HOME.join("Library/Application Support/Zed/copilot");
14 pub static ref DB_DIR: PathBuf = HOME.join("Library/Application Support/Zed/db");
15 pub static ref SETTINGS: PathBuf = CONFIG_DIR.join("settings.json");
16 pub static ref KEYMAP: PathBuf = CONFIG_DIR.join("keymap.json");
17 pub static ref LAST_USERNAME: PathBuf = CONFIG_DIR.join("last-username.txt");
18 pub static ref LOG: PathBuf = LOGS_DIR.join("Zed.log");
19 pub static ref OLD_LOG: PathBuf = LOGS_DIR.join("Zed.log.old");
20 pub static ref LOCAL_SETTINGS_RELATIVE_PATH: &'static Path = Path::new(".zed/settings.json");
21}
22
23pub mod legacy {
24 use std::path::PathBuf;
25
26 lazy_static::lazy_static! {
27 static ref CONFIG_DIR: PathBuf = super::HOME.join(".zed");
28 pub static ref SETTINGS: PathBuf = CONFIG_DIR.join("settings.json");
29 pub static ref KEYMAP: PathBuf = CONFIG_DIR.join("keymap.json");
30 }
31}
32
33pub trait PathExt {
34 fn compact(&self) -> PathBuf;
35 fn icon_suffix(&self) -> Option<&str>;
36}
37
38impl<T: AsRef<Path>> PathExt for T {
39 /// Compacts a given file path by replacing the user's home directory
40 /// prefix with a tilde (`~`).
41 ///
42 /// # Returns
43 ///
44 /// * A `PathBuf` containing the compacted file path. If the input path
45 /// does not have the user's home directory prefix, or if we are not on
46 /// Linux or macOS, the original path is returned unchanged.
47 fn compact(&self) -> PathBuf {
48 if cfg!(target_os = "linux") || cfg!(target_os = "macos") {
49 match self.as_ref().strip_prefix(HOME.as_path()) {
50 Ok(relative_path) => {
51 let mut shortened_path = PathBuf::new();
52 shortened_path.push("~");
53 shortened_path.push(relative_path);
54 shortened_path
55 }
56 Err(_) => self.as_ref().to_path_buf(),
57 }
58 } else {
59 self.as_ref().to_path_buf()
60 }
61 }
62
63 fn icon_suffix(&self) -> Option<&str> {
64 let file_name = self.as_ref().file_name()?.to_str()?;
65
66 if file_name.starts_with(".") {
67 return file_name.strip_prefix(".");
68 }
69
70 self.as_ref()
71 .extension()
72 .map(|extension| extension.to_str())
73 .flatten()
74 }
75}
76
77/// A delimiter to use in `path_query:row_number:column_number` strings parsing.
78pub const FILE_ROW_COLUMN_DELIMITER: char = ':';
79
80/// A representation of a path-like string with optional row and column numbers.
81/// Matching values example: `te`, `test.rs:22`, `te:22:5`, etc.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct PathLikeWithPosition<P> {
84 pub path_like: P,
85 pub row: Option<u32>,
86 // Absent if row is absent.
87 pub column: Option<u32>,
88}
89
90impl<P> PathLikeWithPosition<P> {
91 /// Parses a string that possibly has `:row:column` suffix.
92 /// Ignores trailing `:`s, so `test.rs:22:` is parsed as `test.rs:22`.
93 /// If any of the row/column component parsing fails, the whole string is then parsed as a path like.
94 pub fn parse_str<E>(
95 s: &str,
96 parse_path_like_str: impl Fn(&str) -> Result<P, E>,
97 ) -> Result<Self, E> {
98 let fallback = |fallback_str| {
99 Ok(Self {
100 path_like: parse_path_like_str(fallback_str)?,
101 row: None,
102 column: None,
103 })
104 };
105
106 match s.trim().split_once(FILE_ROW_COLUMN_DELIMITER) {
107 Some((path_like_str, maybe_row_and_col_str)) => {
108 let path_like_str = path_like_str.trim();
109 let maybe_row_and_col_str = maybe_row_and_col_str.trim();
110 if path_like_str.is_empty() {
111 fallback(s)
112 } else if maybe_row_and_col_str.is_empty() {
113 fallback(path_like_str)
114 } else {
115 let (row_parse_result, maybe_col_str) =
116 match maybe_row_and_col_str.split_once(FILE_ROW_COLUMN_DELIMITER) {
117 Some((maybe_row_str, maybe_col_str)) => {
118 (maybe_row_str.parse::<u32>(), maybe_col_str.trim())
119 }
120 None => (maybe_row_and_col_str.parse::<u32>(), ""),
121 };
122
123 match row_parse_result {
124 Ok(row) => {
125 if maybe_col_str.is_empty() {
126 Ok(Self {
127 path_like: parse_path_like_str(path_like_str)?,
128 row: Some(row),
129 column: None,
130 })
131 } else {
132 match maybe_col_str.parse::<u32>() {
133 Ok(col) => Ok(Self {
134 path_like: parse_path_like_str(path_like_str)?,
135 row: Some(row),
136 column: Some(col),
137 }),
138 Err(_) => fallback(s),
139 }
140 }
141 }
142 Err(_) => fallback(s),
143 }
144 }
145 }
146 None => fallback(s),
147 }
148 }
149
150 pub fn map_path_like<P2, E>(
151 self,
152 mapping: impl FnOnce(P) -> Result<P2, E>,
153 ) -> Result<PathLikeWithPosition<P2>, E> {
154 Ok(PathLikeWithPosition {
155 path_like: mapping(self.path_like)?,
156 row: self.row,
157 column: self.column,
158 })
159 }
160
161 pub fn to_string(&self, path_like_to_string: impl Fn(&P) -> String) -> String {
162 let path_like_string = path_like_to_string(&self.path_like);
163 if let Some(row) = self.row {
164 if let Some(column) = self.column {
165 format!("{path_like_string}:{row}:{column}")
166 } else {
167 format!("{path_like_string}:{row}")
168 }
169 } else {
170 path_like_string
171 }
172 }
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178
179 type TestPath = PathLikeWithPosition<String>;
180
181 fn parse_str(s: &str) -> TestPath {
182 TestPath::parse_str(s, |s| Ok::<_, std::convert::Infallible>(s.to_string()))
183 .expect("infallible")
184 }
185
186 #[test]
187 fn path_with_position_parsing_positive() {
188 let input_and_expected = [
189 (
190 "test_file.rs",
191 PathLikeWithPosition {
192 path_like: "test_file.rs".to_string(),
193 row: None,
194 column: None,
195 },
196 ),
197 (
198 "test_file.rs:1",
199 PathLikeWithPosition {
200 path_like: "test_file.rs".to_string(),
201 row: Some(1),
202 column: None,
203 },
204 ),
205 (
206 "test_file.rs:1:2",
207 PathLikeWithPosition {
208 path_like: "test_file.rs".to_string(),
209 row: Some(1),
210 column: Some(2),
211 },
212 ),
213 ];
214
215 for (input, expected) in input_and_expected {
216 let actual = parse_str(input);
217 assert_eq!(
218 actual, expected,
219 "For positive case input str '{input}', got a parse mismatch"
220 );
221 }
222 }
223
224 #[test]
225 fn path_with_position_parsing_negative() {
226 for input in [
227 "test_file.rs:a",
228 "test_file.rs:a:b",
229 "test_file.rs::",
230 "test_file.rs::1",
231 "test_file.rs:1::",
232 "test_file.rs::1:2",
233 "test_file.rs:1::2",
234 "test_file.rs:1:2:",
235 "test_file.rs:1:2:3",
236 ] {
237 let actual = parse_str(input);
238 assert_eq!(
239 actual,
240 PathLikeWithPosition {
241 path_like: input.to_string(),
242 row: None,
243 column: None,
244 },
245 "For negative case input str '{input}', got a parse mismatch"
246 );
247 }
248 }
249
250 // Trim off trailing `:`s for otherwise valid input.
251 #[test]
252 fn path_with_position_parsing_special() {
253 let input_and_expected = [
254 (
255 "test_file.rs:",
256 PathLikeWithPosition {
257 path_like: "test_file.rs".to_string(),
258 row: None,
259 column: None,
260 },
261 ),
262 (
263 "test_file.rs:1:",
264 PathLikeWithPosition {
265 path_like: "test_file.rs".to_string(),
266 row: Some(1),
267 column: None,
268 },
269 ),
270 ];
271
272 for (input, expected) in input_and_expected {
273 let actual = parse_str(input);
274 assert_eq!(
275 actual, expected,
276 "For special case input str '{input}', got a parse mismatch"
277 );
278 }
279 }
280
281 #[test]
282 fn test_path_compact() {
283 let path: PathBuf = [
284 HOME.to_string_lossy().to_string(),
285 "some_file.txt".to_string(),
286 ]
287 .iter()
288 .collect();
289 if cfg!(target_os = "linux") || cfg!(target_os = "macos") {
290 assert_eq!(path.compact().to_str(), Some("~/some_file.txt"));
291 } else {
292 assert_eq!(path.compact().to_str(), path.to_str());
293 }
294 }
295
296 #[test]
297 fn test_path_suffix() {
298 // No dots in name
299 let path = Path::new("/a/b/c/file_name.rs");
300 assert_eq!(path.icon_suffix(), Some("rs"));
301
302 // Single dot in name
303 let path = Path::new("/a/b/c/file.name.rs");
304 assert_eq!(path.icon_suffix(), Some("rs"));
305
306 // Multiple dots in name
307 let path = Path::new("/a/b/c/long.file.name.rs");
308 assert_eq!(path.icon_suffix(), Some("rs"));
309
310 // Hidden file, no extension
311 let path = Path::new("/a/b/c/.gitignore");
312 assert_eq!(path.icon_suffix(), Some("gitignore"));
313
314 // Hidden file, with extension
315 let path = Path::new("/a/b/c/.eslintrc.js");
316 assert_eq!(path.icon_suffix(), Some("eslintrc.js"));
317 }
318}