linthis 0.17.1

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
//! Configuration CLI handlers for linthis config command

use colored::Colorize;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use toml_edit::{value, Array, DocumentMut};

use super::Config;

/// Get config file path based on global flag
fn get_config_path(global: bool) -> crate::Result<PathBuf> {
    let config_dir = if global {
        let home = dirs::home_dir()
            .ok_or_else(|| crate::LintisError::Config("Cannot find home directory".to_string()))?;
        home.join(".linthis")
    } else {
        PathBuf::from(".linthis")
    };
    fs::create_dir_all(&config_dir).map_err(|e| {
        crate::LintisError::Config(format!("Failed to create config directory: {}", e))
    })?;
    Ok(config_dir.join("config.toml"))
}

/// Ensure config file exists, create if not
fn ensure_config_file(config_path: &Path) -> crate::Result<()> {
    if !config_path.exists() {
        let default_content = Config::generate_default_toml();
        fs::write(config_path, default_content).map_err(|e| {
            crate::LintisError::Config(format!("Failed to create config file: {}", e))
        })?;
    }
    Ok(())
}

/// Load TOML document from config file
fn load_toml_doc(config_path: &Path) -> crate::Result<DocumentMut> {
    ensure_config_file(config_path)?;
    let content = fs::read_to_string(config_path)
        .map_err(|e| crate::LintisError::Config(format!("Failed to read config file: {}", e)))?;
    content
        .parse::<DocumentMut>()
        .map_err(|e| crate::LintisError::Config(format!("Failed to parse config file: {}", e)))
}

/// Save TOML document to config file
fn save_toml_doc(config_path: &Path, doc: &DocumentMut) -> crate::Result<()> {
    fs::write(config_path, doc.to_string())
        .map_err(|e| crate::LintisError::Config(format!("Failed to write config file: {}", e)))
}

