cargo-port 0.2.0

A TUI for inspecting and managing Rust projects
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
//! The `Lint` subsystem.
//!
//! Owns the lint runtime, in-flight paths, the running-toast slot,
//! and the on-disk cache stat counter. Startup-pass trackers live on
//! the `Startup` subsystem.
//!
//! The four lookup functions (`status_for_path`, `status_for_root`,
//! `status_for_worktree`, `run_count_at`) return unframed
//! `LintStatus` — callers apply `animation_elapsed` to
//! `status.icon()` at render time.
//!
//! `package_display` returns a typed [`LintDisplay`] enum for the
//! Lint row in the Package detail pane. The renderer matches on
//! variants directly, so `PackageData.lint_display` carries
//! `LintDisplay` rather than a pre-rendered string.

use std::path::Path;
use std::time::Duration;
use std::time::Instant;

use ratatui::Frame;
use ratatui::layout::Position;
use ratatui::layout::Rect;
use tui_pane::Hittable;
use tui_pane::RenderFocus;
use tui_pane::Renderable;
use tui_pane::RunningTracker;
use tui_pane::ToastId;
use tui_pane::ToastTaskId;
use tui_pane::TrackedItem;
use tui_pane::Viewport;

use super::Config;
use super::constants::CATCH_UP_LINT_TOAST_TITLE;
use super::constants::NORMAL_LINT_TOAST_TITLE;
use crate::constants::LINT_NO_LOG;
use crate::lint::CacheUsage;
use crate::lint::LintRunOrigin;
use crate::lint::LintStatus;
use crate::lint::LintStatusKind;
use crate::lint::RuntimeHandle;
use crate::project;
use crate::project::AbsolutePath;
use crate::project::RootItem;
use crate::project::Visibility;
use crate::tui::columns::LintCell;
use crate::tui::hit_test::HoverTarget;
use crate::tui::integration;
use crate::tui::panes;
use crate::tui::panes::LintsData;
use crate::tui::panes::PaneId;
use crate::tui::project_list::ProjectList;
use crate::tui::render_context::PaneRenderCtx;

/// Display value for the Lint row in the Package detail pane.
///
/// Pattern: typed display values, not pre-rendered strings (see
/// "Recurring patterns" in `docs/app-api.md`). The Package
/// renderer matches on variants and applies `animation_elapsed`
/// to `status.icon()` at render time.
///
/// - `NotRust` — selected project is not a Rust project; no cargo lint applies.
/// - `NoRuns` — Rust project, but no lint history (zero runs).
/// - `Runs { count, status }` — Rust project with at least one lint run. `status` is unframed; the
///   renderer frames the icon at render time.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum LintDisplay {
    /// Default for partial / placeholder `PackageData` (e.g.,
    /// submodules and other non-Rust contexts where the Lint row
    /// is excluded by `package_fields_from_data` anyway).
    #[default]
    NotRust,
    NoRuns,
    Runs {
        count:  usize,
        status: LintStatus,
    },
}

/// The `Lint` subsystem. Owns the lint runtime, in-flight
/// paths, running-toast slot, and the disk cache stat counter.
pub struct Lint {
    /// Tokio runtime handle that runs cargo lint commands. Spawned
    /// at startup; replaced by [`Self::set_runtime`] when lint
    /// config (`lint.enabled`, `lint.parallel`, `lint.cache_root`)
    /// changes. `None` when lint is disabled.
    runtime:          Option<RuntimeHandle>,
    /// Presentation-only state for the sticky normal "N lints running" toast.
    /// This tracker is updated only from live `LintStatus` messages whose
    /// origin is [`LintRunOrigin::Normal`].
    running:          RunningTracker<AbsolutePath>,
    /// Presentation-only state for the sticky startup catch-up lint toast.
    /// Keeping this as a separate slot makes it impossible for a later normal
    /// lint to append to the catch-up toast.
    catch_up_running: RunningTracker<AbsolutePath>,
    /// The sticky "Lints paused" warning toast's id while lint is paused;
    /// `None` when running. Paused state is exactly "we hold this toast", so
    /// the toast cannot get out of sync with whether lint is paused.
    pause_toast:      Option<ToastId>,
    /// Bytes used by the on-disk lint-log cache (`~/.cache/cargo-port/lints/`).
    /// Refreshed by `App::refresh_lint_cache_usage_from_disk`,
    /// displayed in the Settings popup.
    pub cache_usage:  CacheUsage,
    /// Per-pane cursor for the Lints pane.
    pub viewport:     Viewport,
    /// Per-pane focus snapshot stamped before the render loop.
    pub focus:        RenderFocus,
    /// Cached Lints table content built per-frame in
    /// `panes::build_lints_data`.
    content:          Option<LintsData>,
}

