cargo-spellcheck 0.15.7

Checks all doc comments for spelling mistakes
Documentation
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Configure cargo-spellcheck
//!
//! Supports `Hunspell` and `LanguageTool` scopes.
//!
//! A default configuration will be generated in the default location by
//! default. Default. Default default default.

// TODO pendeng refactor, avoid spending time on documenting the status quo.
#![allow(missing_docs)]

pub mod args;

mod regex;
pub use self::regex::*;

mod reflow;
pub use self::reflow::*;

mod hunspell;
pub use self::hunspell::*;

mod nlprules;
pub use self::nlprules::*;

mod search_dirs;
pub use search_dirs::*;

mod iso;
pub use iso::*;

use crate::errors::*;
use crate::Detector;
use fancy_regex::Regex;

use fs_err as fs;
use serde::{Deserialize, Serialize};
use std::convert::AsRef;
use std::fmt;
use std::io::Read;
use std::path::{Path, PathBuf};

#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct Config {
    // Options that modify the inputs being picked up.
    #[serde(default)]
    #[serde(alias = "dev-comments")]
    #[serde(alias = "devcomments")]
    pub dev_comments: bool,

    #[serde(default)]
    #[serde(alias = "skip-readme")]
    #[serde(alias = "skipreadme")]
    pub skip_readme: bool,

    #[serde(alias = "Hunspell")]
    #[serde(default = "default_hunspell")]
    pub hunspell: Option<HunspellConfig>,

    #[serde(alias = "ZSpell")]
    #[serde(default = "default_zspell")]
    pub zet: Option<ZetConfig>,

    #[serde(alias = "Spellbook")]
    #[serde(alias = "book")]
    #[serde(default = "default_spellbook")]
    pub spellbook: Option<SpellbookConfig>,

    #[serde(alias = "Nlp")]
    #[serde(alias = "NLP")]
    #[serde(alias = "nlp")]
    #[serde(alias = "NLP")]
    #[serde(alias = "NlpRules")]
    #[serde(default = "default_nlprules")]
    pub nlprules: Option<NlpRulesConfig>,

    #[serde(alias = "ReFlow")]
    #[serde(alias = "Reflow")]
    pub reflow: Option<ReflowConfig>,
}

impl Config {
    const QUALIFIER: &'static str = "rs";
    const ORGANIZATION: &'static str = "fff";
    const APPLICATION: &'static str = "cargo_spellcheck";

    /// Sanitize all relative paths to absolute paths in relation to `base`.
    fn sanitize_paths(&mut self, base: &Path) -> Result<()> {
        if let Some(ref mut hunspell) = self.hunspell {
            hunspell.sanitize_paths(base)?;
        }
        if let Some(ref mut zspell) = self.zet {
            zspell.sanitize_paths(base)?;
        }
        if let Some(ref mut spellbook) = self.spellbook {
            spellbook.sanitize_paths(base)?;
        }
        Ok(())
    }

    pub fn parse<S: AsRef<str>>(s: S) -> Result<Self> {
        Ok(toml::from_str(s.as_ref())?)
    }

