codebook-lsp 0.3.42

A code-aware spell checker with language server implementation, installable via cargo install
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use codebook::Codebook;
use codebook_config::{CodebookConfig, CodebookConfigFile};
use globset::Glob;
use ignore::WalkBuilder;
use std::collections::HashSet;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use string_offsets::{AllConfig, StringOffsets};

macro_rules! err {
    ($($arg:tt)*) => {
        eprintln!("{} {}", Paint::stderr().red("error:"), format_args!($($arg)*))
    };
}

/// Minimal ANSI styling without a dependency. Enabled per stream only when it
/// is a terminal and the NO_COLOR convention (https://no-color.org) is unset.
#[derive(Clone, Copy)]
struct Paint(bool);

impl Paint {
    fn stdout() -> Self {
        Self(color_allowed() && std::io::stdout().is_terminal())
    }

    fn stderr() -> Self {
        Self(color_allowed() && std::io::stderr().is_terminal())
    }

    fn wrap(self, code: &str, text: &str) -> String {
        if self.0 {
            format!("\x1b[{code}m{text}\x1b[0m")
        } else {
            text.to_string()
        }
    }

    fn bold(self, text: &str) -> String {
        self.wrap("1", text)
    }

    fn dim(self, text: &str) -> String {
        self.wrap("2", text)
    }

    fn red(self, text: &str) -> String {
        self.wrap("31", text)
    }

    fn red_bold(self, text: &str) -> String {
        self.wrap("1;31", text)
    }

    fn green(self, text: &str) -> String {
        self.wrap("32", text)
    }

    fn cyan(self, text: &str) -> String {
        self.wrap("36", text)
    }
}

fn color_allowed() -> bool {
    std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty())
}

/// Result of a lint run, mapped to exit codes by the caller.
pub enum LintResult {
    /// All files clean — exit 0.
    Clean,
    /// Spelling errors found — exit 1.
    Errors,
    /// Infrastructure failure (IO errors, bad patterns, etc.) — exit 2.
    Failure,
}

/// Computes a workspace-relative path string for a given file. Falls back to
/// the absolute path if the file is outside the workspace or canonicalization
/// fails. `root_canonical` should be the already-canonicalized workspace root.
fn relative_to_root(root_canonical: Option<&Path>, path: &Path) -> String {
    root_canonical
        .and_then(|root| {
            let canon = path.canonicalize().ok()?;
            canon
                .strip_prefix(root)
                .ok()
                .map(|rel| rel.to_string_lossy().into_owned())
        })
        .unwrap_or_else(|| path.to_string_lossy().into_owned())
}

pub fn run_lint(files: &[String], root: &Path, unique: bool, suggest: bool) -> LintResult {
    let config = match CodebookConfigFile::load(Some(root)) {
        Ok(c) => Arc::new(c),
        Err(e) => {
            err!("failed to load config: {e}");
            return LintResult::Failure;
        }
    };

    print_config_source(&config);
    eprintln!();

    let codebook = Codebook::new(config.clone());

    // Canonicalize the root once here rather than once per file.
    let root_canonical = root.canonicalize().ok();

    let (resolved, mut had_failure) = resolve_paths(files, root);

    let mut seen_words: HashSet<String> = HashSet::new();
    let mut total_errors = 0;
    let mut files_with_errors: usize = 0;
    let mut ignored = 0;
    let mut excluded = 0;

    for path in &resolved {
        let relative = relative_to_root(root_canonical.as_deref(), path);
        let rel_path = Path::new(&relative);

        if config.should_ignore_path(rel_path) {
            ignored += 1;
            continue;
        }
        if !config.should_include_path(rel_path) {
            excluded += 1;
            continue;
        }

        let (errors, file_failure) = check_file(
            path,
            &relative,
            &codebook,
            &mut seen_words,
            unique,
            suggest,
            Paint::stdout(),
        );
        had_failure |= file_failure;
        if errors > 0 {
            total_errors += errors;
            files_with_errors += 1;
        }
    }

    let total = resolved.len();
    let checked = total - ignored - excluded;
    let unique_label = if unique { "unique " } else { "" };
    let paint = Paint::stderr();
    eprintln!(
        "Out of {total} total file(s), checked {checked}, ignored {ignored}, and excluded {excluded}."
    );
    let summary = format!(
        "Found {total_errors} {unique_label}spelling error(s) in {files_with_errors} file(s)."
    );
    if total_errors > 0 {
        eprintln!("{}", paint.red(&summary));
    } else {
        eprintln!("{}", paint.green(&summary));
    }

    if had_failure {
        LintResult::Failure
    } else if total_errors > 0 {
        LintResult::Errors
    } else {
        LintResult::Clean
    }
}

