linthis 0.22.0

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
// 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.

//! Configuration resolver for linthis with priority-based config lookup.
//!
//! This module implements the configuration priority system:
//!
//! 1. **Local manual configs** (highest) - ruff.toml, pyproject.toml, .eslintrc.js in project
//! 2. **CLI plugin configs** - from `--use-plugin` (referenced, not copied)
//! 3. **Project plugin configs** - from `.linthis/config.toml` plugins section
//! 4. **Global plugin configs** - from `~/.linthis/config.toml` plugins
//! 5. **Tool defaults** (lowest)

use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Source of a plugin configuration (determines priority)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ConfigSource {
    /// From `--use-plugin` CLI option (priority 2)
    CliPlugin,
    /// From project `.linthis/config.toml` plugins section (priority 3)
    ProjectPlugin,
    /// From global `~/.linthis/config.toml` plugins (priority 4)
    GlobalPlugin,
}

impl ConfigSource {
    /// Get the priority level (lower number = higher priority)
    pub fn priority(&self) -> u8 {
        match self {
            ConfigSource::CliPlugin => 2,
            ConfigSource::ProjectPlugin => 3,
            ConfigSource::GlobalPlugin => 4,
        }
    }
}

/// A resolved configuration from a plugin
#[derive(Debug, Clone)]
pub struct ResolvedConfig {
    /// Language this config applies to (e.g., "python", "typescript")
    pub language: String,
    /// Tool this config is for (e.g., "ruff", "eslint")
    pub tool: String,
    /// Path to the actual config file in plugin cache
    pub config_path: PathBuf,
    /// Source of this config (determines priority)
    pub source: ConfigSource,
    /// Plugin name for display purposes
    pub plugin_name: String,
}

impl ResolvedConfig {
    /// Create a new resolved config
    pub fn new(
        language: impl Into<String>,
        tool: impl Into<String>,
        config_path: PathBuf,
        source: ConfigSource,
        plugin_name: impl Into<String>,
    ) -> Self {
        Self {
            language: language.into(),
            tool: tool.into(),
            config_path,
            source,
            plugin_name: plugin_name.into(),
        }
    }
}

/// Configuration resolver that manages plugin configs with priority ordering.
///
/// The resolver holds references to plugin configs (not copies) and provides
/// methods to look up the appropriate config for a given language/tool,
/// respecting the priority order.
#[derive(Debug, Clone, Default)]
pub struct ConfigResolver {
    /// Plugin configs sorted by priority (higher priority first)
    configs: Vec<ResolvedConfig>,
}

impl ConfigResolver {
    /// Create a new empty config resolver
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new config resolver with the given configs
    pub fn with_configs(mut configs: Vec<ResolvedConfig>) -> Self {
        // Sort by priority (lower priority number = higher priority)
        configs.sort_by_key(|c| c.source.priority());
        Self { configs }
    }

    /// Add a resolved config to the resolver
    pub fn add_config(&mut self, config: ResolvedConfig) {
        self.configs.push(config);
        // Re-sort after adding
        self.configs.sort_by_key(|c| c.source.priority());
    }

    /// Add multiple resolved configs to the resolver
    pub fn add_configs(&mut self, configs: impl IntoIterator<Item = ResolvedConfig>) {
        self.configs.extend(configs);
        // Re-sort after adding
        self.configs.sort_by_key(|c| c.source.priority());
    }

    /// Get the config path for a language/tool, checking local configs first.
    ///
    /// Priority order:
    /// 1. Local manual config (searched from file's directory upward)
    /// 2. Plugin config (from resolver, sorted by source priority)
    /// 3. None (tool should use defaults)
    pub fn get_config(&self, lang: &str, tool: &str, file: &Path) -> Option<PathBuf> {
        // Priority 1: Check for local manual config first
        if let Some(local) = find_local_config(lang, tool, file) {
            return Some(local);
        }

        // Priority 2-4: Return first matching plugin config (already sorted by priority)
        self.configs
            .iter()
            .find(|c| c.language == lang && c.tool == tool)
            .map(|c| c.config_path.clone())
    }