    pub fn load_from<P: AsRef<Path>>(path: P) -> Result<Option<Self>> {
        let (contents, path) = match Self::load_content(path) {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Ok(None);
            }
            Err(e) => bail!(e),
            Ok(contents) => contents,
        };
        Self::parse(&contents)
            .wrap_err_with(|| {
                eyre!(
                    "Syntax of a given config file({}) is broken",
                    path.display()
                )
            })
            .and_then(|mut cfg| {
                if let Some(base) = path.parent() {
                    cfg.sanitize_paths(base)?;
                }
                Ok(Some(cfg))
            })
    }

    pub fn load_content<P: AsRef<Path>>(path: P) -> std::io::Result<(String, PathBuf)> {
        let path = path.as_ref().canonicalize()?;
        let mut file = fs::File::open(&path)?;

        let mut contents = String::with_capacity(1024);
        file.read_to_string(&mut contents)?;
        Ok((contents, path))
    }

    pub fn load() -> Result<Option<Self>> {
        if let Some(base) = directories::BaseDirs::new() {
            Self::load_from(
                base.config_dir()
                    .join("cargo_spellcheck")
                    .join("config.toml"),
            )
        } else {
            bail!("No idea where your config directory is located. XDG compliance would be nice.")
        }
    }

    pub fn to_toml(&self) -> Result<String> {
        toml::to_string(self).wrap_err_with(|| eyre!("Failed to convert to toml"))
    }

    pub fn write_values_to<W: std::io::Write>(&self, mut writer: W) -> Result<Self> {
        let s = self.to_toml()?;
        writer.write_all(s.as_bytes())?;
        Ok(self.clone())
    }

    pub fn write_values_to_path<P: AsRef<Path>>(&self, path: P) -> Result<Self> {
        let path = path.as_ref();

        if let Some(path) = path.parent() {
            fs::create_dir_all(path).wrap_err_with(|| {
                eyre!("Failed to create config parent dirs {}", path.display())
            })?;
        }

        let file = fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(path)
            .wrap_err_with(|| eyre!("Failed to write default values to {}", path.display()))?;

        let writer = std::io::BufWriter::new(file);

        self.write_values_to(writer)
            .wrap_err_with(|| eyre!("Failed to write default config to {}", path.display()))
    }

    pub fn write_values_to_default_path(&self) -> Result<Self> {
        let path = Self::default_path()?;
        self.write_values_to_path(path)
    }

    pub fn write_default_values_to<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::default().write_values_to_path(path)
    }

    pub fn default_path() -> Result<PathBuf> {
        if let Some(base) =
            directories::ProjectDirs::from(Self::QUALIFIER, Self::ORGANIZATION, Self::APPLICATION)
        {
            Ok(base.config_dir().join("config.toml"))
        } else {
            bail!("No idea where your config directory is located. `$HOME` must be set.")
        }
    }

    /// Obtain a project specific config file.
    pub fn project_config(manifest_dir: impl AsRef<Path>) -> Result<PathBuf> {
        let path = manifest_dir
            .as_ref()
            .to_owned()
            .join(".config")
            .join("spellcheck.toml");

        let path = path.canonicalize()?;

        if path.is_file() {
            Ok(path)
        } else {
            bail!(
                "Local project dir config {} does not exist or is not a file.",
                path.display()
            )
        }
    }

    pub fn write_default_values() -> Result<Self> {
        let d = Self::default_path()?;
        Self::write_default_values_to(d.join("config.toml"))
    }

    pub fn is_enabled(&self, detector: Detector) -> bool {
        match detector {
            Detector::Hunspell => self.hunspell.is_some(),
            Detector::ZSpell => self.zet.is_some(),
            Detector::Spellbook => self.spellbook.is_some(),
            Detector::NlpRules => self.nlprules.is_some(),
            Detector::Reflow => self.reflow.is_some(),
            #[cfg(test)]
            Detector::Dummy => true,
        }
    }

    pub fn full() -> Self {
        Default::default()
    }
}

fn default_nlprules() -> Option<NlpRulesConfig> {
    if cfg!(feature = "nlprules") {
        Some(NlpRulesConfig::default())
    } else {
        log::warn!("Cannot enable nlprules, since it wasn't compiled with `nlprules` as checker");
        None
    }
}

fn default_hunspell() -> Option<HunspellConfig> {
    Some(HunspellConfig::default())
}
fn default_zspell() -> Option<ZetConfig> {
    Some(ZetConfig::default())
}
fn default_spellbook() -> Option<SpellbookConfig> {
    Some(SpellbookConfig::default())
}

