cargo-port 0.1.3

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
use crate::config::CargoPortConfig;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ConfigKey {
    CpuPollMs,
    CpuLowUtilizationMax,
    CpuMediumUtilizationMax,
    InvertScroll,
    IncludeNonRust,
    CiRunCount,
    Editor,
    MainBranch,
    OtherPrimaryBranches,
    IncludeDirs,
    InlineDirs,
    DiscoveryShimmerSecs,
    CacheRoot,
    LintEnabled,
    LintInclude,
    LintExclude,
    LintCommands,
    LintCacheSize,
    LintOnDiscovery,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ReloadDecision {
    #[default]
    Skip,
    Apply,
}

impl ReloadDecision {
    pub const fn should_apply(self) -> bool { matches!(self, Self::Apply) }
}

/// What the config reload should do to the project tree. The three
/// variants are ordered by escalation precedence: `FullRescan` wins
/// over `RegroupMembers`, which wins over `None`. The enum makes the
/// mutual exclusion exhaustive at the type level.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TreeReaction {
    #[default]
    None,
    RegroupMembers,
    FullRescan,
}

impl TreeReaction {
    const fn escalate(&mut self, to: Self) {
        if (to as u8) > (*self as u8) {
            *self = to;
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ReloadActions {
    pub tree:                 TreeReaction,
    pub refresh_cpu:          ReloadDecision,
    pub refresh_lint_runtime: ReloadDecision,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ReloadContext {
    pub scan_complete:       bool,
    pub has_cached_non_rust: bool,
}

#[derive(Clone, Copy)]
struct ConfigHandler {
    key:  ConfigKey,
    mark: fn(&mut ReloadActions, &CargoPortConfig, &CargoPortConfig, ReloadContext),
}

const CONFIG_HANDLERS: &[ConfigHandler] = &[
    ConfigHandler {
        key:  ConfigKey::CpuPollMs,
        mark: mark_refresh_cpu,
    },
    ConfigHandler {
        key:  ConfigKey::CpuLowUtilizationMax,
        mark: mark_refresh_cpu,
    },
    ConfigHandler {
        key:  ConfigKey::CpuMediumUtilizationMax,
        mark: mark_refresh_cpu,
    },
    ConfigHandler {
        key:  ConfigKey::InlineDirs,
        mark: mark_regroup_members,
    },
    ConfigHandler {
        key:  ConfigKey::IncludeNonRust,
        mark: mark_include_non_rust,
    },
    ConfigHandler {
        key:  ConfigKey::CiRunCount,
        mark: mark_full_rescan,
    },
    ConfigHandler {
        key:  ConfigKey::MainBranch,
        mark: mark_full_rescan,
    },
    ConfigHandler {
        key:  ConfigKey::OtherPrimaryBranches,
        mark: mark_full_rescan,
    },
    ConfigHandler {
        key:  ConfigKey::IncludeDirs,
        mark: mark_full_rescan,
    },
    ConfigHandler {
        key:  ConfigKey::CacheRoot,
        mark: mark_full_rescan,
    },
    ConfigHandler {
        key:  ConfigKey::CacheRoot,
        mark: mark_refresh_lint_runtime,
    },
    ConfigHandler {
        key:  ConfigKey::LintEnabled,
        mark: mark_refresh_lint_runtime,
    },
    ConfigHandler {
        key:  ConfigKey::LintInclude,
        mark: mark_refresh_lint_runtime,
    },
    ConfigHandler {
        key:  ConfigKey::LintExclude,
        mark: mark_refresh_lint_runtime,
    },
    ConfigHandler {
        key:  ConfigKey::LintCommands,
        mark: mark_refresh_lint_runtime,
    },
    ConfigHandler {
        key:  ConfigKey::LintCacheSize,
        mark: mark_refresh_lint_runtime,
    },
    ConfigHandler {
        key:  ConfigKey::LintOnDiscovery,
        mark: mark_refresh_lint_runtime,
    },
];

const fn mark_regroup_members(
    actions: &mut ReloadActions,
    _old: &CargoPortConfig,
    _new: &CargoPortConfig,
    _context: ReloadContext,
) {
    actions.tree.escalate(TreeReaction::RegroupMembers);
}

const fn mark_full_rescan(
    actions: &mut ReloadActions,
    _old: &CargoPortConfig,
    _new: &CargoPortConfig,
    _context: ReloadContext,
) {
    actions.tree.escalate(TreeReaction::FullRescan);
}

const fn mark_refresh_lint_runtime(
    actions: &mut ReloadActions,
    _old: &CargoPortConfig,
    _new: &CargoPortConfig,
    _context: ReloadContext,
) {
    actions.refresh_lint_runtime = ReloadDecision::Apply;
}

const fn mark_refresh_cpu(
    actions: &mut ReloadActions,
    _old: &CargoPortConfig,
    _new: &CargoPortConfig,
    _context: ReloadContext,
) {
    actions.refresh_cpu = ReloadDecision::Apply;
}

const fn mark_include_non_rust(
    actions: &mut ReloadActions,
    old: &CargoPortConfig,
    new: &CargoPortConfig,
    context: ReloadContext,
) {
    if !context.scan_complete {
        actions.tree.escalate(TreeReaction::FullRescan);
        return;
    }

    let enabling_non_rust = !old.tui.include_non_rust.includes_non_rust()
        && new.tui.include_non_rust.includes_non_rust();
    if enabling_non_rust && !context.has_cached_non_rust {
        actions.tree.escalate(TreeReaction::FullRescan);
    } else {
        actions.tree.escalate(TreeReaction::RegroupMembers);
    }
}

fn changed_keys(old: &CargoPortConfig, new: &CargoPortConfig) -> Vec<ConfigKey> {
    let mut keys = Vec::new();

    if old.cpu.poll_ms != new.cpu.poll_ms {
        keys.push(ConfigKey::CpuPollMs);
    }
    if old.cpu.low_utilization_max_percent != new.cpu.low_utilization_max_percent {
        keys.push(ConfigKey::CpuLowUtilizationMax);
    }
    if old.cpu.medium_utilization_max_percent != new.cpu.medium_utilization_max_percent {
        keys.push(ConfigKey::CpuMediumUtilizationMax);
    }
    if old.mouse.invert_scroll != new.mouse.invert_scroll {
        keys.push(ConfigKey::InvertScroll);
    }
    if old.tui.include_non_rust != new.tui.include_non_rust {
        keys.push(ConfigKey::IncludeNonRust);
    }
    if old.tui.ci_run_count != new.tui.ci_run_count {
        keys.push(ConfigKey::CiRunCount);
    }
    if old.tui.editor != new.tui.editor {
        keys.push(ConfigKey::Editor);
    }
    if old.tui.main_branch != new.tui.main_branch {
        keys.push(ConfigKey::MainBranch);
    }
    if old.tui.other_primary_branches != new.tui.other_primary_branches {
        keys.push(ConfigKey::OtherPrimaryBranches);
    }
    if old.tui.include_dirs != new.tui.include_dirs {
        keys.push(ConfigKey::IncludeDirs);
    }
    if old.tui.inline_dirs != new.tui.inline_dirs {
        keys.push(ConfigKey::InlineDirs);
    }
    if old.tui.discovery_shimmer_secs.to_bits() != new.tui.discovery_shimmer_secs.to_bits() {
        keys.push(ConfigKey::DiscoveryShimmerSecs);
    }
    if old.cache.root != new.cache.root {
        keys.push(ConfigKey::CacheRoot);
    }
    if old.lint.enabled != new.lint.enabled {
        keys.push(ConfigKey::LintEnabled);
    }
    if old.lint.include != new.lint.include {
        keys.push(ConfigKey::LintInclude);
    }
    if old.lint.exclude != new.lint.exclude {
        keys.push(ConfigKey::LintExclude);
    }
    if old.lint.commands != new.lint.commands {
        keys.push(ConfigKey::LintCommands);
    }
    if old.lint.cache_size != new.lint.cache_size {
        keys.push(ConfigKey::LintCacheSize);
    }
    if old.lint.on_discovery != new.lint.on_discovery {
        keys.push(ConfigKey::LintOnDiscovery);
    }

    keys
}

pub fn collect_reload_actions(
    old: &CargoPortConfig,
    new: &CargoPortConfig,
    context: ReloadContext,
) -> ReloadActions {
    let mut actions = ReloadActions::default();

    for key in changed_keys(old, new) {
        for handler in CONFIG_HANDLERS {
            if handler.key == key {
                (handler.mark)(&mut actions, old, new, context);
            }
        }
    }

    actions
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::NonRustInclusion;
    use crate::config::ScrollDirection;

    #[test]
    fn changed_keys_include_value_only_settings_without_actions() {
        let mut new = CargoPortConfig::default();
        new.mouse.invert_scroll = ScrollDirection::Normal;
        new.tui.editor = "helix".to_string();
        new.tui.discovery_shimmer_secs = 4.0;

        let keys = changed_keys(&CargoPortConfig::default(), &new);

        assert!(keys.contains(&ConfigKey::InvertScroll));
        assert!(keys.contains(&ConfigKey::Editor));
        assert!(keys.contains(&ConfigKey::DiscoveryShimmerSecs));
        assert_eq!(
            collect_reload_actions(&CargoPortConfig::default(), &new, ReloadContext::default()),
            ReloadActions::default()
        );
    }

    #[test]
    fn reload_actions_coalesce_rescan_triggers() {
        let mut new = CargoPortConfig::default();
        new.tui.ci_run_count = 9;
        new.tui.include_dirs = vec!["rust".to_string()];
        new.tui.include_non_rust = NonRustInclusion::Include;

        assert_eq!(
            collect_reload_actions(&CargoPortConfig::default(), &new, ReloadContext::default()),
            ReloadActions {
                tree:                 TreeReaction::FullRescan,
                refresh_cpu:          ReloadDecision::Skip,
                refresh_lint_runtime: ReloadDecision::Skip,
            }
        );
    }

    #[test]
    fn completed_scan_rebuilds_tree_when_hiding_cached_non_rust_projects() {
        let mut old = CargoPortConfig::default();
        old.tui.include_non_rust = NonRustInclusion::Include;
        let mut new = old.clone();
        new.tui.include_non_rust = NonRustInclusion::Exclude;

        assert_eq!(
            collect_reload_actions(
                &old,
                &new,
                ReloadContext {
                    scan_complete:       true,
                    has_cached_non_rust: true,
                },
            ),
            ReloadActions {
                tree:                 TreeReaction::RegroupMembers,
                refresh_cpu:          ReloadDecision::Skip,
                refresh_lint_runtime: ReloadDecision::Skip,
            }
        );
    }

    #[test]
    fn completed_scan_rescans_when_enabling_non_rust_without_cached_projects() {
        let mut new = CargoPortConfig::default();
        new.tui.include_non_rust = NonRustInclusion::Include;

        assert_eq!(
            collect_reload_actions(
                &CargoPortConfig::default(),
                &new,
                ReloadContext {
                    scan_complete:       true,
                    has_cached_non_rust: false,
                },
            ),
            ReloadActions {
                tree:                 TreeReaction::FullRescan,
                refresh_cpu:          ReloadDecision::Skip,
                refresh_lint_runtime: ReloadDecision::Skip,
            }
        );
    }

    #[test]
    fn reload_actions_coalesce_lint_triggers() {
        let mut new = CargoPortConfig::default();
        new.lint.enabled = true;
        new.lint.include = vec!["hana".to_string()];
        new.lint.commands = vec![crate::config::default_clippy_lint_command()];

        assert_eq!(
            collect_reload_actions(&CargoPortConfig::default(), &new, ReloadContext::default()),
            ReloadActions {
                tree:                 TreeReaction::None,
                refresh_cpu:          ReloadDecision::Skip,
                refresh_lint_runtime: ReloadDecision::Apply,
            }
        );
    }

    #[test]
    fn cache_root_marks_rescan_and_lint_runtime_refresh() {
        let mut new = CargoPortConfig::default();
        new.cache.root = "tmp-cache".to_string();

        assert_eq!(
            collect_reload_actions(&CargoPortConfig::default(), &new, ReloadContext::default()),
            ReloadActions {
                tree:                 TreeReaction::FullRescan,
                refresh_cpu:          ReloadDecision::Skip,
                refresh_lint_runtime: ReloadDecision::Apply,
            }
        );
    }

    #[test]
    fn cpu_settings_mark_refresh_cpu_only() {
        let mut new = CargoPortConfig::default();
        new.cpu.poll_ms = 1500;
        new.cpu.low_utilization_max_percent = 55;

        assert_eq!(
            collect_reload_actions(&CargoPortConfig::default(), &new, ReloadContext::default()),
            ReloadActions {
                tree:                 TreeReaction::None,
                refresh_cpu:          ReloadDecision::Apply,
                refresh_lint_runtime: ReloadDecision::Skip,
            }
        );
    }
}