impl Lint {
    /// Construct a fresh `Lint` carrying the runtime handle. The
    /// handle is initialized once at app startup; subsequent
    /// config-driven respawns flow through [`Self::set_runtime`].
    pub fn new(runtime: Option<RuntimeHandle>) -> Self {
        Self {
            runtime,
            running: RunningTracker::new(),
            catch_up_running: RunningTracker::new(),
            pause_toast: None,
            cache_usage: CacheUsage::default(),
            viewport: Viewport::new(),
            focus: RenderFocus::inactive(),
            content: None,
        }
    }

    // ── viewport ────────────────────────────────────────────────

    // ── content ─────────────────────────────────────────────────

    pub const fn content(&self) -> Option<&LintsData> { self.content.as_ref() }

    pub fn set_content(&mut self, data: LintsData) { self.content = Some(data); }

    pub fn clear_content(&mut self) { self.content = None; }

    // ── runtime ─────────────────────────────────────────────────

    /// The lint runtime handle, if lint is enabled.
    pub const fn runtime(&self) -> Option<&RuntimeHandle> { self.runtime.as_ref() }

    /// Clone the runtime handle. Used by spawn paths that want an
    /// owned handle (e.g., [`crate::tui::app::App::reload_lint_history`]).
    pub fn runtime_clone(&self) -> Option<RuntimeHandle> { self.runtime.clone() }

    /// Replace the runtime handle. Called by the config-reload
    /// path when lint settings change.
    pub fn set_runtime(&mut self, handle: Option<RuntimeHandle>) { self.runtime = handle; }

    // ── pause ───────────────────────────────────────────────────

    /// Whether lint is paused. Paused exactly when the sticky warning toast
    /// is held.
    pub const fn is_paused(&self) -> bool { self.pause_toast.is_some() }

    /// Record the sticky "paused" warning toast and enter the paused state.
    pub const fn set_pause_toast(&mut self, id: ToastId) { self.pause_toast = Some(id); }

    /// Leave the paused state, returning the sticky toast id to dismiss.
    pub const fn take_pause_toast(&mut self) -> Option<ToastId> { self.pause_toast.take() }

    // ── running toast projection ────────────────────────────────

    pub fn apply_lint_status(
        &mut self,
        path: AbsolutePath,
        kind: LintStatusKind,
        origin: LintRunOrigin,
    ) {
        match kind {
            LintStatusKind::Running => {
                self.remove_from_other_running_toast(origin, path.as_path());
                let tracker = self.running_tracker_mut(origin);
                tracker.running.entry(path).or_insert_with(Instant::now);
            },
            LintStatusKind::Passed
            | LintStatusKind::Failed
            | LintStatusKind::Stale
            | LintStatusKind::NoLog => self.clear_running_path(path.as_path()),
        }
    }

    pub fn clear_running_path(&mut self, path: &Path) {
        self.running.remove(path);
        self.catch_up_running.remove(path);
    }

    pub fn toast_items_for_origin(
        &self,
        origin: LintRunOrigin,
    ) -> (Option<ToastTaskId>, Vec<TrackedItem>) {
        self.running_tracker(origin).items_for_toast(
            |p| project::home_relative_path(p.as_path()),
            integration::path_key,
        )
    }

