Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//! Support for [EditorConfig](https://EditorConfig.org) configuration loading.
//!
//! EditorConfig is an editor-agnostic format for specifying configuration in an INI-like, human
//! friendly syntax in `.editorconfig` files (which are intended to be checked into VCS). This
//! module provides functions to search for all `.editorconfig` files that apply to a given path
//! and returns an `EditorConfig` type containing any specified configuration options.
//!
//! At time of writing, this module follows the [spec](https://spec.editorconfig.org/) at
//! version 0.17.2.

use std::{
    collections::HashMap,
    fs,
    num::{NonZeroU16, NonZeroU8},
    path::Path,
    str::FromStr,
};

use encoding_rs::Encoding;
use globset::{GlobBuilder, GlobMatcher};

use crate::{
    indent::{IndentStyle, MAX_INDENT},
    LineEnding,
};

/// Configuration declared for a path in `.editorconfig` files.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct EditorConfig {
    pub indent_style: Option<IndentStyle>,
    pub tab_width: Option<NonZeroU8>,
    pub line_ending: Option<LineEnding>,
    pub encoding: Option<&'static Encoding>,
    // pub spelling_language: Option<SpellingLanguage>,
    pub trim_trailing_whitespace: Option<bool>,
    pub insert_final_newline: Option<bool>,
    pub max_line_length: Option<NonZeroU16>,
}

impl EditorConfig {
    /// Finds any configuration in `.editorconfig` files which applies to the given path.
    ///
    /// If no configuration applies then `EditorConfig::default()` is returned.
    pub fn find(path: &Path) -> Self {
        let mut configs = Vec::new();
        // <https://spec.editorconfig.org/#file-processing>
        for ancestor in path.ancestors() {
            let editor_config_file = ancestor.join(".editorconfig");
            let Ok(contents) = fs::read_to_string(&editor_config_file) else {
                continue;
            };
            let ini = match contents.parse::<Ini>() {
                Ok(ini) => ini,
                Err(err) => {
                    log::warn!("Ignoring EditorConfig file at '{editor_config_file:?}' because a glob failed to compile: {err}");
                    continue;
                }
            };
            let is_root = ini.pairs.get("root").map(AsRef::as_ref) == Some("true");
            configs.push((ini, ancestor));
            // > The search shall stop if an EditorConfig file is found with the `root` key set to
            // > `true` in the preamble or when reaching the root filesystem directory.
            if is_root {
                break;
            }
        }

        let mut pairs = Pairs::new();
        // Reverse the configuration stack so that the `.editorconfig` files closest to `path`
        // are applied last and overwrite settings in files closer to the search ceiling.
        //
        // > If multiple EditorConfig files have matching sections, the pairs from the closer
        // > EditorConfig file are read last, so pairs in closer files take precedence.
        for (config, dir) in configs.into_iter().rev() {
            let relative_path = path.strip_prefix(dir).expect("dir is an ancestor of path");

            for section in config.sections {
                if section.glob.is_match(relative_path) {
                    log::info!(
                        "applying EditorConfig from section '{}' in file {:?}",
                        section.glob.glob(),
                        dir.join(".editorconfig")
                    );
                    pairs.extend(section.pairs);
                }
            }
        }

        Self::from_pairs(pairs)
    }

    fn from_pairs(pairs: Pairs) -> Self {
        enum IndentSize {
            Tab,
            Spaces(NonZeroU8),
        }

        // <https://spec.editorconfig.org/#supported-pairs>
        let indent_size = pairs.get("indent_size").and_then(|value| {
            if value.as_ref() == "tab" {
                Some(IndentSize::Tab)
            } else if let Ok(spaces) = value.parse::<NonZeroU8>() {
                Some(IndentSize::Spaces(spaces))
            } else {
                None
            }
        });
        let tab_width = pairs
            .get("tab_width")
            .and_then(|value| value.parse::<NonZeroU8>().ok())
            .or(match indent_size {
                Some(IndentSize::Spaces(spaces)) => Some(spaces),
                _ => None,
            });
        let indent_style = pairs
            .get("indent_style")
            .and_then(|value| match value.as_ref() {
                "tab" => Some(IndentStyle::Tabs),
                "space" => {
                    let spaces = match indent_size {
                        Some(IndentSize::Spaces(spaces)) => spaces.get(),
                        Some(IndentSize::Tab) => tab_width.map(|n| n.get()).unwrap_or(4),
                        None => 4,
                    };
                    Some(IndentStyle::Spaces(spaces.clamp(1, MAX_INDENT)))
                }
                _ => None,
            });
        let line_ending = pairs
            .get("end_of_line")
            .and_then(|value| match value.as_ref() {
                "lf" => Some(LineEnding::LF),
                "crlf" => Some(LineEnding::Crlf),
                #[cfg(feature = "unicode-lines")]
                "cr" => Some(LineEnding::CR),
                _ => None,
            });
        let encoding = pairs.get("charset").and_then(|value| match value.as_ref() {
            "latin1" => Some(encoding_rs::WINDOWS_1252),
            "utf-8" => Some(encoding_rs::UTF_8),
            // `utf-8-bom` is intentionally ignored.
            // > `utf-8-bom` is discouraged.
            "utf-16le" => Some(encoding_rs::UTF_16LE),
            "utf-16be" => Some(encoding_rs::UTF_16BE),
            _ => None,
        });
        let trim_trailing_whitespace =
            pairs
                .get("trim_trailing_whitespace")
                .and_then(|value| match value.as_ref() {
                    "true" => Some(true),
                    "false" => Some(false),
                    _ => None,
                });
        let insert_final_newline = pairs
            .get("insert_final_newline")
            .and_then(|value| match value.as_ref() {
                "true" => Some(true),
                "false" => Some(false),
                _ => None,
            });
        // This option is not in the spec but is supported by some editors.
        // <https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties#max_line_length>
        let max_line_length = pairs
            .get("max_line_length")
            .and_then(|value| value.parse::<NonZeroU16>().ok());

        Self {
            indent_style,
            tab_width,
            line_ending,
            encoding,
            trim_trailing_whitespace,
            insert_final_newline,
            max_line_length,
        }
    }
}