/// Add value to an array field
pub fn handle_config_add(field: &str, value: &str, global: bool) -> ExitCode {
    let config_path = match get_config_path(global) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    let mut doc = match load_toml_doc(&config_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    // Get or create array
    if !doc.contains_key(field) {
        doc[field] = toml_edit::Item::Value(toml_edit::Value::Array(Array::new()));
    }

    let arr = match doc.get_mut(field).and_then(|item| item.as_array_mut()) {
        Some(a) => a,
        None => {
            eprintln!(
                "{}: Field '{}' exists but is not an array",
                "Error".red(),
                field
            );
            return ExitCode::from(1);
        }
    };

    // Check for duplicates
    if arr.iter().any(|v| v.as_str() == Some(value)) {
        eprintln!(
            "{}: Value '{}' already exists in '{}'",
            "Warning".yellow(),
            value,
            field
        );
        return ExitCode::SUCCESS;
    }

    // Add value
    arr.push(value);

    if let Err(e) = save_toml_doc(&config_path, &doc) {
        eprintln!("{}: {}", "Error".red(), e);
        return ExitCode::from(1);
    }

    let config_type = if global { "global" } else { "project" };
    println!(
        "{} Added '{}' to {} in {} configuration",
        "✓".green(),
        value.bold(),
        field,
        config_type
    );

    ExitCode::SUCCESS
}

/// Remove value from an array field
pub fn handle_config_remove(field: &str, value: &str, global: bool) -> ExitCode {
    let config_path = match get_config_path(global) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    if !config_path.exists() {
        eprintln!(
            "{}: Config file does not exist: {}",
            "Error".red(),
            config_path.display()
        );
        return ExitCode::from(1);
    }

    let mut doc = match load_toml_doc(&config_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    let arr = doc.get_mut(field).and_then(|v| v.as_array_mut());

    let arr = match arr {
        Some(a) => a,
        None => {
            eprintln!(
                "{}: Field '{}' not found or is not an array",
                "Error".red(),
                field
            );
            return ExitCode::from(1);
        }
    };

    // Find and remove value
    let initial_len = arr.len();
    arr.retain(|v| v.as_str() != Some(value));

    if arr.len() == initial_len {
        eprintln!(
            "{}: Value '{}' not found in '{}'",
            "Warning".yellow(),
            value,
            field
        );
        return ExitCode::SUCCESS;
    }

    if let Err(e) = save_toml_doc(&config_path, &doc) {
        eprintln!("{}: {}", "Error".red(), e);
        return ExitCode::from(1);
    }

    let config_type = if global { "global" } else { "project" };
    println!(
        "{} Removed '{}' from {} in {} configuration",
        "✓".green(),
        value.bold(),
        field,
        config_type
    );

    ExitCode::SUCCESS
}

/// Clear all values from an array field
pub fn handle_config_clear(field: &str, global: bool) -> ExitCode {
    let config_path = match get_config_path(global) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    if !config_path.exists() {
        eprintln!(
            "{}: Config file does not exist: {}",
            "Error".red(),
            config_path.display()
        );
        return ExitCode::from(1);
    }

    let mut doc = match load_toml_doc(&config_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    // Set field to empty array
    doc[field] = value(Array::new());

    if let Err(e) = save_toml_doc(&config_path, &doc) {
        eprintln!("{}: {}", "Error".red(), e);
        return ExitCode::from(1);
    }

    let config_type = if global { "global" } else { "project" };
    println!(
        "{} Cleared all values from {} in {} configuration",
        "✓".green(),
        field,
        config_type
    );

    ExitCode::SUCCESS
}

/// Validate and parse scalar field value
fn parse_scalar_value(field: &str, val: &str) -> crate::Result<toml_edit::Item> {
    match field {
        "max_complexity" => {
            let num = val.parse::<i64>().map_err(|_| {
                crate::LintisError::Config("max_complexity must be a positive integer".to_string())
            })?;
            if num < 0 {
                return Err(crate::LintisError::Config(
                    "max_complexity must be a positive integer".to_string(),
                ));
            }
            Ok(value(num))
        }
        "preset" => {
            if !["google", "standard", "airbnb"].contains(&val) {
                return Err(crate::LintisError::Config(
                    "preset must be one of: google, standard, airbnb".to_string(),
                ));
            }
            Ok(value(val))
        }
        "verbose" => {
            let _ = val.parse::<bool>().map_err(|_| {
                crate::LintisError::Config("verbose must be true or false".to_string())
            })?;
            Ok(value(val))
        }
        _ => Ok(value(val)),
    }
}

/// Set a scalar field value
pub fn handle_config_set(field: &str, value_str: &str, global: bool) -> ExitCode {
    let config_path = match get_config_path(global) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    let parsed_value = match parse_scalar_value(field, value_str) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    let mut doc = match load_toml_doc(&config_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    doc[field] = parsed_value;

    if let Err(e) = save_toml_doc(&config_path, &doc) {
        eprintln!("{}: {}", "Error".red(), e);
        return ExitCode::from(1);
    }

    let config_type = if global { "global" } else { "project" };
    println!(
        "{} Set {} = '{}' in {} configuration",
        "✓".green(),
        field.bold(),
        value_str,
        config_type
    );

    ExitCode::SUCCESS
}

/// Unset a scalar field
pub fn handle_config_unset(field: &str, global: bool) -> ExitCode {
    let config_path = match get_config_path(global) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    if !config_path.exists() {
        eprintln!(
            "{}: Config file does not exist: {}",
            "Error".red(),
            config_path.display()
        );
        return ExitCode::from(1);
    }

    let mut doc = match load_toml_doc(&config_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    if doc.get(field).is_none() {
        eprintln!(
            "{}: Field '{}' not found in configuration",
            "Warning".yellow(),
            field
        );
        return ExitCode::SUCCESS;
    }

    doc.remove(field);

    if let Err(e) = save_toml_doc(&config_path, &doc) {
        eprintln!("{}: {}", "Error".red(), e);
        return ExitCode::from(1);
    }

    let config_type = if global { "global" } else { "project" };
    println!(
        "{} Unset {} in {} configuration",
        "✓".green(),
        field.bold(),
        config_type
    );

    ExitCode::SUCCESS
}

/// Get value of a field
pub fn handle_config_get(field: &str, global: bool) -> ExitCode {
    let config_path = match get_config_path(global) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    if !config_path.exists() {
        eprintln!(
            "{}: Config file does not exist: {}",
            "Error".red(),
            config_path.display()
        );
        return ExitCode::from(1);
    }

    let doc = match load_toml_doc(&config_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    match doc.get(field) {
        Some(value) => {
            if let Some(arr) = value.as_array() {
                print!("[");
                for (i, v) in arr.iter().enumerate() {
                    if i > 0 {
                        print!(", ");
                    }
                    if let Some(s) = v.as_str() {
                        print!("\"{}\"", s);
                    } else {
                        print!("{}", v);
                    }
                }
                println!("]");
            } else {
                println!("{}", value);
            }
        }
        None => {
            eprintln!("{}: Field '{}' not found", "Error".red(), field);
            return ExitCode::from(1);
        }
    }

    ExitCode::SUCCESS
}

/// List all configuration values
pub fn handle_config_list(verbose: bool, global: bool) -> ExitCode {
    let config_path = match get_config_path(global) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    if !config_path.exists() {
        let config_type = if global { "global" } else { "project" };
        eprintln!(
            "{}: No {} configuration file found at {}",
            "Warning".yellow(),
            config_type,
            config_path.display()
        );
        return ExitCode::from(1);
    }

    let doc = match load_toml_doc(&config_path) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("{}: {}", "Error".red(), e);
            return ExitCode::from(1);
        }
    };

    let config_type = if global { "Global" } else { "Project" };
    println!(
        "{} Configuration ({})",
        config_type.bold(),
        config_path.display()
    );
    println!();

    if doc.is_empty() {
        println!("  {}", "(empty)".dimmed());
        return ExitCode::SUCCESS;
    }

    // Print configuration items
    for (key, value) in doc.iter() {
        if verbose {
            println!("{} = {}", key.cyan().bold(), value);
        } else {
            println!("{} = {}", key, value);
        }
    }

    ExitCode::SUCCESS
}

/// Fallback for home directory if dirs crate is not available
mod dirs {
    use std::path::PathBuf;

    pub fn home_dir() -> Option<PathBuf> {
        std::env::var("HOME")
            .ok()
            .map(PathBuf::from)
            .or_else(|| std::env::var("USERPROFILE").ok().map(PathBuf::from))
    }
}

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

    #[test]
    fn test_config_add_includes() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join(".linthis");
        fs::create_dir_all(&config_dir).unwrap();
        let config_path = config_dir.join("config.toml");

        // Create empty config
        fs::write(&config_path, "").unwrap();

        let mut doc = load_toml_doc(&config_path).unwrap();

        // Add to includes
        if !doc.contains_key("includes") {
            doc["includes"] = toml_edit::Item::Value(toml_edit::Value::Array(Array::new()));
        }
        let arr = doc.get_mut("includes").unwrap().as_array_mut().unwrap();
        arr.push("src/**");
        arr.push("lib/**");

        save_toml_doc(&config_path, &doc).unwrap();

        let config = Config::load(&config_path).unwrap();
        assert_eq!(config.includes, vec!["src/**", "lib/**"]);
    }

    #[test]
    fn test_config_add_dedup() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join(".linthis");
        fs::create_dir_all(&config_dir).unwrap();
        let config_path = config_dir.join("config.toml");

        fs::write(&config_path, "").unwrap();

        let mut doc = load_toml_doc(&config_path).unwrap();

        // Use manual key checking instead of entry().or_insert()
        if !doc.contains_key("excludes") {
            doc["excludes"] = toml_edit::Item::Value(toml_edit::Value::Array(Array::new()));
        }
        let arr = doc.get_mut("excludes").unwrap().as_array_mut().unwrap();

        // Add same value twice
        arr.push("*.log");
        if !arr.iter().any(|v| v.as_str() == Some("*.log")) {
            arr.push("*.log");
        }

        save_toml_doc(&config_path, &doc).unwrap();

        let config = Config::load(&config_path).unwrap();
        assert_eq!(config.excludes, vec!["*.log"]);
    }

    #[test]
    fn test_config_set_max_complexity() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join(".linthis");
        fs::create_dir_all(&config_dir).unwrap();
        let config_path = config_dir.join("config.toml");

        fs::write(&config_path, "").unwrap();

        let mut doc = load_toml_doc(&config_path).unwrap();
        doc["max_complexity"] = value(25i64);
        save_toml_doc(&config_path, &doc).unwrap();

        let config = Config::load(&config_path).unwrap();
        assert_eq!(config.max_complexity, Some(25));
    }

    #[test]
    fn test_parse_scalar_value() {
        assert!(parse_scalar_value("max_complexity", "20").is_ok());
        assert!(parse_scalar_value("max_complexity", "abc").is_err());
        assert!(parse_scalar_value("max_complexity", "-1").is_err());

        assert!(parse_scalar_value("preset", "google").is_ok());
        assert!(parse_scalar_value("preset", "invalid").is_err());

        assert!(parse_scalar_value("verbose", "true").is_ok());
        assert!(parse_scalar_value("verbose", "xyz").is_err());
    }
}