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

//! TUI application state and logic.

use std::path::PathBuf;

use crate::utils::types::{LintIssue, RunResult};
use crate::watch::{WatchConfig, WatchState};
use crate::Severity;

/// Application state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppState {
    /// Running normally
    Running,
    /// Help overlay is shown
    ShowingHelp,
    /// Quitting
    Quitting,
}

/// Which panel is focused
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FocusedPanel {
    /// File tree panel
    Files,
    /// Issues list panel
    Issues,
}

/// TUI Application
pub struct App {
    /// Current application state
    pub state: AppState,
    /// Watch configuration
    pub config: WatchConfig,
    /// Watch state (lint results)
    pub watch_state: WatchState,
    /// Currently focused panel
    pub focused_panel: FocusedPanel,
    /// Selected index in issues list
    pub issue_index: usize,
    /// Selected index in file tree
    pub file_index: usize,
    /// Scroll offset for issues
    pub issue_scroll: usize,
    /// Scroll offset for files
    pub file_scroll: usize,
    /// Whether a force re-run was requested
    pub force_rerun: bool,
    /// Status message to display
    pub status_message: Option<String>,
    /// Paths being watched
    pub watched_paths: Vec<PathBuf>,
}

impl App {
    /// Create a new App
    pub fn new(config: WatchConfig) -> Self {
        let watched_paths = config.paths.clone();
        Self {
            state: AppState::Running,
            config,
            watch_state: WatchState::new(),
            focused_panel: FocusedPanel::Issues,
            issue_index: 0,
            file_index: 0,
            issue_scroll: 0,
            file_scroll: 0,
            force_rerun: false,
            status_message: None,
            watched_paths,
        }
    }

    /// Check if app is running
    pub fn is_running(&self) -> bool {
        self.state != AppState::Quitting
    }

    /// Quit the application
    pub fn quit(&mut self) {
        self.state = AppState::Quitting;
    }

    /// Toggle help overlay
    pub fn toggle_help(&mut self) {
        self.state = match self.state {
            AppState::ShowingHelp => AppState::Running,
            _ => AppState::ShowingHelp,
        };
    }

    /// Switch focus between panels
    pub fn switch_focus(&mut self) {
        self.focused_panel = match self.focused_panel {
            FocusedPanel::Files => FocusedPanel::Issues,
            FocusedPanel::Issues => FocusedPanel::Files,
        };
    }

    /// Move selection up
    pub fn move_up(&mut self) {
        match self.focused_panel {
            FocusedPanel::Issues => {
                if self.issue_index > 0 {
                    self.issue_index -= 1;
                    self.adjust_issue_scroll();
                }
            }
            FocusedPanel::Files => {
                if self.file_index > 0 {
                    self.file_index -= 1;
                    self.adjust_file_scroll();
                }
            }
        }
    }

    /// Move selection down
    pub fn move_down(&mut self) {
        match self.focused_panel {
            FocusedPanel::Issues => {
                let max = self.watch_state.issues().len().saturating_sub(1);
                if self.issue_index < max {
                    self.issue_index += 1;
                    self.adjust_issue_scroll();
                }
            }
            FocusedPanel::Files => {
                let max = self.watch_state.file_count().saturating_sub(1);
                if self.file_index < max {
                    self.file_index += 1;
                    self.adjust_file_scroll();
                }
            }
        }
    }

    /// Adjust scroll to keep selection visible (issues)
    fn adjust_issue_scroll(&mut self) {
        // Assume visible height of ~20 lines
        const VISIBLE: usize = 20;
        if self.issue_index < self.issue_scroll {
            self.issue_scroll = self.issue_index;
        } else if self.issue_index >= self.issue_scroll + VISIBLE {
            self.issue_scroll = self.issue_index - VISIBLE + 1;
        }
    }

    /// Adjust scroll to keep selection visible (files)
    fn adjust_file_scroll(&mut self) {
        const VISIBLE: usize = 15;
        if self.file_index < self.file_scroll {
            self.file_scroll = self.file_index;
        } else if self.file_index >= self.file_scroll + VISIBLE {
            self.file_scroll = self.file_index - VISIBLE + 1;
        }
    }

    /// Request a force re-run
    pub fn request_rerun(&mut self) {
        self.force_rerun = true;
        self.set_status("Re-running...");
    }

    /// Check and clear force rerun flag
    pub fn take_force_rerun(&mut self) -> bool {
        let val = self.force_rerun;
        self.force_rerun = false;
        val
    }

    /// Clear all results
    pub fn clear(&mut self) {
        self.watch_state.clear();
        self.issue_index = 0;
        self.file_index = 0;
        self.issue_scroll = 0;
        self.file_scroll = 0;
        self.set_status("Cleared");
    }

    /// Set status message
    pub fn set_status(&mut self, msg: impl Into<String>) {
        self.status_message = Some(msg.into());
    }

    /// Clear status message
    pub fn clear_status(&mut self) {
        self.status_message = None;
    }

