bath 0.6.0

A TUI tool to manage and export environment variable profiles
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
use crate::tui::daisyui_themes;
use crate::tui::input::{self, Action};
use crate::tui::state::{AppState, ConfirmAction, Overlay, PromptAction};
use crate::tui::view::Tab;
use anyhow::Result;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
    Goto(Tab),
    AddVar,
    AddItem,
    AddDef,
    AddProfile,
    Remove,
    Use,
    Duplicate,
    Rename,
    Save,
    Theme,
    Quit,
}

pub struct Spec {
    pub names: &'static [&'static str],
    pub command: Command,
    pub help: &'static str,
}

pub const COMMANDS: &[Spec] = &[
    Spec {
        names: &["env", "edit"],
        command: Command::Goto(Tab::Env),
        help: "edit the active profile",
    },
    Spec {
        names: &["profiles"],
        command: Command::Goto(Tab::Profiles),
        help: "list profiles",
    },
    Spec {
        names: &["library", "lib", "items"],
        command: Command::Goto(Tab::Library),
        help: "values you reuse across profiles",
    },
    Spec {
        names: &["defs"],
        command: Command::Goto(Tab::Defs),
        help: "your variable definitions",
    },
    Spec {
        names: &["export", "preview"],
        command: Command::Goto(Tab::Export),
        help: "shell output for the active profile",
    },
    Spec {
        names: &["help"],
        command: Command::Goto(Tab::Help),
        help: "keys and commands",
    },
    Spec {
        names: &["add-var", "new-var", "av"],
        command: Command::AddVar,
        help: "add a line to the env file",
    },
    Spec {
        names: &["add-item", "new-item", "ai"],
        command: Command::AddItem,
        help: "add a value to the library",
    },
    Spec {
        names: &["add-def", "new-def", "ad"],
        command: Command::AddDef,
        help: "add a variable definition",
    },
    Spec {
        names: &["add-profile", "new-profile", "ap"],
        command: Command::AddProfile,
        help: "create an empty profile",
    },
    Spec {
        names: &["rm", "del", "delete"],
        command: Command::Remove,
        help: "rm [VAR]: remove a var, line or profile",
    },
    Spec {
        names: &["use", "switch"],
        command: Command::Use,
        help: "use <profile>",
    },
    Spec {
        names: &["dup", "duplicate", "copy"],
        command: Command::Duplicate,
        help: "copy the selected profile",
    },
    Spec {
        names: &["rename", "mv"],
        command: Command::Rename,
        help: "rename the selected profile",
    },
    Spec {
        names: &["save", "w"],
        command: Command::Save,
        help: "save the current tab",
    },
    Spec {
        names: &["theme"],
        command: Command::Theme,
        help: "theme <name>",
    },
    Spec {
        names: &["quit", "q", "exit"],
        command: Command::Quit,
        help: "quit bath",
    },
];

pub fn lookup(name: &str) -> Option<Command> {
    COMMANDS
        .iter()
        .find(|s| s.names.contains(&name))
        .map(|s| s.command)
}

pub fn is_command(name: &str) -> bool {
    lookup(name).is_some()
}

pub fn takes_argument(name: &str) -> bool {
    matches!(
        lookup(name),
        Some(Command::Use | Command::Theme | Command::Remove)
    )
}

/// Whether `argument` names something `command` accepts (a profile for
/// `use`, a theme preset for `theme`).
pub fn is_known_argument(app: &AppState, command: &str, argument: &str) -> bool {
    match lookup(command) {
        Some(Command::Use) => app.profiles.iter().any(|p| p.name == argument),
        Some(Command::Theme) => daisyui_themes::get(argument).is_some(),
        Some(Command::Remove) => app.parse_env().vars.iter().any(|v| v.name == argument),
        _ => false,
    }
}

pub const MAX_VISIBLE_SUGGESTIONS: usize = 8;

pub fn clamp_selection(selected: usize, len: usize) -> usize {
    selected.min(len.saturating_sub(1))
}

