linthis 0.17.2

A fast, cross-platform multi-language linter and formatter
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
// Copyright 2024 zhlinh and linthis Project Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at
//
// https://opensource.org/license/MIT
//
// The above copyright notice and this permission
// notice shall be included in all copies or
// substantial portions of the Software.

//! Utility modules for linthis.

pub mod language;
pub mod output;
pub mod types;
pub mod unicode;
pub mod walker;

use std::fs;
use std::path::Path;

/// Default exclusion patterns for common directories that shouldn't be linted.
pub const DEFAULT_EXCLUDES: &[&str] = &[
    // Linthis working directory
    ".linthis/**",
    // Version control
    ".git/**",
    ".hg/**",
    ".svn/**",
    // Dependencies
    "node_modules/**",
    "vendor/**",
    "venv/**",
    ".venv/**",
    "__pycache__/**",
    // Third-party libraries
    "third_party/**",
    "thirdparty/**",
    "third-party/**",
    "3rdparty/**",
    "3rd_party/**",
    "3rd-party/**",
    "3party/**",
    "external/**",
    "externals/**",
    "deps/**",
    // Build outputs
    "target/**",
    "build/**",
    "dist/**",
    "out/**",
    "_build/**",
    // IDE and editor
    ".idea/**",
    ".vscode/**",
    ".vs/**",
    "*.swp",
    "*~",
    // Generated files
    "*.generated.*",
    "*.min.js",
    "*.min.css",
    // Lint/formatter config files (often generated by linthis or similar tools)
    // C/C++/ObjC
    ".clang-format",
    ".clang-tidy",
    "CPPLINT.cfg",
    "compile_commands.json",
    // Python
    "ruff.toml",
    ".ruff.toml",
    ".flake8",
    "setup.cfg",
    "pyproject.toml",
    // JavaScript/TypeScript
    ".eslintrc",
    ".eslintrc.js",
    ".eslintrc.json",
    ".eslintrc.yml",
    ".eslintrc.yaml",
    ".prettierrc",
    ".prettierrc.json",
    "prettierrc.js",
    "prettier.config.js",
    // Go
    ".golangci.yml",
    ".golangci.yaml",
    // Java
    "checkstyle.xml",
    ".checkstyle.xml",
    "checkstyle-config.xml",
    // Kotlin
    "detekt.yml",
    // Swift
    ".swiftlint.yml",
    // Dart
    "analysis_options.yaml",
    // Scala
    "scalastyle_config.xml",
    ".scalafix.conf",
    // Ruby
    ".rubocop.yml",
    // Rust
    "rustfmt.toml",
    // Package managers (iOS)
    "Pods/**",
    "**/Pods/**",
    "Carthage/**",
    "**/Carthage/**",
];

/// Get list of staged files from git.
pub fn get_staged_files() -> crate::Result<Vec<std::path::PathBuf>> {
    crate::vcs::detect_vcs().get_pending_files()
}

/// Get files changed since a VCS ref (branch, tag, or commit).
pub fn get_changed_files(base: Option<&str>) -> crate::Result<Vec<std::path::PathBuf>> {
    crate::vcs::detect_vcs().get_changed_files(base)
}

/// Get uncommitted files (both staged and unstaged changes).
pub fn get_uncommitted_files() -> crate::Result<Vec<std::path::PathBuf>> {
    crate::vcs::detect_vcs().get_modified_files()
}

/// Check if a path matches any of the ignore patterns.
pub fn should_ignore(path: &Path, patterns: &[regex::Regex]) -> bool {
    let path_str = path.to_string_lossy();
    patterns.iter().any(|pattern| pattern.is_match(&path_str))
}

/// Read a specific line from a file (1-indexed).
pub fn read_file_line(path: &Path, line_number: usize) -> Option<String> {
    use std::fs::File;
    use std::io::{BufRead, BufReader};

    if line_number == 0 {
        return None;
    }

    let file = File::open(path).ok()?;
    let reader = BufReader::new(file);

    reader
        .lines()
        .nth(line_number - 1)
        .and_then(|line| line.ok())
}

/// Result of reading a file line with context.
pub struct LineWithContext {
    /// The target line content
    pub line: String,
    /// Context lines before (line_number, content)
    pub before: Vec<(usize, String)>,
    /// Context lines after (line_number, content)
    pub after: Vec<(usize, String)>,
}