    /// Get the config path for a language/tool without checking local configs.
    /// This is useful when you only want plugin configs.
    ///
    /// Supports tool aliases (e.g., "ruff" matches "ruff-from-flake8").
    pub fn get_plugin_config(&self, lang: &str, tool: &str) -> Option<PathBuf> {
        // First try exact match
        if let Some(config) = self
            .configs
            .iter()
            .find(|c| c.language == lang && c.tool == tool)
        {
            return Some(config.config_path.clone());
        }

        // Try alias match (e.g., "ruff" matches "ruff-from-flake8")
        let aliases = get_tool_aliases(tool);
        for alias in aliases {
            if let Some(config) = self
                .configs
                .iter()
                .find(|c| c.language == lang && c.tool == alias)
            {
                return Some(config.config_path.clone());
            }
        }

        None
    }

    /// Get all configs for a given language
    pub fn get_configs_for_language(&self, lang: &str) -> Vec<&ResolvedConfig> {
        self.configs.iter().filter(|c| c.language == lang).collect()
    }

    /// Get all configs for a given tool
    pub fn get_configs_for_tool(&self, tool: &str) -> Vec<&ResolvedConfig> {
        self.configs.iter().filter(|c| c.tool == tool).collect()
    }

    /// Get the number of configs in the resolver
    pub fn len(&self) -> usize {
        self.configs.len()
    }

    /// Check if the resolver has no configs
    pub fn is_empty(&self) -> bool {
        self.configs.is_empty()
    }

    /// Get all configs as a slice
    pub fn configs(&self) -> &[ResolvedConfig] {
        &self.configs
    }
}

/// Find local manual config file by walking up from the file's directory.
///
/// This implements Priority 1: local manual configs take precedence over plugin configs.
pub fn find_local_config(lang: &str, tool: &str, file: &Path) -> Option<PathBuf> {
    let config_names = get_config_names(lang, tool);
    if config_names.is_empty() {
        return None;
    }

    let mut current = if file.is_file() {
        file.parent()?.to_path_buf()
    } else {
        file.to_path_buf()
    };

    loop {
        for config_name in &config_names {
            let config_path = current.join(config_name);
            if config_path.exists() {
                // Skip configs in .linthis/configs/ directory (those are plugin configs)
                if !is_plugin_config_path(&config_path) {
                    return Some(config_path);
                }
            }
        }

        if !current.pop() {
            break;
        }
    }

    None
}

/// Check if a path is inside a .linthis/configs/ directory (plugin config location)
fn is_plugin_config_path(path: &Path) -> bool {
    let path_str = path.to_string_lossy();
    path_str.contains(".linthis/configs/") || path_str.contains(".linthis\\configs\\")
}

/// Get tool aliases for matching plugin configs.
///
/// Some plugins use descriptive tool names like "ruff-from-flake8" instead of "ruff".
/// This function returns a list of aliases that should be checked.
fn get_tool_aliases(tool: &str) -> Vec<&'static str> {
    match tool {
        "ruff" => vec!["ruff-from-flake8"],
        "eslint" => vec!["eslint-from-tslint"],
        "clang-format" => vec!["clang-format-from-idea"],
        _ => vec![],
    }
}

/// Get the list of config file names to search for a given language/tool
fn get_config_names(lang: &str, tool: &str) -> Vec<&'static str> {
    match (lang, tool) {
        ("python", "ruff") => vec!["ruff.toml", ".ruff.toml", "pyproject.toml"],
        ("typescript" | "javascript", "eslint") => vec![
            ".eslintrc.js",
            ".eslintrc.cjs",
            ".eslintrc.json",
            ".eslintrc.yml",
            ".eslintrc.yaml",
            "eslint.config.js",
            "eslint.config.mjs",
            "eslint.config.cjs",
        ],
        ("typescript" | "javascript", "prettier") => vec![
            ".prettierrc",
            ".prettierrc.json",
            ".prettierrc.yml",
            ".prettierrc.yaml",
            ".prettierrc.js",
            ".prettierrc.cjs",
            "prettier.config.js",
            "prettier.config.cjs",
        ],
        ("go", "golangci-lint") => vec![
            ".golangci.yml",
            ".golangci.yaml",
            ".golangci.toml",
            ".golangci.json",
        ],
        ("cpp" | "oc", "clang-tidy") => vec![".clang-tidy"],
        ("cpp" | "oc", "clang-format") => vec![".clang-format", "_clang-format"],
        ("rust", "clippy") => vec!["clippy.toml", ".clippy.toml"],
        ("rust", "rustfmt") => vec!["rustfmt.toml", ".rustfmt.toml"],
        ("java", "checkstyle") => vec!["checkstyle.xml"],
        ("kotlin", "ktlint") => vec![".editorconfig"],
        ("swift", "swiftlint") => vec![".swiftlint.yml", ".swiftlint.yaml"],
        ("dart", "analysis_options") => vec!["analysis_options.yaml"],
        ("lua", "luacheck") => vec![".luacheckrc"],
        ("lua", "stylua") => vec!["stylua.toml", ".stylua.toml"],
        ("shell", "shellcheck") => vec![".shellcheckrc"],
        ("ruby", "rubocop") => vec![".rubocop.yml"],
        ("php", "phpcs") => vec![
            "phpcs.xml",
            "phpcs.xml.dist",
            ".phpcs.xml",
            ".phpcs.xml.dist",
        ],
        ("scala", "scalafmt") => vec![".scalafmt.conf"],
        ("*", "linthis-secrets") => vec!["secrets.toml", ".secrets.toml"],
        _ => vec![],
    }
}