/// Spell-checks a single file and prints any diagnostics to stdout.
///
/// Returns `(error_count, had_io_error)`. `error_count` is 0 if the file was
/// clean; `had_io_error` is true when the file could not be read. `relative` is
/// the workspace-relative path used for display and ignore matching.
fn check_file(
    path: &Path,
    relative: &str,
    codebook: &Codebook,
    seen_words: &mut HashSet<String>,
    unique: bool,
    suggest: bool,
    paint: Paint,
) -> (usize, bool) {
    let text = match std::fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
            // Binary / non-UTF-8 file — silently skip.
            return (0, false);
        }
        Err(e) => {
            err!("{}: {e}", path.display());
            return (0, true);
        }
    };

    let display = relative.strip_prefix("./").unwrap_or(relative);

    // Build the offset table once per file
    let offsets = StringOffsets::<AllConfig>::new(&text);
    let mut locations = codebook.spell_check(&text, None, Some(relative));
    // Sort inner locations first (HashSet iteration order is nondeterministic),
    // then sort the outer list by first occurrence in the file.
    for wl in &mut locations {
        wl.locations.sort_by_key(|r| r.start_byte);
    }
    locations.sort_by_key(|l| l.locations.first().map(|r| r.start_byte).unwrap_or(0));

    // Collect hits first so we can compute pad_len for column alignment. The
    // unique check is per-word, so all ranges of a word are included or skipped
    // together.
    let mut hits: Vec<(String, &str, Option<Vec<String>>)> = Vec::new();
    for wl in &locations {
        if unique && !seen_words.insert(wl.word.to_lowercase()) {
            continue;
        }

        let mut suggestions = if suggest {
            codebook.get_suggestions(wl.word.as_str())
        } else {
            None
        };

        // If unique mode: Only emit the first occurrence of each word.
        let ranges = if unique {
            &wl.locations[..1]
        } else {
            &wl.locations[..]
        };

        for (i, range) in ranges.iter().enumerate() {
            // utf8_to_char_pos returns 0-based line and Unicode-char column.
            let pos = offsets.utf8_to_char_pos(range.start_byte.min(text.len()));

            // Move out of `suggestions` on the last iteration to avoid a clone.
            let sugg = if i + 1 < ranges.len() {
                suggestions.clone()
            } else {
                suggestions.take()
            };

            hits.push((
                format!("{}:{}", pos.line + 1, pos.col + 1),
                wl.word.as_str(),
                sugg,
            ));
        }
    }

    if hits.is_empty() {
        return (0, false);
    }

    let pad_len = hits.iter().map(|(lc, _, _)| lc.len()).max().unwrap_or(0);

    println!("{}", paint.bold(display));
    for (linecol, word, suggestions) in &hits {
        let pad = " ".repeat(pad_len - linecol.len());
        let loc = paint.dim(&format!("{display}:{linecol}"));
        let word = paint.red_bold(word);
        if let Some(s) = suggestions {
            println!("  {loc}{pad}  {word}  -> {}", paint.cyan(&s.join(", ")));
        } else {
            println!("  {loc}{pad}  {word}");
        }
    }
    println!();

    (hits.len(), false)
}

/// Prints which config file is being used, or notes that the default is active.
fn print_config_source(config: &CodebookConfigFile) {
    let cwd = std::env::current_dir().unwrap_or_default();
    let (label, path) = match (
        config.project_config_path().filter(|p| p.is_file()),
        config.global_config_path().filter(|p| p.is_file()),
    ) {
        (Some(p), _) => ("using config", p),
        (None, Some(g)) => ("using global config", g),
        (None, None) => {
            eprintln!(
                "{}",
                Paint::stderr().dim("No config found, using default config")
            );
            return;
        }
    };
    let display = path
        .strip_prefix(&cwd)
        .unwrap_or(&path)
        .display()
        .to_string();
    eprintln!("{}", Paint::stderr().dim(&format!("{label} {display}")));
}

/// Resolves a mix of file paths, directories, and glob patterns into a sorted,
/// deduplicated list of file paths. All paths are resolved through the `ignore`
/// crate's `WalkBuilder`, which respects `.gitignore` rules (including nested
/// ones) and skips hidden files/directories.
///
/// Returns `(paths, had_failure)`. `had_failure` is true for unmatched
/// patterns, invalid globs, or walk I/O errors.
fn resolve_paths(patterns: &[String], root: &Path) -> (Vec<PathBuf>, bool) {
    let mut paths = Vec::new();
    let mut had_failure = false;

    for pattern in patterns {
        // root.join() is a no-op when pattern is absolute
        let p = root.join(pattern);
        if p.is_dir() {
            had_failure |= collect_walk(&mut WalkBuilder::new(&p), &mut paths);
        } else if p.is_file() {
            paths.push(p);
        } else {
            // Treat as a glob pattern. Walk from the workspace root so that
            // the full .gitignore hierarchy (parent + nested) is respected,
            // then post-filter surviving files against the glob.
            let pattern_str = p.to_string_lossy();
            let matcher = match Glob::new(&pattern_str).map(|g| g.compile_matcher()) {
                Ok(m) => m,
                Err(e) => {
                    err!("invalid pattern '{pattern_str}': {e}");
                    had_failure = true;
                    continue;
                }
            };
            let before = paths.len();
            let mut walker = WalkBuilder::new(root);
            for entry in walker.follow_links(false).build() {
                match entry {
                    Ok(e) if e.file_type().is_some_and(|ft| ft.is_file()) => {
                        if matcher.is_match(e.path()) {
                            paths.push(e.into_path());
                        }
                    }
                    Ok(_) => {}
                    Err(e) => {
                        err!("walk error: {e}");
                        had_failure = true;
                    }
                }
            }
            if paths.len() == before {
                err!("no match for '{pattern_str}'");
                had_failure = true;
            }
        }
    }

    paths.sort();
    paths.dedup();
    (paths, had_failure)
}