type Pairs = HashMap<Box<str>, Box<str>>;

#[derive(Debug)]
struct Section {
    glob: GlobMatcher,
    pairs: Pairs,
}

#[derive(Debug, Default)]
struct Ini {
    pairs: Pairs,
    sections: Vec<Section>,
}

impl FromStr for Ini {
    type Err = globset::Error;

    fn from_str(source: &str) -> Result<Self, Self::Err> {
        // <https://spec.editorconfig.org/#file-format>
        let mut ini = Ini::default();
        // > EditorConfig files are in an INI-like file format. To read an EditorConfig file, take
        // > one line at a time, from beginning to end. For each line:
        for full_line in source.lines() {
            // > 1. Remove all leading and trailing whitespace.
            let line = full_line.trim();
            // > 2. Process the remaining text as specified for its type below.
            // > The types of lines are:
            // > * Blank: contains nothing. Blank lines are ignored.
            if line.is_empty() {
                continue;
            }
            // > * Comment: starts with a ';' or '#'. Comment lines are ignored.
            if line.starts_with([';', '#']) {
                continue;
            }
            if let Some(section) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
                // > * Section Header: starts with a `[` and ends with a `]`. These lines define
                // >   globs...

                // <https://spec.editorconfig.org/#glob-expressions>
                // We need to modify the glob string slightly since EditorConfig's glob flavor
                // doesn't match `globset`'s exactly. `globset` only allows '**' at the beginning
                // or end of a glob or between two '/'s. (This replacement is not very fancy but
                // should cover most practical cases.)
                let mut glob_str = section.replace("**.", "**/*.");
                if !is_glob_relative(section) {
                    glob_str.insert_str(0, "**/");
                }
                let glob = GlobBuilder::new(&glob_str)
                    .literal_separator(true)
                    .backslash_escape(true)
                    .empty_alternates(true)
                    .build()?;
                ini.sections.push(Section {
                    glob: glob.compile_matcher(),
                    pairs: Pairs::new(),
                });
            } else if let Some((key, value)) = line.split_once('=') {
                // > * Key-Value Pair (or Pair): contains a key and a value, separated by an `=`.
                // >     * Key: The part before the first `=` on the line.
                // >     * Value: The part, if any, after the first `=` on the line.
                // >     * Keys and values are trimmed of leading and trailing whitespace, but
                // >       include any whitespace that is between non-whitespace characters.
                // >     * If a value is not provided, then the value is an empty string.
                let key = key.trim().to_lowercase().into_boxed_str();
                let value = value.trim().to_lowercase().into_boxed_str();
                if let Some(section) = ini.sections.last_mut() {
                    section.pairs.insert(key, value);
                } else {
                    ini.pairs.insert(key, value);
                }
            }
        }
        Ok(ini)
    }
}

/// Determines whether a glob is relative to the directory of the config file.
fn is_glob_relative(source: &str) -> bool {
    // > If the glob contains a path separator (a `/` not inside square brackets), then the
    // > glob is relative to the directory level of the particular `.editorconfig` file itself.
    let mut idx = 0;
    while let Some(open) = source[idx..].find('[').map(|open| idx + open) {
        if source[..open].contains('/') {
            return true;
        }
        idx = source[open..]
            .find(']')
            .map_or(source.len(), |close| idx + close);
    }
    source[idx..].contains('/')
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn is_glob_relative_test() {
        assert!(is_glob_relative("subdir/*.c"));
        assert!(!is_glob_relative("*.txt"));
        assert!(!is_glob_relative("[a/b].c"));
    }

    fn editor_config(path: impl AsRef<Path>, source: &str) -> EditorConfig {
        let path = path.as_ref();
        let ini = source.parse::<Ini>().unwrap();
        let pairs = ini
            .sections
            .into_iter()
            .filter(|section| section.glob.is_match(path))
            .fold(Pairs::new(), |mut acc, section| {
                acc.extend(section.pairs);
                acc
            });
        EditorConfig::from_pairs(pairs)
    }

    #[test]
    fn parse_test() {
        let source = r#"
        [*]
        indent_style = space

        [Makefile]
        indent_style = tab

        [docs/**.txt]
        insert_final_newline = true
        "#;

        assert_eq!(
            editor_config("a.txt", source),
            EditorConfig {
                indent_style: Some(IndentStyle::Spaces(4)),
                ..Default::default()
            }
        );
        assert_eq!(
            editor_config("pkg/Makefile", source),
            EditorConfig {
                indent_style: Some(IndentStyle::Tabs),
                ..Default::default()
            }
        );
        assert_eq!(
            editor_config("docs/config/editor.txt", source),
            EditorConfig {
                indent_style: Some(IndentStyle::Spaces(4)),
                insert_final_newline: Some(true),
                ..Default::default()
            }
        );
    }
}