impl Default for Config {
    fn default() -> Self {
        Self {
            dev_comments: false,
            skip_readme: false,
            hunspell: default_hunspell(),
            zet: default_zspell(),
            spellbook: default_spellbook(),
            nlprules: default_nlprules(),
            reflow: Some(ReflowConfig::default()),
        }
    }
}

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

    #[test]
    fn can_serialize_to_toml() {
        let config = dbg!(Config::full());
        assert_matches!(config.to_toml(), Ok(_s));
    }

    #[test]
    fn project_config_works() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join(".config")
            .join("spellcheck.toml");
        assert_matches!(Config::load_from(&path), Ok(_));
    }

    #[test]
    fn all() {
        let _ = Config::parse(
            r#"
dev_comments = true
skip-readme = true

[Hunspell]
lang = "en_US"
search_dirs = ["/usr/lib64/hunspell"]
extra_dictionaries = ["/home/bernhard/test.dic"]
			"#,
        )
        .unwrap();
    }

    #[test]
    fn empty() {
        assert!(Config::parse(
            r#"
			"#,
        )
        .is_ok());
    }
    #[test]
    fn partial_1() {
        let _cfg = Config::parse(
            r#"
[hunspell]
lang = "en_GB"
search_dirs = ["/usr/lib64/hunspell"]
extra_dictionaries = ["/home/bernhard/test.dic"]
			"#,
        )
        .unwrap();
    }

    #[test]
    fn partial_3() {
        let cfg = Config::parse(
            r#"
[Hunspell]
lang = "de_AT"
search_dirs = ["/usr/lib64/hunspell"]
extra_dictionaries = ["/home/bernhard/test.dic"]
			"#,
        )
        .unwrap();
        let _hunspell = cfg.hunspell.expect("Must contain hunspell cfg");
    }

    #[test]
    fn partial_4() {
        let cfg = Config::parse(
            r#"
[Hunspell]
lang = "en_US"
			"#,
        )
        .unwrap();
        let _hunspell = cfg.hunspell.expect("Must contain hunspell cfg");
    }

    #[test]
    fn partial_5() {
        assert!(Config::parse(
            r#"
[hUNspell]
lang = "en_US"
			"#,
        )
        .is_err());
    }

    #[test]
    fn partial_6() {
        let cfg = Config::parse(
            r#"
[hunspell]
			"#,
        )
        .unwrap();
        let _hunspell = cfg.hunspell.expect("Must contain hunspell cfg");
    }

    #[test]
    fn partial_7() {
        let cfg = Config::parse(
            r#"
[Hunspell.quirks]
allow_concatenation = true
allow_dashes = true
transform_regex = ["^'([^\\s])'$", "^[0-9]+x$"]
			"#,
        )
        .unwrap();
        let _hunspell = cfg.hunspell.expect("Must contain hunspell cfg");
    }

    #[test]
    fn partial_8() {
        let cfg = Config::parse(
            r#"
[Hunspell]
search_dirs = ["/search/1", "/search/2"]
skip_os_lookups = true
			"#,
        )
        .unwrap();

        let hunspell: HunspellConfig = cfg.hunspell.expect("Must contain hunspell cfg");
        assert!(hunspell.skip_os_lookups);

        let search_dirs = hunspell.search_dirs;
        let search_dirs2: Vec<_> = search_dirs.as_ref().clone();
        assert!(!search_dirs2.is_empty());

        assert_eq!(search_dirs.iter(false).count(), 2);

        #[cfg(target_os = "linux")]
        assert_eq!(search_dirs.iter(true).count(), 5);

        #[cfg(target_os = "windows")]
        assert_eq!(search_dirs.iter(true).count(), 2);

        #[cfg(target_os = "macos")]
        assert!(search_dirs.iter(true).count() >= 3);
    }

    #[test]
    fn partial_9() {
        let cfg = Config::parse(
            r#"
[Reflow]
max_line_length = 42
"#,
        )
        .unwrap();
        assert_eq!(
            cfg.reflow.expect("Must contain reflow cfg").max_line_length,
            42
        );
    }
}