/// Scroll window over `len` suggestions that keeps the selection visible.
/// Returns `(window_start, highlight_row)`.
pub fn suggestion_window(selected: usize, len: usize, visible: usize) -> (usize, usize) {
    if len == 0 || visible == 0 {
        return (0, 0);
    }
    let selected = clamp_selection(selected, len);
    let start = selected
        .saturating_sub(visible - 1)
        .min(len.saturating_sub(visible));
    (start, selected - start)
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Suggestion {
    pub text: String,
    pub help: String,
}

fn argument_suggestions(prefix: &str, query: &str, names: Vec<String>) -> Vec<Suggestion> {
    let q = query.to_lowercase();
    names
        .into_iter()
        .filter(|n| n.to_lowercase().contains(&q))
        .map(|n| Suggestion {
            text: format!("{prefix} {n}"),
            help: String::new(),
        })
        .collect()
}

pub fn suggestions(app: &AppState, input: &str) -> Vec<Suggestion> {
    let input = input.trim_start();
    if let Some((word, rest)) = input.split_once(' ') {
        let names = match lookup(word) {
            Some(Command::Use) => app.profiles.iter().map(|p| p.name.clone()).collect(),
            Some(Command::Theme) => daisyui_themes::names()
                .into_iter()
                .map(str::to_string)
                .collect(),
            Some(Command::Remove) => app.parse_env().vars.into_iter().map(|v| v.name).collect(),
            _ => Vec::new(),
        };
        return argument_suggestions(word, rest.trim(), names);
    }
    let q = input.to_lowercase();
    let matches = |s: &&Spec| q.is_empty() || s.names.iter().any(|n| n.starts_with(&q));
    COMMANDS
        .iter()
        .filter(matches)
        .map(|s| {
            let name = s
                .names
                .iter()
                .find(|n| n.starts_with(&q))
                .unwrap_or(&s.names[0]);
            Suggestion {
                text: name.to_string(),
                help: format!("{:<28}{}", s.names.join(" "), s.help),
            }
        })
        .collect()
}

/// The command line Enter runs: what was typed when it is a complete command,
/// else the highlighted suggestion.
pub fn pick(app: &AppState, input: &str, selected: usize) -> String {
    let typed = input.trim();
    let (word, arg) = typed.split_once(' ').unwrap_or((typed, ""));
    let arg = arg.trim();
    let complete = match (is_command(word), takes_argument(word)) {
        (false, _) => false,
        (true, false) => true,
        (true, true) => arg.is_empty() || is_known_argument(app, word, arg),
    };
    if complete {
        return typed.to_string();
    }
    let list = suggestions(app, typed);
    list.get(clamp_selection(selected, list.len()))
        .map(|s| s.text.clone())
        .unwrap_or_else(|| typed.to_string())
}

fn goto_new_line(app: &mut AppState, tab: Tab) {
    app.tab = tab;
    let Some(buf) = app.buffer_mut(tab) else {
        return;
    };
    buf.append_line("");
}

pub fn execute(app: &mut AppState, line: &str) -> Result<Action> {
    let line = line.trim();
    let (word, arg) = line.split_once(' ').unwrap_or((line, ""));
    let arg = arg.trim();
    let Some(command) = lookup(word) else {
        if !line.is_empty() {
            app.status = format!("unknown command: {word}");
        }
        return Ok(Action::None);
    };
    match command {
        Command::Goto(tab) => app.tab = tab,
        Command::AddVar => goto_new_line(app, Tab::Env),
        Command::AddItem => goto_new_line(app, Tab::Library),
        Command::AddDef => goto_new_line(app, Tab::Defs),
        Command::AddProfile => {
            app.overlay = Some(Overlay::Prompt {
                action: PromptAction::Add,
                input: String::new(),
            });
        }
        Command::Remove => remove(app, arg),
        Command::Use => use_named(app, arg),
        Command::Duplicate => input::open_profile_prompt(app, true),
        Command::Rename => input::open_profile_prompt(app, false),
        Command::Save => input::save_tab(app, app.tab)?,
        Command::Theme => theme(app, arg)?,
        Command::Quit => return Ok(input::request_quit(app)),
    }
    Ok(Action::None)
}

fn remove_named(app: &mut AppState, var: &str) {
    app.tab = Tab::Env;
    if !app.remove_env_var(var) {
        app.status = format!("{var} is not in {}", app.env_title());
        return;
    }
    app.status = format!("removed {var} (Ctrl+S saves, Ctrl+Z undoes)");
}

fn remove(app: &mut AppState, arg: &str) {
    if !arg.is_empty() {
        remove_named(app, arg);
        return;
    }
    match app.tab {
        Tab::Env => {
            let Some(var) = app.env_var_at_cursor() else {
                app.env.delete_line();
                return;
            };
            app.remove_env_var(&var);
            app.status = format!("removed {var} (Ctrl+S saves, Ctrl+Z undoes)");
        }
        Tab::Library | Tab::Defs => {
            if let Some(buf) = app.buffer_mut(app.tab) {
                buf.delete_line();
            }
        }
        Tab::Profiles => input::confirm_delete_profile(app),
        _ => app.status = "nothing to remove here".to_string(),
    }
}

fn use_named(app: &mut AppState, name: &str) {
    let Some(index) = app.profiles.iter().position(|p| p.name == name) else {
        app.status = format!("profile not found: {name}");
        return;
    };
    input::use_profile_checked(app, index);
}

fn theme(app: &mut AppState, name: &str) -> Result<()> {
    if name.is_empty() {
        app.status = format!(
            "theme <name>: {} themes, current {}",
            daisyui_themes::THEMES.len(),
            app.theme_preset
        );
        return Ok(());
    }
    if !app.set_theme_preset(name, true)? {
        app.status = format!("theme not found: {name}");
        return Ok(());
    }
    app.status = format!("theme: {}", app.theme.name);
    Ok(())
}

pub fn open_palette(app: &mut AppState) {
    app.completion = None;
    app.overlay = Some(Overlay::Palette {
        input: String::new(),
        selected: 0,
    });
}

pub fn confirm(app: &mut AppState, message: String, action: ConfirmAction) {
    app.overlay = Some(Overlay::Confirm { message, action });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui::state::tests::test_app;

    #[test]
    fn aliases_resolve_to_the_same_command() {
        for name in ["add-var", "new-var", "av"] {
            assert_eq!(lookup(name), Some(Command::AddVar));
        }
        for name in ["add-item", "new-item", "ai"] {
            assert_eq!(lookup(name), Some(Command::AddItem));
        }
        for name in ["rm", "del"] {
            assert_eq!(lookup(name), Some(Command::Remove));
        }
        for name in ["use", "switch"] {
            assert_eq!(lookup(name), Some(Command::Use));
        }
        for name in ["q", "quit", "exit"] {
            assert_eq!(lookup(name), Some(Command::Quit));
        }
    }

    #[test]
    fn no_alias_is_listed_twice() {
        let mut names: Vec<&str> = COMMANDS
            .iter()
            .flat_map(|s| s.names.iter().copied())
            .collect();
        let total = names.len();
        names.sort();
        names.dedup();
        assert_eq!(names.len(), total);
    }

    #[test]
    fn suggestions_match_aliases_and_arguments() {
        let app = test_app(&["work", "home"]);
        let texts: Vec<String> = suggestions(&app, "new")
            .into_iter()
            .map(|s| s.text)
            .collect();
        assert!(texts.contains(&"new-var".to_string()));
        assert!(texts.contains(&"new-item".to_string()));
        let texts: Vec<String> = suggestions(&app, "switch h")
            .into_iter()
            .map(|s| s.text)
            .collect();
        assert_eq!(texts, vec!["switch home".to_string()]);
    }

    #[test]
    fn pick_prefers_typed_complete_commands() {
        let app = test_app(&["work"]);
        assert_eq!(pick(&app, "q", 0), "q");
        assert_eq!(pick(&app, "use work", 0), "use work");
        assert_eq!(pick(&app, "use wo", 0), "use work");
        assert_eq!(pick(&app, "lib", 0), "lib");
        assert_eq!(pick(&app, "libr", 0), "library");
    }

    #[test]
    fn add_var_appends_a_line_in_env() -> Result<()> {
        let mut app = test_app(&["work"]);
        app.env.insert_str("CC = clang");
        app.tab = Tab::Help;
        execute(&mut app, "av")?;
        assert_eq!(app.tab, Tab::Env);
        assert_eq!(app.env.lines(), &["CC = clang", ""]);
        assert_eq!(app.env.row, 1);
        Ok(())
    }

    #[test]
    fn rm_with_name_removes_the_var() -> Result<()> {
        let mut app = test_app(&["work"]);
        app.env.insert_str("PATH = /a\n  /b\nCC = clang");
        execute(&mut app, "del PATH")?;
        assert_eq!(app.env.lines(), &["CC = clang"]);
        Ok(())
    }

    #[test]
    fn clamp_selection_clamps_to_last_index_and_zero_when_empty() {
        assert_eq!(clamp_selection(0, 14), 0);
        assert_eq!(clamp_selection(20, 14), 13);
        assert_eq!(clamp_selection(5, 0), 0);
    }

    #[test]
    fn suggestion_window_start_plus_row_is_the_clamped_selection() {
        for len in 1..20usize {
            for sel in 0..25usize {
                for vis in 1..10usize {
                    let (start, row) = suggestion_window(sel, len, vis);
                    assert_eq!(start + row, clamp_selection(sel, len));
                    assert!(row < vis);
                    assert!(start + vis.min(len) <= len);
                }
            }
        }
    }
}