/// Builder for creating a ConfigResolver with configs from multiple sources
#[derive(Debug, Default)]
pub struct ConfigResolverBuilder {
    configs: Vec<ResolvedConfig>,
}

impl ConfigResolverBuilder {
    /// Create a new builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Add configs from CLI plugins (--use-plugin)
    pub fn with_cli_plugins(
        mut self,
        plugin_configs: Vec<(String, String, PathBuf, String)>,
    ) -> Self {
        for (lang, tool, path, plugin_name) in plugin_configs {
            self.configs.push(ResolvedConfig::new(
                lang,
                tool,
                path,
                ConfigSource::CliPlugin,
                plugin_name,
            ));
        }
        self
    }

    /// Add configs from project plugins (.linthis/config.toml)
    pub fn with_project_plugins(
        mut self,
        plugin_configs: Vec<(String, String, PathBuf, String)>,
    ) -> Self {
        for (lang, tool, path, plugin_name) in plugin_configs {
            self.configs.push(ResolvedConfig::new(
                lang,
                tool,
                path,
                ConfigSource::ProjectPlugin,
                plugin_name,
            ));
        }
        self
    }

    /// Add configs from global plugins (~/.linthis/)
    pub fn with_global_plugins(
        mut self,
        plugin_configs: Vec<(String, String, PathBuf, String)>,
    ) -> Self {
        for (lang, tool, path, plugin_name) in plugin_configs {
            self.configs.push(ResolvedConfig::new(
                lang,
                tool,
                path,
                ConfigSource::GlobalPlugin,
                plugin_name,
            ));
        }
        self
    }

    /// Build the ConfigResolver
    pub fn build(self) -> ConfigResolver {
        ConfigResolver::with_configs(self.configs)
    }
}

/// Thread-safe shared ConfigResolver
pub type SharedConfigResolver = Arc<ConfigResolver>;

