| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 42 |
|
| 43 |
|
| 44 |
pub fn find(path: &Path) -> Self { |
| 45 |
let mut configs = Vec::new(); |
| 46 |
|
| 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 |
|
| 62 |
|
| 63 |
if is_root { |
| 64 |
break; |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
let mut pairs = Pairs::new(); |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 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 |
|
| 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 |
|
| 142 |
|
| 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 |
|
| 163 |
|
| 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 |
|
| 199 |
let mut ini = Ini::default(); |
| 200 |
|
| 201 |
|
| 202 |
for full_line in source.lines() { |
| 203 |
|
| 204 |
let line = full_line.trim(); |
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
if line.is_empty() { |
| 209 |
continue; |
| 210 |
} |
| 211 |
|
| 212 |
if line.starts_with([';', '#']) { |
| 213 |
continue; |
| 214 |
} |
| 215 |
if let Some(section) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) { |
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 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 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 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 |
|
| 258 |
fn is_glob_relative(source: &str) -> bool { |
| 259 |
|
| 260 |
|
| 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 |
} |