/// Read a specific line from a file with surrounding context (1-indexed).
/// Returns the target line and up to `context_lines` lines before and after.
pub fn read_file_line_with_context(
    path: &Path,
    line_number: usize,
    context_lines: usize,
) -> Option<LineWithContext> {
    use std::fs::File;
    use std::io::{BufRead, BufReader};

    if line_number == 0 {
        return None;
    }

    let file = File::open(path).ok()?;
    let reader = BufReader::new(file);

    // Calculate the range of lines to read
    let start_line = line_number.saturating_sub(context_lines);
    let end_line = line_number + context_lines;

    let mut before = Vec::new();
    let mut target_line = None;
    let mut after = Vec::new();

    for (idx, line_result) in reader.lines().enumerate() {
        let current_line = idx + 1; // 1-indexed

        if current_line < start_line {
            continue;
        }
        if current_line > end_line {
            break;
        }

        if let Ok(content) = line_result {
            if current_line < line_number {
                before.push((current_line, content));
            } else if current_line == line_number {
                target_line = Some(content);
            } else {
                after.push((current_line, content));
            }
        }
    }

    target_line.map(|line| LineWithContext {
        line,
        before,
        after,
    })
}

/// Get the project root directory (git root or current directory).
pub fn get_project_root() -> std::path::PathBuf {
    crate::vcs::detect_vcs().project_root().to_path_buf()
}

/// Check if we're in a git repository.
pub fn is_git_repo() -> bool {
    crate::vcs::detect_vcs().kind() == crate::vcs::VcsKind::Git
}

/// Check if we're in any VCS repository.
pub fn is_vcs_repo() -> bool {
    crate::vcs::detect_vcs().kind() != crate::vcs::VcsKind::None
}

/// Parse .gitignore file and return glob patterns.
/// Converts gitignore patterns to glob patterns for use with our walker.
pub fn parse_gitignore(gitignore_path: &Path) -> Vec<String> {
    let mut patterns = Vec::new();

    let content = match fs::read_to_string(gitignore_path) {
        Ok(c) => c,
        Err(_) => return patterns,
    };

    for line in content.lines() {
        let line = line.trim();

        // Skip empty lines and comments
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        // Skip negation patterns (not supported in simple glob)
        if line.starts_with('!') {
            continue;
        }

        // Convert gitignore pattern to glob pattern
        let pattern = convert_gitignore_to_glob(line);
        if !pattern.is_empty() {
            patterns.push(pattern);
        }
    }

    patterns
}

/// Convert a gitignore pattern to a glob pattern.
fn convert_gitignore_to_glob(pattern: &str) -> String {
    let mut pattern = pattern.to_string();

    // Remove leading slash (gitignore root anchor)
    let rooted = pattern.starts_with('/');
    if rooted {
        pattern = pattern[1..].to_string();
    }

    // Handle trailing slash (directory indicator)
    let is_dir = pattern.ends_with('/');
    if is_dir {
        pattern = pattern[..pattern.len() - 1].to_string();
    }

    // If pattern doesn't contain / (except trailing), it matches anywhere
    // Convert to **/pattern
    if !rooted && !pattern.contains('/') {
        pattern = format!("**/{}", pattern);
    }

    // Add /** suffix for directories to match all contents
    if is_dir || !pattern.contains('.') {
        // Likely a directory, add /** to match contents
        if !pattern.ends_with("/**") && !pattern.ends_with("/*") {
            pattern.push_str("/**");
        }
    }

    pattern
}

/// Get all gitignore patterns from the project.
/// Reads .gitignore from project root and any nested .gitignore files.
pub fn get_gitignore_patterns(project_root: &Path) -> Vec<String> {
    let mut patterns = Vec::new();

    // Read root .gitignore
    let root_gitignore = project_root.join(".gitignore");
    if root_gitignore.exists() {
        patterns.extend(parse_gitignore(&root_gitignore));
    }

    // Also check for global gitignore
    if let Some(home) = std::env::var("HOME").ok().map(std::path::PathBuf::from) {
        let global_gitignore = home.join(".gitignore_global");
        if global_gitignore.exists() {
            patterns.extend(parse_gitignore(&global_gitignore));
        }
    }

    patterns
}

/// Check if a file contains a `.linthis` ignore entry.
fn file_has_linthis_ignore(path: &Path) -> bool {
    std::fs::read_to_string(path)
        .map(|c| has_linthis_ignore(&c))
        .unwrap_or(false)
}