    /// Update from lint results
    pub fn update_results(&mut self, result: &RunResult) {
        self.watch_state.update_from_result(result);

        // Reset selection if out of bounds
        let issue_count = self.watch_state.issues().len();
        if self.issue_index >= issue_count && issue_count > 0 {
            self.issue_index = issue_count - 1;
        }

        // Update status
        if self.watch_state.is_clean() {
            self.set_status("✓ All clear!");
        } else {
            let errors = self.watch_state.error_count();
            let warnings = self.watch_state.warning_count();
            self.set_status(format!("{} errors, {} warnings", errors, warnings));
        }
    }

    /// Get currently selected issue
    pub fn selected_issue(&self) -> Option<&LintIssue> {
        self.watch_state.issues().get(self.issue_index)
    }

    /// Get file path and line for opening in editor
    pub fn selected_location(&self) -> Option<(PathBuf, usize)> {
        self.selected_issue()
            .map(|issue| (issue.file_path.clone(), issue.line))
    }

    /// Open selected file in editor
    pub fn open_in_editor(&self) -> Option<std::process::Output> {
        let (path, line) = self.selected_location()?;

        // Try common editors in order of preference
        let editors = [
            (
                "code",
                vec!["-g".to_string(), format!("{}:{}", path.display(), line)],
            ),
            (
                "cursor",
                vec!["-g".to_string(), format!("{}:{}", path.display(), line)],
            ),
            (
                "vim",
                vec![format!("+{}", line), path.display().to_string()],
            ),
            (
                "nvim",
                vec![format!("+{}", line), path.display().to_string()],
            ),
            (
                "nano",
                vec![format!("+{}", line), path.display().to_string()],
            ),
        ];

        for (editor, args) in editors {
            if let Ok(output) = std::process::Command::new(editor).args(&args).output() {
                return Some(output);
            }
        }

        None
    }

    /// Get issues grouped by severity for display
    pub fn issues_by_severity(&self) -> (Vec<&LintIssue>, Vec<&LintIssue>, Vec<&LintIssue>) {
        let issues = self.watch_state.issues();
        let mut errors = Vec::new();
        let mut warnings = Vec::new();
        let mut infos = Vec::new();

        for issue in issues {
            match issue.severity {
                Severity::Error => errors.push(issue),
                Severity::Warning => warnings.push(issue),
                Severity::Info => infos.push(issue),
            }
        }

        (errors, warnings, infos)
    }

    /// Get display path (relative to watched root if possible)
    pub fn display_path(&self, path: &std::path::Path) -> String {
        // Try to make path relative to first watched path
        if let Some(root) = self.watched_paths.first() {
            if let Ok(rel) = path.strip_prefix(root) {
                return rel.display().to_string();
            }
        }

        // Fall back to file name
        path.file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| path.display().to_string())
    }
}

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

    #[test]
    fn test_app_state_transitions() {
        let config = WatchConfig::default();
        let mut app = App::new(config);

        assert_eq!(app.state, AppState::Running);
        assert!(app.is_running());

        app.toggle_help();
        assert_eq!(app.state, AppState::ShowingHelp);

        app.toggle_help();
        assert_eq!(app.state, AppState::Running);

        app.quit();
        assert_eq!(app.state, AppState::Quitting);
        assert!(!app.is_running());
    }

    #[test]
    fn test_focus_switching() {
        let config = WatchConfig::default();
        let mut app = App::new(config);

        assert_eq!(app.focused_panel, FocusedPanel::Issues);

        app.switch_focus();
        assert_eq!(app.focused_panel, FocusedPanel::Files);

        app.switch_focus();
        assert_eq!(app.focused_panel, FocusedPanel::Issues);
    }

    #[test]
    fn test_navigation() {
        let config = WatchConfig::default();
        let mut app = App::new(config);

        // Add some mock issues
        let mut result = RunResult::new();
        result.issues.push(LintIssue {
            file_path: PathBuf::from("test.rs"),
            line: 1,
            column: None,
            message: "Error 1".to_string(),
            code: Some("E001".to_string()),
            severity: Severity::Error,
            source: Some("test".to_string()),
            suggestion: None,
            language: None,
            code_line: None,
            context_before: Vec::new(),
            context_after: Vec::new(),
        });
        result.issues.push(LintIssue {
            file_path: PathBuf::from("test.rs"),
            line: 2,
            column: None,
            message: "Error 2".to_string(),
            code: Some("E002".to_string()),
            severity: Severity::Error,
            source: Some("test".to_string()),
            suggestion: None,
            language: None,
            code_line: None,
            context_before: Vec::new(),
            context_after: Vec::new(),
        });
        app.update_results(&result);

        assert_eq!(app.issue_index, 0);

        app.move_down();
        assert_eq!(app.issue_index, 1);

        app.move_down(); // Should not go past end
        assert_eq!(app.issue_index, 1);

        app.move_up();
        assert_eq!(app.issue_index, 0);

        app.move_up(); // Should not go negative
        assert_eq!(app.issue_index, 0);
    }

    #[test]
    fn test_force_rerun() {
        let config = WatchConfig::default();
        let mut app = App::new(config);

        assert!(!app.force_rerun);

        app.request_rerun();
        assert!(app.force_rerun);

        assert!(app.take_force_rerun());
        assert!(!app.force_rerun);
    }
}