    pub const fn running_toast_title(origin: LintRunOrigin) -> &'static str {
        match origin {
            LintRunOrigin::CatchUp => CATCH_UP_LINT_TOAST_TITLE,
            LintRunOrigin::Normal => NORMAL_LINT_TOAST_TITLE,
        }
    }

    pub const fn set_running_toast_for_origin(
        &mut self,
        origin: LintRunOrigin,
        toast: Option<ToastTaskId>,
    ) {
        match origin {
            LintRunOrigin::CatchUp => self.catch_up_running.toast = toast,
            LintRunOrigin::Normal => self.running.toast = toast,
        }
    }

    #[cfg(test)]
    pub fn running_toast_is_empty(&self) -> bool {
        self.running.is_empty() && self.catch_up_running.is_empty()
    }

    #[cfg(test)]
    pub const fn running_toast_id(&self) -> Option<ToastTaskId> { self.running.toast }

    pub fn running_toast_path_count(&self) -> usize {
        self.running.running.len() + self.catch_up_running.running.len()
    }

    #[cfg(test)]
    pub fn running_toast_contains_path(&self, path: &Path) -> bool {
        self.running.running.contains_key(path) || self.catch_up_running.running.contains_key(path)
    }

    #[cfg(test)]
    pub fn normal_running_toast_contains_path(&self, path: &Path) -> bool {
        self.running.running.contains_key(path)
    }

    #[cfg(test)]
    pub fn catch_up_running_toast_contains_path(&self, path: &Path) -> bool {
        self.catch_up_running.running.contains_key(path)
    }

    const fn running_tracker(&self, origin: LintRunOrigin) -> &RunningTracker<AbsolutePath> {
        match origin {
            LintRunOrigin::CatchUp => &self.catch_up_running,
            LintRunOrigin::Normal => &self.running,
        }
    }

    const fn running_tracker_mut(
        &mut self,
        origin: LintRunOrigin,
    ) -> &mut RunningTracker<AbsolutePath> {
        match origin {
            LintRunOrigin::CatchUp => &mut self.catch_up_running,
            LintRunOrigin::Normal => &mut self.running,
        }
    }

    fn remove_from_other_running_toast(&mut self, origin: LintRunOrigin, path: &Path) {
        match origin {
            LintRunOrigin::CatchUp => {
                self.running.remove(path);
            },
            LintRunOrigin::Normal => {
                self.catch_up_running.remove(path);
            },
        }
    }

    // ── cache usage ─────────────────────────────────────────────

    pub const fn set_cache_usage(&mut self, usage: CacheUsage) { self.cache_usage = usage; }

    // ── read-side lookups ───────────────────────────────────────

    /// Lint status of the project at `path`. Returns
    /// [`LintStatus::NoLog`] when the path has no lint history.
    pub fn status_for_path(projects: &ProjectList, path: &Path) -> LintStatus {
        projects
            .lint_at_path(path)
            .map_or(LintStatus::NoLog, |lr| lr.status().clone())
    }

    /// Lint status of a `RootItem` (single project or worktree
    /// group), aggregated across the group's checkouts when
    /// applicable. Delegates to [`RootItem::lint_rollup_status`].
    pub fn status_for_root(item: &RootItem) -> LintStatus { item.lint_rollup_status() }

    /// Lint status of a single worktree entry within a worktree
    /// group; `worktree_index` 0 is the primary checkout.
    pub fn status_for_worktree(item: &RootItem, worktree_index: usize) -> LintStatus {
        match item {
            RootItem::Worktrees(group) => group.lint_status_for_worktree(worktree_index),
            _ => LintStatus::NoLog,
        }
    }

    /// Run count at `path`, or 0 when no lint history exists.
    pub fn run_count_at(projects: &ProjectList, path: &Path) -> usize {
        projects.lint_at_path(path).map_or(0, |lr| lr.runs().len())
    }

    /// Build the [`LintDisplay`] for the Package detail pane row
    /// at the selected project.
    ///
    /// `is_worktree_group` is true when the selected row's
    /// package title is "Worktree Group" — i.e., the detail
    /// pane is showing a worktree-group rollup. In that case the
    /// status aggregates across the group's checkouts and the run
    /// count sums across them. Otherwise the lookup is per-path.
    pub fn package_display(
        projects: &ProjectList,
        abs: &AbsolutePath,
        is_worktree_group: bool,
        is_rust: bool,
    ) -> LintDisplay {
        if !is_rust {
            return LintDisplay::NotRust;
        }
        let path = abs.as_path();
        let (status, count) = if is_worktree_group {
            let group_item = projects.iter().find(|entry| {
                entry.root_item.path() == abs && matches!(&entry.root_item, RootItem::Worktrees(_))
            });
            match group_item.map(|entry| &entry.root_item) {
                Some(item @ RootItem::Worktrees(group)) => {
                    let status = Self::status_for_root(item);
                    let count: usize = group
                        .iter_entries()
                        .filter(|entry| entry.visibility() == Visibility::Visible)
                        .map(|entry| Self::run_count_at(projects, entry.path().as_path()))
                        .sum();
                    (status, count)
                },
                _ => (
                    Self::status_for_path(projects, path),
                    Self::run_count_at(projects, path),
                ),
            }
        } else {
            (
                Self::status_for_path(projects, path),
                Self::run_count_at(projects, path),
            )
        };
        // A first, in-progress run has no completed history yet
        // (count == 0). Still surface it as `Runs` so the detail pane
        // shows the spinner — matching the project-list column and
        // toast, which key off `status` directly. The renderer omits
        // the `0` count while it's zero.
        if count == 0 && !matches!(status, LintStatus::Running(_)) {
            LintDisplay::NoRuns
        } else {
            LintDisplay::Runs { count, status }
        }
    }
}

