Debian Codegraph @

helix-loader/src/lib.rs

raw symbols SCIP
1 pub mod config;
2 pub mod grammar;
3 pub mod workspace_trust;
4
5 use helix_stdx::{env::current_working_dir, path};
6
7 use etcetera::base_strategy::{choose_base_strategy, BaseStrategy};
8 use std::path::{Path, PathBuf};
9
10 pub const VERSION_AND_GIT_HASH: &str = env!("VERSION_AND_GIT_HASH");
11
12 static RUNTIME_DIRS: once_cell::sync::Lazy<Vec<PathBuf>> =
13 once_cell::sync::Lazy::new(prioritize_runtime_dirs);
14
15 static CONFIG_FILE: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCell::new();
16
17 static LOG_FILE: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCell::new();
18
19 pub fn initialize_config_file(specified_file: Option<PathBuf>) {
20 let config_file = specified_file.unwrap_or_else(default_config_file);
21 ensure_parent_dir(&config_file);
22 CONFIG_FILE.set(config_file).ok();
23 }
24
25 pub fn initialize_log_file(specified_file: Option<PathBuf>) {
26 let log_file = specified_file.unwrap_or_else(default_log_file);
27 ensure_parent_dir(&log_file);
28 LOG_FILE.set(log_file).ok();
29 }
30
31 /// A list of runtime directories from highest to lowest priority
32 ///
33 /// The priority is:
34 ///
35 /// 1. sibling directory to `CARGO_MANIFEST_DIR` (if environment variable is set)
36 /// 2. subdirectory of user config directory (always included)
37 /// 3. `HELIX_RUNTIME` (if environment variable is set)
38 /// 4. `HELIX_DEFAULT_RUNTIME` (if environment variable is set *at build time*)
39 /// 5. subdirectory of path to helix executable (always included)
40 ///
41 /// Postcondition: returns at least two paths (they might not exist).
42 fn prioritize_runtime_dirs() -> Vec<PathBuf> {
43 const RT_DIR: &str = "runtime";
44 // Adding higher priority first
45 let mut rt_dirs = Vec::new();
46 if let Ok(dir) = std::env::var("CARGO_MANIFEST_DIR") {
47 // this is the directory of the crate being run by cargo, we need the workspace path so we take the parent
48 let path = PathBuf::from(dir).parent().unwrap().join(RT_DIR);
49 log::debug!("runtime dir: {}", path.to_string_lossy());
50 rt_dirs.push(path);
51 }
52
53 let conf_rt_dir = config_dir().join(RT_DIR);
54 rt_dirs.push(conf_rt_dir);
55
56 if let Ok(dir) = std::env::var("HELIX_RUNTIME") {
57 let dir = path::expand_tilde(Path::new(&dir));
58 rt_dirs.push(path::normalize(dir));
59 }
60
61 // If this variable is set during build time, it will always be included
62 // in the lookup list. This allows downstream packagers to set a fallback
63 // directory to a location that is conventional on their distro so that they
64 // need not resort to a wrapper script or a global environment variable.
65 if let Some(dir) = std::option_env!("HELIX_DEFAULT_RUNTIME") {
66 rt_dirs.push(dir.into());
67 }
68
69 // fallback to location of the executable being run
70 // canonicalize the path in case the executable is symlinked
71 let exe_rt_dir = std::env::current_exe()
72 .ok()
73 .and_then(|path| std::fs::canonicalize(path).ok())
74 .and_then(|path| path.parent().map(|path| path.to_path_buf().join(RT_DIR)))
75 .unwrap();
76 rt_dirs.push(exe_rt_dir);
77 rt_dirs
78 }
79
80 /// Runtime directories ordered from highest to lowest priority
81 ///
82 /// All directories should be checked when looking for files.
83 ///
84 /// Postcondition: returns at least one path (it might not exist).
85 pub fn runtime_dirs() -> &'static [PathBuf] {
86 &RUNTIME_DIRS
87 }
88
89 /// Find file with path relative to runtime directory
90 ///
91 /// `rel_path` should be the relative path from within the `runtime/` directory.
92 /// The valid runtime directories are searched in priority order and the first
93 /// file found to exist is returned, otherwise None.
94 fn find_runtime_file(rel_path: &Path) -> Option<PathBuf> {
95 RUNTIME_DIRS.iter().find_map(|rt_dir| {
96 let path = rt_dir.join(rel_path);
97 if path.exists() {
98 Some(path)
99 } else {
100 None
101 }
102 })
103 }
104
105 /// Find file with path relative to runtime directory
106 ///
107 /// `rel_path` should be the relative path from within the `runtime/` directory.
108 /// The valid runtime directories are searched in priority order and the first
109 /// file found to exist is returned, otherwise the path to the final attempt
110 /// that failed.
111 pub fn runtime_file(rel_path: impl AsRef<Path>) -> PathBuf {
112 find_runtime_file(rel_path.as_ref()).unwrap_or_else(|| {
113 RUNTIME_DIRS
114 .last()
115 .map(|dir| dir.join(rel_path))
116 .unwrap_or_default()
117 })
118 }
119
120 pub fn config_dir() -> PathBuf {
121 // TODO: allow env var override
122 let strategy = choose_base_strategy().expect("Unable to find the config directory!");
123 let mut path = strategy.config_dir();
124 path.push("helix");
125 path
126 }
127
128 pub fn cache_dir() -> PathBuf {
129 // TODO: allow env var override
130 let strategy = choose_base_strategy().expect("Unable to find the cache directory!");
131 let mut path = strategy.cache_dir();
132 path.push("helix");
133 path
134 }
135
136 pub fn data_dir() -> PathBuf {
137 let strategy = choose_base_strategy().expect("Unable to find the data directory!");
138 let mut path = strategy.data_dir();
139 path.push("helix");
140 path
141 }
142
143 pub fn config_file() -> PathBuf {
144 CONFIG_FILE.get().map(|path| path.to_path_buf()).unwrap()
145 }
146
147 pub fn log_file() -> PathBuf {
148 LOG_FILE.get().map(|path| path.to_path_buf()).unwrap()
149 }
150
151 pub fn workspace_config_file() -> PathBuf {
152 find_workspace().0.join(".helix").join("config.toml")
153 }
154
155 pub fn workspace_lang_config_file() -> PathBuf {
156 find_workspace().0.join(".helix").join("languages.toml")
157 }
158
159 pub fn lang_config_file() -> PathBuf {
160 config_dir().join("languages.toml")
161 }
162
163 pub fn default_log_file() -> PathBuf {
164 cache_dir().join("helix.log")
165 }
166
167 /// Merge two TOML documents, merging values from `right` onto `left`
168 ///
169 /// `merge_depth` sets the nesting depth up to which values are merged instead
170 /// of overridden.
171 ///
172 /// When a table exists in both `left` and `right`, the merged table consists of
173 /// all keys in `left`'s table unioned with all keys in `right` with the values
174 /// of `right` being merged recursively onto values of `left`.
175 ///
176 /// `crate::merge_toml_values(a, b, 3)` combines, for example:
177 ///
178 /// b:
179 /// ```toml
180 /// [[language]]
181 /// name = "toml"
182 /// language-server = { command = "taplo", args = ["lsp", "stdio"] }
183 /// ```
184 /// a:
185 /// ```toml
186 /// [[language]]
187 /// language-server = { command = "/usr/bin/taplo" }
188 /// ```
189 ///
190 /// into:
191 /// ```toml
192 /// [[language]]
193 /// name = "toml"
194 /// language-server = { command = "/usr/bin/taplo" }
195 /// ```
196 ///
197 /// thus it overrides the third depth-level of b with values of a if they exist,
198 /// but otherwise merges their values
199 pub fn merge_toml_values(left: toml::Value, right: toml::Value, merge_depth: usize) -> toml::Value {
200 use toml::Value;
201
202 fn get_name(v: &Value) -> Option<&str> {
203 v.get("name").and_then(Value::as_str)
204 }
205
206 match (left, right) {
207 (Value::Array(mut left_items), Value::Array(right_items)) => {
208 if merge_depth > 0 {
209 left_items.reserve(right_items.len());
210 for rvalue in right_items {
211 let lvalue = get_name(&rvalue)
212 .and_then(|rname| {
213 left_items.iter().position(|v| get_name(v) == Some(rname))
214 })
215 .map(|lpos| left_items.remove(lpos));
216 let mvalue = match lvalue {
217 Some(lvalue) => merge_toml_values(lvalue, rvalue, merge_depth - 1),
218 None => rvalue,
219 };
220 left_items.push(mvalue);
221 }
222 Value::Array(left_items)
223 } else {
224 Value::Array(right_items)
225 }
226 }
227 (Value::Table(mut left_map), Value::Table(right_map)) => {
228 if merge_depth > 0 {
229 for (rname, rvalue) in right_map {
230 match left_map.remove(&rname) {
231 Some(lvalue) => {
232 let merged_value = merge_toml_values(lvalue, rvalue, merge_depth - 1);
233 left_map.insert(rname, merged_value);
234 }
235 None => {
236 left_map.insert(rname, rvalue);
237 }
238 }
239 }
240 Value::Table(left_map)
241 } else {
242 Value::Table(right_map)
243 }
244 }
245 // Catch everything else we didn't handle, and use the right value
246 (_, value) => value,
247 }
248 }
249
250 /// Finds the current workspace folder.
251 /// Used as a ceiling dir for LSP root resolution, the filepicker and potentially as a future filewatching root
252 ///
253 /// This function starts searching the FS upward from the CWD
254 /// and returns the first directory that contains either `.git`, `.svn`, `.jj` or `.helix`.
255 /// If no workspace was found returns (CWD, true).
256 /// Otherwise (workspace, false) is returned
257 pub fn find_workspace() -> (PathBuf, bool) {
258 let current_dir = current_working_dir();
259 find_workspace_in(current_dir)
260 }
261
262 pub fn find_workspace_in(dir: impl AsRef<Path>) -> (PathBuf, bool) {
263 let dir = dir.as_ref();
264 for ancestor in dir.ancestors() {
265 if ancestor.join(".git").exists()
266 || ancestor.join(".svn").exists()
267 || ancestor.join(".jj").exists()
268 || ancestor.join(".helix").exists()
269 {
270 return (ancestor.to_owned(), false);
271 }
272 }
273
274 (dir.to_owned(), true)
275 }
276
277 fn default_config_file() -> PathBuf {
278 config_dir().join("config.toml")
279 }
280
281 fn ensure_parent_dir(path: &Path) {
282 if let Some(parent) = path.parent() {
283 if !parent.exists() {
284 std::fs::create_dir_all(parent).ok();
285 }
286 }
287 }
288
289 #[cfg(test)]
290 mod merge_toml_tests {
291 use std::str;
292
293 use super::merge_toml_values;
294 use toml::Value;
295
296 #[test]
297 fn language_toml_map_merges() {
298 const USER: &str = r#"
299 [[language]]
300 name = "nix"
301 test = "bbb"
302 indent = { tab-width = 4, unit = " ", test = "aaa" }
303 "#;
304
305 let base = include_bytes!("../../languages.toml");
306 let base = str::from_utf8(base).expect("Couldn't parse built-in languages config");
307 let base: Value = toml::from_str(base).expect("Couldn't parse built-in languages config");
308 let user: Value = toml::from_str(USER).unwrap();
309
310 let merged = merge_toml_values(base, user, 3);
311 let languages = merged.get("language").unwrap().as_array().unwrap();
312 let nix = languages
313 .iter()
314 .find(|v| v.get("name").unwrap().as_str().unwrap() == "nix")
315 .unwrap();
316 let nix_indent = nix.get("indent").unwrap();
317
318 // We changed tab-width and unit in indent so check them if they are the new values
319 assert_eq!(
320 nix_indent.get("tab-width").unwrap().as_integer().unwrap(),
321 4
322 );
323 assert_eq!(nix_indent.get("unit").unwrap().as_str().unwrap(), " ");
324 // We added a new keys, so check them
325 assert_eq!(nix.get("test").unwrap().as_str().unwrap(), "bbb");
326 assert_eq!(nix_indent.get("test").unwrap().as_str().unwrap(), "aaa");
327 // We didn't change comment-token so it should be same
328 assert_eq!(nix.get("comment-token").unwrap().as_str().unwrap(), "#");
329 }
330
331 #[test]
332 fn language_toml_nested_array_merges() {
333 const USER: &str = r#"
334 [[language]]
335 name = "typescript"
336 language-server = { command = "deno", args = ["lsp"] }
337 "#;
338
339 let base = include_bytes!("../../languages.toml");
340 let base = str::from_utf8(base).expect("Couldn't parse built-in languages config");
341 let base: Value = toml::from_str(base).expect("Couldn't parse built-in languages config");
342 let user: Value = toml::from_str(USER).unwrap();
343
344 let merged = merge_toml_values(base, user, 3);
345 let languages = merged.get("language").unwrap().as_array().unwrap();
346 let ts = languages
347 .iter()
348 .find(|v| v.get("name").unwrap().as_str().unwrap() == "typescript")
349 .unwrap();
350 assert_eq!(
351 ts.get("language-server")
352 .unwrap()
353 .get("args")
354 .unwrap()
355 .as_array()
356 .unwrap(),
357 &vec![Value::String("lsp".into())]
358 )
359 }
360 }