/// Create a shared (Arc) ConfigResolver
pub fn shared_resolver(resolver: ConfigResolver) -> SharedConfigResolver {
    Arc::new(resolver)
}

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

    #[test]
    fn test_config_source_priority() {
        assert!(ConfigSource::CliPlugin.priority() < ConfigSource::ProjectPlugin.priority());
        assert!(ConfigSource::ProjectPlugin.priority() < ConfigSource::GlobalPlugin.priority());
    }

    #[test]
    fn test_config_resolver_sorting() {
        let resolver = ConfigResolver::with_configs(vec![
            ResolvedConfig::new(
                "python",
                "ruff",
                PathBuf::from("/global/ruff.toml"),
                ConfigSource::GlobalPlugin,
                "global",
            ),
            ResolvedConfig::new(
                "python",
                "ruff",
                PathBuf::from("/cli/ruff.toml"),
                ConfigSource::CliPlugin,
                "cli",
            ),
            ResolvedConfig::new(
                "python",
                "ruff",
                PathBuf::from("/project/ruff.toml"),
                ConfigSource::ProjectPlugin,
                "project",
            ),
        ]);

        // Should be sorted: CLI (2) < Project (3) < Global (4)
        let configs = resolver.configs();
        assert_eq!(configs[0].source, ConfigSource::CliPlugin);
        assert_eq!(configs[1].source, ConfigSource::ProjectPlugin);
        assert_eq!(configs[2].source, ConfigSource::GlobalPlugin);
    }

    #[test]
    fn test_get_plugin_config() {
        let resolver = ConfigResolver::with_configs(vec![
            ResolvedConfig::new(
                "python",
                "ruff",
                PathBuf::from("/cli/ruff.toml"),
                ConfigSource::CliPlugin,
                "cli",
            ),
            ResolvedConfig::new(
                "python",
                "ruff",
                PathBuf::from("/project/ruff.toml"),
                ConfigSource::ProjectPlugin,
                "project",
            ),
        ]);

        // Should return CLI plugin config (higher priority)
        let config = resolver.get_plugin_config("python", "ruff");
        assert_eq!(config, Some(PathBuf::from("/cli/ruff.toml")));
    }

    #[test]
    fn test_get_plugin_config_not_found() {
        let resolver = ConfigResolver::new();
        let config = resolver.get_plugin_config("python", "ruff");
        assert_eq!(config, None);
    }

    #[test]
    fn test_local_config_has_priority() {
        // Create temp directory with local ruff.toml
        let temp = tempdir().unwrap();
        let local_config = temp.path().join("ruff.toml");
        fs::write(&local_config, "# local config").unwrap();

        let test_file = temp.path().join("test.py");
        fs::write(&test_file, "# test").unwrap();

        // Create resolver with plugin config
        let resolver = ConfigResolver::with_configs(vec![ResolvedConfig::new(
            "python",
            "ruff",
            PathBuf::from("/plugin/ruff.toml"),
            ConfigSource::CliPlugin,
            "plugin",
        )]);

        // Should return local config (priority 1) over plugin config (priority 2)
        let config = resolver.get_config("python", "ruff", &test_file);
        assert_eq!(config, Some(local_config));
    }

    #[test]
    fn test_plugin_config_used_when_no_local() {
        // Create temp directory WITHOUT local config
        let temp = tempdir().unwrap();
        let test_file = temp.path().join("test.py");
        fs::write(&test_file, "# test").unwrap();

        // Create resolver with plugin config
        let plugin_path = PathBuf::from("/plugin/ruff.toml");
        let resolver = ConfigResolver::with_configs(vec![ResolvedConfig::new(
            "python",
            "ruff",
            plugin_path.clone(),
            ConfigSource::CliPlugin,
            "plugin",
        )]);

        // Should return plugin config when no local config exists
        let config = resolver.get_config("python", "ruff", &test_file);
        assert_eq!(config, Some(plugin_path));
    }

    #[test]
    fn test_is_plugin_config_path() {
        assert!(is_plugin_config_path(Path::new(
            "/project/.linthis/configs/python/ruff.toml"
        )));
        assert!(is_plugin_config_path(Path::new(
            "C:\\project\\.linthis\\configs\\python\\ruff.toml"
        )));
        assert!(!is_plugin_config_path(Path::new("/project/ruff.toml")));
        assert!(!is_plugin_config_path(Path::new(
            "/project/.linthis/config.toml"
        )));
    }

    #[test]
    fn test_get_config_names_python() {
        let names = get_config_names("python", "ruff");
        assert!(names.contains(&"ruff.toml"));
        assert!(names.contains(&".ruff.toml"));
        assert!(names.contains(&"pyproject.toml"));
    }

    #[test]
    fn test_get_config_names_typescript() {
        let names = get_config_names("typescript", "eslint");
        assert!(names.contains(&".eslintrc.js"));
        assert!(names.contains(&"eslint.config.js"));
    }

    #[test]
    fn test_builder() {
        let resolver = ConfigResolverBuilder::new()
            .with_cli_plugins(vec![(
                "python".to_string(),
                "ruff".to_string(),
                PathBuf::from("/cli/ruff.toml"),
                "cli-plugin".to_string(),
            )])
            .with_project_plugins(vec![(
                "python".to_string(),
                "ruff".to_string(),
                PathBuf::from("/project/ruff.toml"),
                "project-plugin".to_string(),
            )])
            .build();

        assert_eq!(resolver.len(), 2);

        // CLI plugin should come first (higher priority)
        let configs = resolver.configs();
        assert_eq!(configs[0].source, ConfigSource::CliPlugin);
        assert_eq!(configs[1].source, ConfigSource::ProjectPlugin);
    }

    #[test]
    fn test_resolver_len_and_is_empty() {
        let resolver = ConfigResolver::new();
        assert!(resolver.is_empty());
        assert_eq!(resolver.len(), 0);

        let resolver = ConfigResolver::with_configs(vec![ResolvedConfig::new(
            "python",
            "ruff",
            PathBuf::from("/ruff.toml"),
            ConfigSource::CliPlugin,
            "test",
        )]);
        assert!(!resolver.is_empty());
        assert_eq!(resolver.len(), 1);
    }
}