/// Resolve the global gitignore path from git config or default ~/.gitignore_global.
fn resolve_global_gitignore_path() -> Option<std::path::PathBuf> {
    let global_path = std::process::Command::new("git")
        .args(["config", "--global", "core.excludesFile"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());

    global_path
        .map(|p| {
            if p.starts_with('~') {
                if let Ok(home) = std::env::var("HOME") {
                    return std::path::PathBuf::from(p.replacen('~', &home, 1));
                }
            }
            std::path::PathBuf::from(p)
        })
        .or_else(|| {
            std::env::var("HOME")
                .ok()
                .map(|h| std::path::PathBuf::from(h).join(".gitignore_global"))
        })
}

/// Check if any of the given file contents already contain a `.linthis` ignore entry.
fn has_linthis_ignore(content: &str) -> bool {
    content
        .lines()
        .any(|line| line.trim() == ".linthis/" || line.trim() == ".linthis")
}

/// Ensure `.linthis/` is ignored by git in the project.
///
/// Checks project `.gitignore`, global gitignore (`core.excludesFile` or
/// `~/.gitignore_global`), and `.git/info/exclude`. If `.linthis/` is already
/// covered by any of them, does nothing. Otherwise appends to the project's
/// `.gitignore` (creating it if needed) and prints a message.
pub fn ensure_gitignore_has_linthis(project_root: &Path) {
    // 1. Check project .gitignore
    let gitignore_path = project_root.join(".gitignore");
    if file_has_linthis_ignore(&gitignore_path) {
        return;
    }

    // 2. Check global gitignore
    let global_gitignore = resolve_global_gitignore_path();
    if global_gitignore.as_ref().is_some_and(|p| file_has_linthis_ignore(p)) {
        return;
    }

    // 3. Check .git/info/exclude
    let exclude_path = project_root.join(".git").join("info").join("exclude");
    if file_has_linthis_ignore(&exclude_path) {
        return;
    }

    // Not ignored anywhere — prefer adding to global gitignore (less project impact)
    let target_path = if let Some(ref gp) = global_gitignore {
        // Ensure the global excludesFile is configured if using default ~/.gitignore_global
        if std::fs::read_to_string(gp).is_err() {
            // File doesn't exist yet — create it and set core.excludesFile if needed
            let _ = std::process::Command::new("git")
                .args([
                    "config",
                    "--global",
                    "core.excludesFile",
                    &gp.to_string_lossy(),
                ])
                .output();
        }
        gp.clone()
    } else {
        // No HOME — fall back to project .gitignore
        gitignore_path.clone()
    };

    let target_existing = std::fs::read_to_string(&target_path).unwrap_or_default();
    let mut content = target_existing;
    if !content.is_empty() && !content.ends_with('\n') {
        content.push('\n');
    }
    content.push_str("\n# Linthis working directory\n.linthis/\n");

    match std::fs::write(&target_path, &content) {
        Ok(_) => {
            if target_path == gitignore_path {
                eprintln!("[linthis] Added .linthis/ to .gitignore");
            } else {
                eprintln!(
                    "[linthis] Added .linthis/ to global gitignore ({})",
                    target_path.display()
                );
            }
        }
        Err(e) => {
            eprintln!(
                "[linthis] Warning: failed to update {}: {}",
                target_path.display(),
                e
            );
            eprintln!("[linthis] Please add '.linthis/' to your gitignore manually");
        }
    }

    // Also exclude from IDE search indexes
    ensure_ide_exclude_linthis(project_root);
}

/// Exclude `.linthis/` from IDE search indexes.
/// Only modifies IDE config if the IDE directory already exists.
fn ensure_ide_exclude_linthis(project_root: &Path) {
    ensure_jetbrains_exclude(project_root);
    ensure_vscode_exclude(project_root);
}

/// Add `.linthis` as excluded folder in JetBrains `.iml` files.
fn ensure_jetbrains_exclude(project_root: &Path) {
    let idea_dir = project_root.join(".idea");
    if !idea_dir.is_dir() {
        return;
    }

    // Find .iml files in .idea/
    let entries = match std::fs::read_dir(&idea_dir) {
        Ok(e) => e,
        Err(_) => return,
    };

    let exclude_url = "file://$MODULE_DIR$/.linthis";
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().is_none_or(|e| e != "iml") {
            continue;
        }

        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        // Already excluded
        if content.contains(exclude_url) {
            continue;
        }

        // Insert <excludeFolder> inside <content url="file://$MODULE_DIR$">
        let marker = "<content url=\"file://$MODULE_DIR$\"";
        if let Some(pos) = content.find(marker) {
            // Find the closing > or /> of the content tag
            let after_marker = &content[pos..];
            if let Some(close_pos) = after_marker.find("/>") {
                // Self-closing <content ... /> — expand it
                let insert_at = pos + close_pos;
                let new_content = format!(
                    "{}>\n      <excludeFolder url=\"{}\" />\n    </content{}",
                    &content[..insert_at],
                    exclude_url,
                    &content[insert_at + 2..] // skip "/>"
                );
                if std::fs::write(&path, &new_content).is_ok() {
                    eprintln!(
                        "[linthis] Added .linthis/ exclude to {}",
                        path.file_name().unwrap_or_default().to_string_lossy()
                    );
                }
            } else if let Some(close_pos) = after_marker.find('>') {
                // <content ...> with children — insert before </content>
                let content_start = pos + close_pos + 1;
                let remaining = &content[content_start..];
                if let Some(end_pos) = remaining.find("</content>") {
                    let insert_at = content_start + end_pos;
                    let new_content = format!(
                        "{}      <excludeFolder url=\"{}\" />\n    {}",
                        &content[..insert_at],
                        exclude_url,
                        &content[insert_at..]
                    );
                    if std::fs::write(&path, &new_content).is_ok() {
                        eprintln!(
                            "[linthis] Added .linthis/ exclude to {}",
                            path.file_name().unwrap_or_default().to_string_lossy()
                        );
                    }
                }
            }
        }
    }
}

