on 376c19e help sign in
251 lines 9.0 kB history raw
1pub mod config;
2pub mod grammar;
4use etcetera::base_strategy::{choose_base_strategy, BaseStrategy};
5use std::path::PathBuf;
7pub const VERSION_AND_GIT_HASH: &str = env!("VERSION_AND_GIT_HASH");
9pub static RUNTIME_DIR: once_cell::sync::Lazy<PathBuf> = once_cell::sync::Lazy::new(runtime_dir);
11static CONFIG_FILE: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCell::new();
13pub fn initialize_config_file(specified_file: Option<PathBuf>) {
14 let config_file = specified_file.unwrap_or_else(|| {
15 let config_dir = config_dir();
17 if !config_dir.exists() {
18 std::fs::create_dir_all(&config_dir).ok();
19 }
21 config_dir.join("config.toml")
22 });
24 // We should only initialize this value once.
25 CONFIG_FILE.set(config_file).ok();
28pub fn runtime_dir() -> PathBuf {
29 if let Ok(dir) = std::env::var("HELIX_RUNTIME") {
30 return dir.into();
31 }
33 if let Ok(dir) = std::env::var("CARGO_MANIFEST_DIR") {
34 // this is the directory of the crate being run by cargo, we need the workspace path so we take the parent
35 let path = std::path::PathBuf::from(dir).parent().unwrap().join(RT_DIR);
36 log::debug!("runtime dir: {}", path.to_string_lossy());
37 return path;
38 }
40 const RT_DIR: &str = "runtime";
41 let conf_dir = config_dir().join(RT_DIR);
42 if conf_dir.exists() {
43 return conf_dir;
44 }
46 // fallback to location of the executable being run
47 // canonicalize the path in case the executable is symlinked
48 std::env::current_exe()
49 .ok()
50 .and_then(|path| std::fs::canonicalize(path).ok())
51 .and_then(|path| path.parent().map(|path| path.to_path_buf().join(RT_DIR)))
52 .unwrap()
55pub fn config_dir() -> PathBuf {
56 // TODO: allow env var override
57 let strategy = choose_base_strategy().expect("Unable to find the config directory!");
58 let mut path = strategy.config_dir();
59 path.push("helix");
60 path
63pub fn local_config_dirs() -> Vec<PathBuf> {
64 let directories = find_local_config_dirs()
65 .into_iter()
66 .map(|path| path.join(".helix"))
67 .collect();
68 log::debug!("Located configuration folders: {:?}", directories);
69 directories
72pub fn cache_dir() -> PathBuf {
73 // TODO: allow env var override
74 let strategy = choose_base_strategy().expect("Unable to find the config directory!");
75 let mut path = strategy.cache_dir();
76 path.push("helix");
77 path
80pub fn config_file() -> PathBuf {
81 CONFIG_FILE
82 .get()
83 .map(|path| path.to_path_buf())
84 .unwrap_or_else(|| config_dir().join("config.toml"))
87pub fn lang_config_file() -> PathBuf {
88 config_dir().join("languages.toml")
91pub fn log_file() -> PathBuf {
92 cache_dir().join("helix.log")
95pub fn find_local_config_dirs() -> Vec<PathBuf> {
96 let current_dir = std::env::current_dir().expect("unable to determine current directory");
97 let mut directories = Vec::new();
99 for ancestor in current_dir.ancestors() {
100 if ancestor.join(".git").exists() {
101 directories.push(ancestor.to_path_buf());
102 // Don't go higher than repo if we're in one
103 break;
104 } else if ancestor.join(".helix").is_dir() {
105 directories.push(ancestor.to_path_buf());
106 }
107 }
108 directories
111/// Merge two TOML documents, merging values from `right` onto `left`
112///
113/// When an array exists in both `left` and `right`, `right`'s array is
114/// used. When a table exists in both `left` and `right`, the merged table
115/// consists of all keys in `left`'s table unioned with all keys in `right`
116/// with the values of `right` being merged recursively onto values of
117/// `left`.
118///
119/// `merge_toplevel_arrays` controls whether a top-level array in the TOML
120/// document is merged instead of overridden. This is useful for TOML
121/// documents that use a top-level array of values like the `languages.toml`,
122/// where one usually wants to override or add to the array instead of
123/// replacing it altogether.
124pub fn merge_toml_values(left: toml::Value, right: toml::Value, merge_depth: usize) -> toml::Value {
125 use toml::Value;
127 fn get_name(v: &Value) -> Option<&str> {
128 v.get("name").and_then(Value::as_str)
129 }
131 match (left, right) {
132 (Value::Array(mut left_items), Value::Array(right_items)) => {
133 // The top-level arrays should be merged but nested arrays should
134 // act as overrides. For the `languages.toml` config, this means
135 // that you can specify a sub-set of languages in an overriding
136 // `languages.toml` but that nested arrays like Language Server
137 // arguments are replaced instead of merged.
138 if merge_depth > 0 {
139 left_items.reserve(right_items.len());
140 for rvalue in right_items {
141 let lvalue = get_name(&rvalue)
142 .and_then(|rname| {
143 left_items.iter().position(|v| get_name(v) == Some(rname))
144 })
145 .map(|lpos| left_items.remove(lpos));
146 let mvalue = match lvalue {
147 Some(lvalue) => merge_toml_values(lvalue, rvalue, merge_depth - 1),
148 None => rvalue,
149 };
150 left_items.push(mvalue);
151 }
152 Value::Array(left_items)
153 } else {
154 Value::Array(right_items)
155 }
156 }
157 (Value::Table(mut left_map), Value::Table(right_map)) => {
158 if merge_depth > 0 {
159 for (rname, rvalue) in right_map {
160 match left_map.remove(&rname) {
161 Some(lvalue) => {
162 let merged_value = merge_toml_values(lvalue, rvalue, merge_depth - 1);
163 left_map.insert(rname, merged_value);
164 }
165 None => {
166 left_map.insert(rname, rvalue);
167 }
168 }
169 }
170 Value::Table(left_map)
171 } else {
172 Value::Table(right_map)
173 }
174 }
175 // Catch everything else we didn't handle, and use the right value
176 (_, value) => value,
177 }
180#[cfg(test)]
181mod merge_toml_tests {
182 use std::str;
184 use super::merge_toml_values;
185 use toml::Value;
187 #[test]
188 fn language_toml_map_merges() {
189 const USER: &str = r#"
190 [[language]]
191 name = "nix"
192 test = "bbb"
193 indent = { tab-width = 4, unit = " ", test = "aaa" }
194 "#;
196 let base = include_bytes!("../../languages.toml");
197 let base = str::from_utf8(base).expect("Couldn't parse built-in languages config");
198 let base: Value = toml::from_str(base).expect("Couldn't parse built-in languages config");
199 let user: Value = toml::from_str(USER).unwrap();
201 let merged = merge_toml_values(base, user, 3);
202 let languages = merged.get("language").unwrap().as_array().unwrap();
203 let nix = languages
204 .iter()
205 .find(|v| v.get("name").unwrap().as_str().unwrap() == "nix")
206 .unwrap();
207 let nix_indent = nix.get("indent").unwrap();
209 // We changed tab-width and unit in indent so check them if they are the new values
210 assert_eq!(
211 nix_indent.get("tab-width").unwrap().as_integer().unwrap(),
212 4
213 );
214 assert_eq!(nix_indent.get("unit").unwrap().as_str().unwrap(), " ");
215 // We added a new keys, so check them
216 assert_eq!(nix.get("test").unwrap().as_str().unwrap(), "bbb");
217 assert_eq!(nix_indent.get("test").unwrap().as_str().unwrap(), "aaa");
218 // We didn't change comment-token so it should be same
219 assert_eq!(nix.get("comment-token").unwrap().as_str().unwrap(), "#");
220 }
222 #[test]
223 fn language_toml_nested_array_merges() {
224 const USER: &str = r#"
225 [[language]]
226 name = "typescript"
227 language-server = { command = "deno", args = ["lsp"] }
228 "#;
230 let base = include_bytes!("../../languages.toml");
231 let base = str::from_utf8(base).expect("Couldn't parse built-in languages config");
232 let base: Value = toml::from_str(base).expect("Couldn't parse built-in languages config");
233 let user: Value = toml::from_str(USER).unwrap();
235 let merged = merge_toml_values(base, user, 3);
236 let languages = merged.get("language").unwrap().as_array().unwrap();
237 let ts = languages
238 .iter()
239 .find(|v| v.get("name").unwrap().as_str().unwrap() == "typescript")
240 .unwrap();
241 assert_eq!(
242 ts.get("language-server")
243 .unwrap()
244 .get("args")
245 .unwrap()
246 .as_array()
247 .unwrap(),
248 &vec![Value::String("lsp".into())]
249 )
250 }