/// Walks using the given `WalkBuilder`, collecting all files into `out`.
/// Respects `.gitignore` rules (including nested) and skips hidden
/// files/directories. Returns `true` if any I/O error occurred.
fn collect_walk(walker: &mut WalkBuilder, out: &mut Vec<PathBuf>) -> bool {
    let mut had_failure = false;
    for entry in walker.follow_links(false).build() {
        match entry {
            Ok(e) if e.file_type().is_some_and(|ft| ft.is_file()) => out.push(e.into_path()),
            Ok(_) => {}
            Err(e) => {
                err!("walk error: {e}");
                had_failure = true;
            }
        }
    }
    had_failure
}

#[cfg(test)]
mod tests {
    use super::*;
    use codebook::Codebook;
    use codebook_config::CodebookConfigMemory;
    use std::collections::HashSet;
    use std::fs;
    use std::sync::Arc;
    use tempfile::tempdir;

    #[test]
    fn test_path_and_dir_resolution() {
        let dir = tempdir().unwrap();
        let sub = dir.path().join("sub");
        fs::create_dir_all(&sub).unwrap();

        let f1 = dir.path().join("a.rs");
        let f2 = sub.join("b.txt");
        fs::write(&f1, "").unwrap();
        fs::write(&f2, "").unwrap();

        let root_canon = dir.path().canonicalize().unwrap();
        assert_eq!(relative_to_root(Some(&root_canon), &f1), "a.rs");

        let pattern = format!("{}/**/*.*", dir.path().display());
        let (paths, err) = resolve_paths(&[pattern], dir.path());

        assert!(!err);
        assert_eq!(paths.len(), 2);
        let path_strs: HashSet<_> = paths.iter().map(|p| p.to_string_lossy()).collect();
        assert!(path_strs.iter().any(|s| s.ends_with("a.rs")));
        assert!(path_strs.iter().any(|s| s.ends_with("b.txt")));

        let (_, err_missing) = resolve_paths(&["nonexistent.rs".into()], dir.path());
        assert!(err_missing);
    }

    #[test]
    fn test_check_file_logic() {
        let dir = tempdir().unwrap();
        let f = dir.path().join("test.txt");
        fs::write(&f, "actualbad\n🦀 actualbad").unwrap();

        // Load dictionaries from the codebook crate's checked-in fixtures;
        // test builds deny network access (deny-network feature).
        let fixtures = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../codebook/tests/fixtures/dictionaries");
        let cb = Codebook::with_dictionary_dir(
            Arc::new(CodebookConfigMemory::default()),
            Some(fixtures),
        );
        let mut seen = HashSet::new();

        // Test basic flagging and multi-occurrence counting
        let (count, err) = check_file(&f, "test.txt", &cb, &mut seen, false, false, Paint(false));
        assert_eq!(count, 2);
        assert!(!err);

        // Test unique mode
        let mut seen_unique = HashSet::new();
        let (c1, _) = check_file(
            &f,
            "f1.txt",
            &cb,
            &mut seen_unique,
            true,
            false,
            Paint(false),
        );
        let (c2, _) = check_file(
            &f,
            "f2.txt",
            &cb,
            &mut seen_unique,
            true,
            false,
            Paint(false),
        );
        assert_eq!(c1, 1, "Should flag word once");
        assert_eq!(c2, 0, "Should skip already-seen word in second file");

        // Test IO failure
        let (_, err_io) = check_file(
            &dir.path().join("missing"),
            "!",
            &cb,
            &mut seen,
            false,
            false,
            Paint(false),
        );
        assert!(err_io);
    }

    #[test]
    fn test_unicode_line_col() {
        let cases = [
            ("actualbad", 0, 1, 1),        // Start
            ("ok\nactualbad", 3, 2, 1),    // Newline
            ("résumé actualbad", 9, 1, 8), // Multi-byte chars (é is 2 bytes)
            ("🦀 actualbad", 5, 1, 3),     // Emoji (4 bytes, 1 char)
        ];

        for (text, offset, line, col) in cases {
            let table = StringOffsets::<AllConfig>::new(text);
            let pos = table.utf8_to_char_pos(offset);
            assert_eq!(
                (pos.line + 1, pos.col + 1),
                (line, col),
                "Failed on: {}",
                text
            );
        }
    }
}