/// Add `.linthis` to VS Code search.exclude.
/// Prefers global user settings; falls back to project `.vscode/settings.json`.
fn ensure_vscode_exclude(project_root: &Path) {
    // 1. Check if already excluded in global user settings
    if let Some(global_path) = vscode_user_settings_path() {
        if let Ok(content) = std::fs::read_to_string(&global_path) {
            if content.contains("\".linthis\"") || content.contains("\".linthis/\"") {
                return;
            }
        }
    }

    // 2. Check project .vscode/settings.json
    let project_settings = project_root.join(".vscode").join("settings.json");
    if let Ok(content) = std::fs::read_to_string(&project_settings) {
        if content.contains("\".linthis\"") || content.contains("\".linthis/\"") {
            return;
        }
    }

    // 3. Not excluded anywhere — prefer global user settings
    if let Some(global_path) = vscode_user_settings_path() {
        if add_linthis_to_vscode_settings(&global_path) {
            eprintln!(
                "[linthis] Added .linthis/ to VS Code global search.exclude ({})",
                global_path.display()
            );
            return;
        }
    }

    // 4. Fall back to project .vscode/settings.json (only if .vscode/ exists)
    if project_root.join(".vscode").is_dir()
        && add_linthis_to_vscode_settings(&project_settings)
    {
        eprintln!("[linthis] Added .linthis/ to .vscode/settings.json search.exclude");
    }
}

/// Get the VS Code global user settings.json path.
fn vscode_user_settings_path() -> Option<std::path::PathBuf> {
    if cfg!(target_os = "macos") {
        std::env::var("HOME")
            .ok()
            .map(|h| Path::new(&h).join("Library/Application Support/Code/User/settings.json"))
    } else if cfg!(target_os = "windows") {
        std::env::var("APPDATA")
            .ok()
            .map(|a| Path::new(&a).join("Code/User/settings.json"))
    } else {
        std::env::var("HOME")
            .ok()
            .map(|h| Path::new(&h).join(".config/Code/User/settings.json"))
    }
    .filter(|p| p.parent().is_some_and(|d| d.is_dir()))
}

/// Add `.linthis` to search.exclude in a VS Code settings.json file.
/// Returns true on success.
fn add_linthis_to_vscode_settings(settings_path: &Path) -> bool {
    let content = std::fs::read_to_string(settings_path).unwrap_or_default();

    if content.trim().is_empty() {
        let new_content = "{\n  \"search.exclude\": {\n    \".linthis\": true\n  }\n}\n";
        return std::fs::write(settings_path, new_content).is_ok();
    }

    let mut json: serde_json::Value = match serde_json::from_str(&content) {
        Ok(v) => v,
        Err(_) => return false,
    };

    let search_exclude = json
        .as_object_mut()
        .and_then(|obj| {
            if !obj.contains_key("search.exclude") {
                obj.insert("search.exclude".to_string(), serde_json::json!({}));
            }
            obj.get_mut("search.exclude")
        })
        .and_then(|v| v.as_object_mut());

    if let Some(exclude) = search_exclude {
        exclude.insert(".linthis".to_string(), serde_json::json!(true));
    } else {
        return false;
    }

    serde_json::to_string_pretty(&json)
        .map(|formatted| std::fs::write(settings_path, format!("{}\n", formatted)).is_ok())
        .unwrap_or(false)
}