Debian Codegraph @

helix-core/src/editor_config.rs

raw symbols SCIP
1 //! Support for [EditorConfig](https://EditorConfig.org) configuration loading.
2 //!
3 //! EditorConfig is an editor-agnostic format for specifying configuration in an INI-like, human
4 //! friendly syntax in `.editorconfig` files (which are intended to be checked into VCS). This
5 //! module provides functions to search for all `.editorconfig` files that apply to a given path
6 //! and returns an `EditorConfig` type containing any specified configuration options.
7 //!
8 //! At time of writing, this module follows the [spec](https://spec.editorconfig.org/) at
9 //! version 0.17.2.
10
11 use std::{
12 collections::HashMap,
13 fs,
14 num::{NonZeroU16, NonZeroU8},
15 path::Path,
16 str::FromStr,
17 };
18
19 use encoding_rs::Encoding;
20 use globset::{GlobBuilder, GlobMatcher};
21
22 use crate::{
23 indent::{IndentStyle, MAX_INDENT},
24 LineEnding,
25 };
26
27 /// Configuration declared for a path in `.editorconfig` files.
28 #[derive(Debug, Default, PartialEq, Eq)]
29 pub struct EditorConfig {
30 pub indent_style: Option<IndentStyle>,
31 pub tab_width: Option<NonZeroU8>,
32 pub line_ending: Option<LineEnding>,
33 pub encoding: Option<&'static Encoding>,
34 // pub spelling_language: Option<SpellingLanguage>,
35 pub trim_trailing_whitespace: Option<bool>,
36 pub insert_final_newline: Option<bool>,
37 pub max_line_length: Option<NonZeroU16>,
38 }
39
40 impl EditorConfig {
41 /// Finds any configuration in `.editorconfig` files which applies to the given path.
42 ///
43 /// If no configuration applies then `EditorConfig::default()` is returned.
44 pub fn find(path: &Path) -> Self {
45 let mut configs = Vec::new();
46 // <https://spec.editorconfig.org/#file-processing>
47 for ancestor in path.ancestors() {
48 let editor_config_file = ancestor.join(".editorconfig");
49 let Ok(contents) = fs::read_to_string(&editor_config_file) else {
50 continue;
51 };
52 let ini = match contents.parse::<Ini>() {
53 Ok(ini) => ini,
54 Err(err) => {
55 log::warn!("Ignoring EditorConfig file at '{editor_config_file:?}' because a glob failed to compile: {err}");
56 continue;
57 }
58 };
59 let is_root = ini.pairs.get("root").map(AsRef::as_ref) == Some("true");
60 configs.push((ini, ancestor));
61 // > The search shall stop if an EditorConfig file is found with the `root` key set to
62 // > `true` in the preamble or when reaching the root filesystem directory.
63 if is_root {
64 break;
65 }
66 }
67
68 let mut pairs = Pairs::new();
69 // Reverse the configuration stack so that the `.editorconfig` files closest to `path`
70 // are applied last and overwrite settings in files closer to the search ceiling.
71 //
72 // > If multiple EditorConfig files have matching sections, the pairs from the closer
73 // > EditorConfig file are read last, so pairs in closer files take precedence.
74 for (config, dir) in configs.into_iter().rev() {
75 let relative_path = path.strip_prefix(dir).expect("dir is an ancestor of path");
76
77 for section in config.sections {
78 if section.glob.is_match(relative_path) {
79 log::info!(
80 "applying EditorConfig from section '{}' in file {:?}",
81 section.glob.glob(),
82 dir.join(".editorconfig")
83 );
84 pairs.extend(section.pairs);
85 }
86 }
87 }
88
89 Self::from_pairs(pairs)
90 }
91
92 fn from_pairs(pairs: Pairs) -> Self {
93 enum IndentSize {
94 Tab,
95 Spaces(NonZeroU8),
96 }
97
98 // <https://spec.editorconfig.org/#supported-pairs>
99 let indent_size = pairs.get("indent_size").and_then(|value| {
100 if value.as_ref() == "tab" {
101 Some(IndentSize::Tab)
102 } else if let Ok(spaces) = value.parse::<NonZeroU8>() {
103 Some(IndentSize::Spaces(spaces))
104 } else {
105 None
106 }
107 });
108 let tab_width = pairs
109 .get("tab_width")
110 .and_then(|value| value.parse::<NonZeroU8>().ok())
111 .or(match indent_size {
112 Some(IndentSize::Spaces(spaces)) => Some(spaces),
113 _ => None,
114 });
115 let indent_style = pairs
116 .get("indent_style")
117 .and_then(|value| match value.as_ref() {
118 "tab" => Some(IndentStyle::Tabs),
119 "space" => {
120 let spaces = match indent_size {
121 Some(IndentSize::Spaces(spaces)) => spaces.get(),
122 Some(IndentSize::Tab) => tab_width.map(|n| n.get()).unwrap_or(4),
123 None => 4,
124 };
125 Some(IndentStyle::Spaces(spaces.clamp(1, MAX_INDENT)))
126 }
127 _ => None,
128 });
129 let line_ending = pairs
130 .get("end_of_line")
131 .and_then(|value| match value.as_ref() {
132 "lf" => Some(LineEnding::LF),
133 "crlf" => Some(LineEnding::Crlf),
134 #[cfg(feature = "unicode-lines")]
135 "cr" => Some(LineEnding::CR),
136 _ => None,
137 });
138 let encoding = pairs.get("charset").and_then(|value| match value.as_ref() {
139 "latin1" => Some(encoding_rs::WINDOWS_1252),
140 "utf-8" => Some(encoding_rs::UTF_8),
141 // `utf-8-bom` is intentionally ignored.
142 // > `utf-8-bom` is discouraged.
143 "utf-16le" => Some(encoding_rs::UTF_16LE),
144 "utf-16be" => Some(encoding_rs::UTF_16BE),
145 _ => None,
146 });
147 let trim_trailing_whitespace =
148 pairs
149 .get("trim_trailing_whitespace")
150 .and_then(|value| match value.as_ref() {
151 "true" => Some(true),
152 "false" => Some(false),
153 _ => None,
154 });
155 let insert_final_newline = pairs
156 .get("insert_final_newline")
157 .and_then(|value| match value.as_ref() {
158 "true" => Some(true),
159 "false" => Some(false),
160 _ => None,
161 });
162 // This option is not in the spec but is supported by some editors.
163 // <https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties#max_line_length>
164 let max_line_length = pairs
165 .get("max_line_length")
166 .and_then(|value| value.parse::<NonZeroU16>().ok());
167
168 Self {
169 indent_style,
170 tab_width,
171 line_ending,
172 encoding,
173 trim_trailing_whitespace,
174 insert_final_newline,
175 max_line_length,
176 }
177 }
178 }
179
180 type Pairs = HashMap<Box<str>, Box<str>>;
181
182 #[derive(Debug)]
183 struct Section {
184 glob: GlobMatcher,
185 pairs: Pairs,
186 }
187
188 #[derive(Debug, Default)]
189 struct Ini {
190 pairs: Pairs,
191 sections: Vec<Section>,
192 }
193
194 impl FromStr for Ini {
195 type Err = globset::Error;
196
197 fn from_str(source: &str) -> Result<Self, Self::Err> {
198 // <https://spec.editorconfig.org/#file-format>
199 let mut ini = Ini::default();
200 // > EditorConfig files are in an INI-like file format. To read an EditorConfig file, take
201 // > one line at a time, from beginning to end. For each line:
202 for full_line in source.lines() {
203 // > 1. Remove all leading and trailing whitespace.
204 let line = full_line.trim();
205 // > 2. Process the remaining text as specified for its type below.
206 // > The types of lines are:
207 // > * Blank: contains nothing. Blank lines are ignored.
208 if line.is_empty() {
209 continue;
210 }
211 // > * Comment: starts with a ';' or '#'. Comment lines are ignored.
212 if line.starts_with([';', '#']) {
213 continue;
214 }
215 if let Some(section) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
216 // > * Section Header: starts with a `[` and ends with a `]`. These lines define
217 // > globs...
218
219 // <https://spec.editorconfig.org/#glob-expressions>
220 // We need to modify the glob string slightly since EditorConfig's glob flavor
221 // doesn't match `globset`'s exactly. `globset` only allows '**' at the beginning
222 // or end of a glob or between two '/'s. (This replacement is not very fancy but
223 // should cover most practical cases.)
224 let mut glob_str = section.replace("**.", "**/*.");
225 if !is_glob_relative(section) {
226 glob_str.insert_str(0, "**/");
227 }
228 let glob = GlobBuilder::new(&glob_str)
229 .literal_separator(true)
230 .backslash_escape(true)
231 .empty_alternates(true)
232 .build()?;
233 ini.sections.push(Section {
234 glob: glob.compile_matcher(),
235 pairs: Pairs::new(),
236 });
237 } else if let Some((key, value)) = line.split_once('=') {
238 // > * Key-Value Pair (or Pair): contains a key and a value, separated by an `=`.
239 // > * Key: The part before the first `=` on the line.
240 // > * Value: The part, if any, after the first `=` on the line.
241 // > * Keys and values are trimmed of leading and trailing whitespace, but
242 // > include any whitespace that is between non-whitespace characters.
243 // > * If a value is not provided, then the value is an empty string.
244 let key = key.trim().to_lowercase().into_boxed_str();
245 let value = value.trim().to_lowercase().into_boxed_str();
246 if let Some(section) = ini.sections.last_mut() {
247 section.pairs.insert(key, value);
248 } else {
249 ini.pairs.insert(key, value);
250 }
251 }
252 }
253 Ok(ini)
254 }
255 }
256
257 /// Determines whether a glob is relative to the directory of the config file.
258 fn is_glob_relative(source: &str) -> bool {
259 // > If the glob contains a path separator (a `/` not inside square brackets), then the
260 // > glob is relative to the directory level of the particular `.editorconfig` file itself.
261 let mut idx = 0;
262 while let Some(open) = source[idx..].find('[').map(|open| idx + open) {
263 if source[..open].contains('/') {
264 return true;
265 }
266 idx = source[open..]
267 .find(']')
268 .map_or(source.len(), |close| idx + close);
269 }
270 source[idx..].contains('/')
271 }
272
273 #[cfg(test)]
274 mod test {
275 use super::*;
276
277 #[test]
278 fn is_glob_relative_test() {
279 assert!(is_glob_relative("subdir/*.c"));
280 assert!(!is_glob_relative("*.txt"));
281 assert!(!is_glob_relative("[a/b].c"));
282 }
283
284 fn editor_config(path: impl AsRef<Path>, source: &str) -> EditorConfig {
285 let path = path.as_ref();
286 let ini = source.parse::<Ini>().unwrap();
287 let pairs = ini
288 .sections
289 .into_iter()
290 .filter(|section| section.glob.is_match(path))
291 .fold(Pairs::new(), |mut acc, section| {
292 acc.extend(section.pairs);
293 acc
294 });
295 EditorConfig::from_pairs(pairs)
296 }
297
298 #[test]
299 fn parse_test() {
300 let source = r#"
301 [*]
302 indent_style = space
303
304 [Makefile]
305 indent_style = tab
306
307 [docs/**.txt]
308 insert_final_newline = true
309 "#;
310
311 assert_eq!(
312 editor_config("a.txt", source),
313 EditorConfig {
314 indent_style: Some(IndentStyle::Spaces(4)),
315 ..Default::default()
316 }
317 );
318 assert_eq!(
319 editor_config("pkg/Makefile", source),
320 EditorConfig {
321 indent_style: Some(IndentStyle::Tabs),
322 ..Default::default()
323 }
324 );
325 assert_eq!(
326 editor_config("docs/config/editor.txt", source),
327 EditorConfig {
328 indent_style: Some(IndentStyle::Spaces(4)),
329 insert_final_newline: Some(true),
330 ..Default::default()
331 }
332 );
333 }
334 }