/// Resolve a [`LintStatus`] to the [`LintCell`] (icon + style
/// pair) rendered in the Lint column. Free fn so renderers can
/// call it from `Pane::render` with typed refs (no `&App`).
pub fn lint_cell_for(
    status: &LintStatus,
    config: &Config,
    animation_elapsed: Duration,
) -> LintCell {
    if !config.lint_enabled() {
        return LintCell::from_parts(LINT_NO_LOG, ratatui::style::Style::default());
    }
    let icon = integration::lint_icon_for(status.kind()).frame_at(animation_elapsed);
    let style = if matches!(status, LintStatus::Running(_)) {
        ratatui::style::Style::default().fg(tui_pane::accent_color())
    } else {
        ratatui::style::Style::default()
    };
    LintCell::from_parts(icon, style)
}

impl Renderable<PaneRenderCtx<'_>> for Lint {
    fn render(&mut self, frame: &mut Frame<'_>, area: Rect, ctx: &PaneRenderCtx<'_>) {
        panes::render_lints_pane_body(frame, area, self, ctx);
    }
}

impl Hittable<HoverTarget> for Lint {
    fn hit_test_at(&self, pos: Position) -> Option<HoverTarget> {
        let row = panes::hit_test_table_row(&self.viewport, pos)?;
        Some(HoverTarget::PaneRow {
            pane: PaneId::Lints,
            row,
        })
    }
}

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

    #[test]
    fn new_starts_with_no_runtime_and_empty_inflight() {
        let lint = Lint::new(None);
        assert!(lint.runtime().is_none());
        assert!(lint.running_toast_is_empty());
        assert!(lint.running_toast_id().is_none());
    }

    #[test]
    fn running_toast_round_trip() {
        let mut lint = Lint::new(None);
        lint.set_running_toast_for_origin(LintRunOrigin::Normal, Some(ToastTaskId(7)));
        assert_eq!(lint.running_toast_id(), Some(tui_pane::ToastTaskId(7)));
        lint.set_running_toast_for_origin(LintRunOrigin::Normal, None);
        assert!(lint.running_toast_id().is_none());
    }

    #[test]
    fn running_lint_toasts_are_separate_by_origin() {
        let mut lint = Lint::new(None);
        let path = AbsolutePath::from(Path::new("/abs/a"));

        lint.apply_lint_status(
            path.clone(),
            LintStatusKind::Running,
            LintRunOrigin::CatchUp,
        );
        assert!(lint.catch_up_running_toast_contains_path(path.as_path()));
        assert!(!lint.normal_running_toast_contains_path(path.as_path()));

        lint.apply_lint_status(path.clone(), LintStatusKind::Running, LintRunOrigin::Normal);
        assert!(!lint.catch_up_running_toast_contains_path(path.as_path()));
        assert!(lint.normal_running_toast_contains_path(path.as_path()));

        lint.apply_lint_status(path.clone(), LintStatusKind::Passed, LintRunOrigin::Normal);
        assert!(!lint.running_toast_contains_path(path.as_path()));
    }

    #[test]
    fn package_display_returns_not_rust_when_is_rust_false() {
        let projects = ProjectList::default();
        let abs = AbsolutePath::from(Path::new("/abs/x"));
        assert_eq!(
            Lint::package_display(&projects, &abs, false, false),
            LintDisplay::NotRust,
        );
    }

    #[test]
    fn package_display_returns_no_runs_when_rust_with_zero_runs() {
        let projects = ProjectList::default();
        let abs = AbsolutePath::from(Path::new("/abs/x"));
        assert_eq!(
            Lint::package_display(&projects, &abs, false, true),
            LintDisplay::NoRuns,
        );
    }

    #[test]
    fn run_count_at_returns_zero_for_unknown_path() {
        let projects = ProjectList::default();
        assert_eq!(Lint::run_count_at(&projects, Path::new("/abs/missing")), 0);
    }

    #[test]
    fn status_for_path_returns_no_log_for_unknown_path() {
        let projects = ProjectList::default();
        assert_eq!(
            Lint::status_for_path(&projects, Path::new("/abs/missing")),
            LintStatus::NoLog,
        );
    }
}