Debian Codegraph @

helix-term/src/config.rs

raw symbols SCIP
1 use crate::keymap;
2 use crate::keymap::{merge_keys, KeyTrie};
3 use helix_loader::merge_toml_values;
4 use helix_view::{document::Mode, theme};
5 use serde::Deserialize;
6 use std::collections::HashMap;
7 use std::fmt::Display;
8 use std::fs;
9 use std::io::Error as IOError;
10 use toml::de::Error as TomlError;
11
12 #[derive(Debug, Clone, PartialEq)]
13 pub struct Config {
14 pub theme: Option<theme::Config>,
15 pub keys: HashMap<Mode, KeyTrie>,
16 pub editor: helix_view::editor::Config,
17 }
18
19 #[derive(Debug, Clone, PartialEq, Deserialize)]
20 #[serde(deny_unknown_fields)]
21 pub struct ConfigRaw {
22 pub theme: Option<theme::Config>,
23 pub keys: Option<HashMap<Mode, KeyTrie>>,
24 pub editor: Option<toml::Value>,
25 }
26
27 impl Default for Config {
28 fn default() -> Config {
29 Config {
30 theme: None,
31 keys: keymap::default(),
32 editor: helix_view::editor::Config::default(),
33 }
34 }
35 }
36
37 #[derive(Debug)]
38 pub enum ConfigLoadError {
39 BadConfig(TomlError),
40 Error(IOError),
41 }
42
43 impl Default for ConfigLoadError {
44 fn default() -> Self {
45 ConfigLoadError::Error(IOError::new(std::io::ErrorKind::NotFound, "place holder"))
46 }
47 }
48
49 impl Display for ConfigLoadError {
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 match self {
52 ConfigLoadError::BadConfig(err) => err.fmt(f),
53 ConfigLoadError::Error(err) => err.fmt(f),
54 }
55 }
56 }
57
58 impl Config {
59 pub fn load(
60 global: Result<&String, ConfigLoadError>,
61 local: Result<String, ConfigLoadError>,
62 ) -> Result<Config, ConfigLoadError> {
63 let global_config: Result<ConfigRaw, ConfigLoadError> =
64 global.and_then(|file| toml::from_str(file).map_err(ConfigLoadError::BadConfig));
65 let local_config: Result<ConfigRaw, ConfigLoadError> =
66 local.and_then(|file| toml::from_str(&file).map_err(ConfigLoadError::BadConfig));
67 let res = match (global_config, local_config) {
68 (Ok(global), Ok(local)) => {
69 let mut keys = keymap::default();
70 if let Some(global_keys) = global.keys {
71 merge_keys(&mut keys, global_keys)
72 }
73 if let Some(local_keys) = local.keys {
74 merge_keys(&mut keys, local_keys)
75 }
76
77 let editor = match (global.editor, local.editor) {
78 (None, None) => helix_view::editor::Config::default(),
79 (None, Some(val)) | (Some(val), None) => {
80 val.try_into().map_err(ConfigLoadError::BadConfig)?
81 }
82 (Some(global), Some(local)) => merge_toml_values(global, local, 3)
83 .try_into()
84 .map_err(ConfigLoadError::BadConfig)?,
85 };
86
87 Config {
88 theme: local.theme.or(global.theme),
89 keys,
90 editor,
91 }
92 }
93 // if any configs are invalid return that first
94 (_, Err(ConfigLoadError::BadConfig(err)))
95 | (Err(ConfigLoadError::BadConfig(err)), _) => {
96 return Err(ConfigLoadError::BadConfig(err))
97 }
98 (Ok(config), Err(_)) | (Err(_), Ok(config)) => {
99 let mut keys = keymap::default();
100 if let Some(keymap) = config.keys {
101 merge_keys(&mut keys, keymap);
102 }
103 Config {
104 theme: config.theme,
105 keys,
106 editor: config.editor.map_or_else(
107 || Ok(helix_view::editor::Config::default()),
108 |val| val.try_into().map_err(ConfigLoadError::BadConfig),
109 )?,
110 }
111 }
112
113 // these are just two io errors return the one for the global config
114 (Err(err), Err(_)) => return Err(err),
115 };
116
117 Ok(res)
118 }
119
120 pub fn load_default() -> Result<Config, ConfigLoadError> {
121 let global_config =
122 fs::read_to_string(helix_loader::config_file()).map_err(ConfigLoadError::Error)?;
123 let local_config = fs::read_to_string(helix_loader::workspace_config_file())
124 .map_err(ConfigLoadError::Error);
125
126 let phony_config = ConfigLoadError::Error(IOError::other("hacky placeholder"));
127 let global_parsed = Config::load(Ok(&global_config), Err(phony_config))?;
128
129 // We need to build a transient `WorkspaceTrust` just to ask whether the workspace is
130 // trusted enough to load its `.helix/config.toml`. The persisted-trust file on disk is the
131 // source of truth either way; this transient instance has an empty cache and is dropped
132 // after the check.
133 let trust = helix_loader::workspace_trust::WorkspaceTrust::new(
134 (&global_parsed.editor.workspace_trust).into(),
135 );
136 if trust
137 .query_current(helix_loader::workspace_trust::TrustQuery::LocalConfig)
138 .is_trusted()
139 {
140 let mut merged = Config::load(Ok(&global_config), local_config)?;
141 // editor.workspace-trust is global/user-scope only. Without this override, a
142 // workspace's `.helix/config.toml` could set `level = "insecure"`; once the user trusted
143 // *that* workspace, refresh_config would re-load with the override merged in and from
144 // then on every subsequent workspace in the session would be implicitly trusted. Pin
145 // the gate's own configuration to the global file.
146 merged.editor.workspace_trust = global_parsed.editor.workspace_trust;
147 Ok(merged)
148 } else {
149 Ok(global_parsed)
150 }
151 }
152 }
153
154 #[cfg(test)]
155 mod tests {
156 use super::*;
157
158 impl Config {
159 fn load_test(config: &str) -> Config {
160 Config::load(Ok(&config.to_owned()), Err(ConfigLoadError::default())).unwrap()
161 }
162 }
163
164 #[test]
165 fn parsing_keymaps_config_file() {
166 use crate::keymap;
167 use helix_core::hashmap;
168 use helix_view::document::Mode;
169
170 let sample_keymaps = r#"
171 [keys.insert]
172 y = "move_line_down"
173 S-C-a = "delete_selection"
174
175 [keys.normal]
176 A-F12 = "move_next_word_end"
177 "#;
178
179 let mut keys = keymap::default();
180 merge_keys(
181 &mut keys,
182 hashmap! {
183 Mode::Insert => keymap!({ "Insert mode"
184 "y" => move_line_down,
185 "S-C-a" => delete_selection,
186 }),
187 Mode::Normal => keymap!({ "Normal mode"
188 "A-F12" => move_next_word_end,
189 }),
190 },
191 );
192
193 assert_eq!(
194 Config::load_test(sample_keymaps),
195 Config {
196 keys,
197 ..Default::default()
198 }
199 );
200 }
201
202 #[test]
203 fn keys_resolve_to_correct_defaults() {
204 // From serde default
205 let default_keys = Config::load_test("").keys;
206 assert_eq!(default_keys, keymap::default());
207
208 // From the Default trait
209 let default_keys = Config::default().keys;
210 assert_eq!(default_keys, keymap::default());
211 }
212 }