bath 0.4.1

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
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
use crate::config::{Entry, PathEntry, VarKind};
use crate::export::{self, OperationMode};
use crate::tui::util::{centered_rect, is_ctrl_c, next_key_press};
use anyhow::Result;
use crossterm::event::{KeyCode, KeyModifiers};
use ratatui::{
    backend::Backend,
    layout::{Constraint, Direction, Layout},
    style::{Color, Style},
    widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
    Terminal,
};

fn is_path_part(opt: &crate::tui::state::VarTypeOption) -> bool {
    opt.editor == crate::tui::state::EditorStyle::PathPart
}

#[allow(dead_code)]
pub fn edit_var_parts_dialog<B: Backend>(
    terminal: &mut Terminal<B>,
    var: &crate::tui::state::VarTypeOption,
    initial_parts: &[Entry],
) -> Result<Option<Vec<Entry>>> {
    let mut parts: Vec<Entry> = initial_parts.to_vec();
    let mut selected: usize = 0;

    loop {
        terminal.draw(|f| {
            let size = f.size();
            let area = centered_rect(85, 70, size);
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Min(0), Constraint::Length(2)].as_ref())
                .split(area);

            let items: Vec<ListItem> = if parts.is_empty() {
                vec![ListItem::new("(no parts)")]
            } else {
                parts.iter().map(|e| ListItem::new(e.to_string())).collect()
            };
            let mut list_state = ListState::default();
            if !parts.is_empty() {
                list_state.select(Some(selected.min(parts.len().saturating_sub(1))));
            }

            let title = format!(
                "{} parts (a:add, e:edit, d:delete, J/K:move, Enter:save, Esc:cancel)",
                var.name
            );
            let list = List::new(items)
                .block(Block::default().borders(Borders::ALL).title(title))
                .highlight_style(Style::default().bg(Color::Blue));
            f.render_stateful_widget(list, chunks[0], &mut list_state);

            let hint = Paragraph::new(format!(
                "Export preview uses separator '{}' and produces one export line.",
                var.separator
            ))
            .block(Block::default().borders(Borders::ALL));
            f.render_widget(hint, chunks[1]);
        })?;

        if let Some(key) = next_key_press(std::time::Duration::from_millis(100))? {
            // Ctrl+C cancels like Esc so the global quit chord is never dead here.
            if is_ctrl_c(&key) {
                return Ok(None);
            }
            match key.code {
                KeyCode::Esc => return Ok(None),
                KeyCode::Enter => return Ok(Some(parts)),
                KeyCode::Up => {
                    selected = selected.saturating_sub(1);
                }
                KeyCode::Down => {
                    if selected + 1 < parts.len() {
                        selected += 1;
                    }
                }
                KeyCode::Char('K') => {
                    if selected > 0 && selected < parts.len() {
                        parts.swap(selected - 1, selected);
                        selected = selected.saturating_sub(1);
                    }
                }
                KeyCode::Char('J') => {
                    if selected + 1 < parts.len() {
                        parts.swap(selected, selected + 1);
                        selected += 1;
                    }
                }
                KeyCode::Char('d') => {
                    if selected < parts.len() {
                        parts.remove(selected);
                        if selected >= parts.len() && selected > 0 {
                            selected = selected.saturating_sub(1);
                        }
                    }
                }
                KeyCode::Char('a') => {
                    let one = vec![var.clone()];
                    if let Some(new_entry) = edit_env_var_dialog(terminal, &one, None)? {
                        parts.push(new_entry);
                        selected = parts.len().saturating_sub(1);
                    }
                }
                KeyCode::Char('e') if selected < parts.len() => {
                    let one = vec![var.clone()];
                    let current = parts.get(selected);
                    if let Some(new_entry) = edit_env_var_dialog(terminal, &one, current)? {
                        parts[selected] = new_entry;
                    }
                }
                _ => {}
            }
        }
    }
}

#[derive(PartialEq, Debug, Clone, Copy, Default)]
pub enum FocusArea {
    #[default]
    Search,
    Options,
    Input,
}

#[derive(Default)]
pub struct EnvVarEditorState {
    pub all_options: Vec<crate::tui::state::VarTypeOption>,
    pub search: String,
    pub filtered: Vec<crate::tui::state::VarTypeOption>,
    pub selected: usize,
    pub input: String,
    pub path: String,
    pub version: String,
    pub tool: String,
    pub active_input_field: usize,
    pub focus: FocusArea,
    /// In-dialog message shown when a save attempt was rejected.
    pub hint: Option<String>,
    last_search: String,
}

impl EnvVarEditorState {
    pub fn new(options: &[crate::tui::state::VarTypeOption], initial: Option<&Entry>) -> Self {
        let mut s = Self {
            all_options: options.to_vec(),
            search: String::new(),
            filtered: options.to_vec(),
            selected: 0,
            input: String::new(),
            path: String::new(),
            version: String::new(),
            tool: String::new(),
            active_input_field: 0,
            // New entries start on the value/path field so typed text lands
            // in the value instead of the search box (F15).
            focus: FocusArea::Input,
            hint: None,
            last_search: String::new(),
        };

        if let Some(e) = initial {
            let initial_name = e.var_name().into_owned();
            if let Some(pos) = s.all_options.iter().position(|o| o.name == initial_name) {
                s.selected = pos;
            }
            match e {
                Entry::Path(pe) => {
                    s.path = pe.path.clone();
                    s.version = pe.version.clone();
                    s.tool = pe.program.clone();
                    s.focus = FocusArea::Input;
                }
                Entry::CPath(v)
                | Entry::CInclude(v)
                | Entry::CPlusInclude(v)
                | Entry::OBJCInclude(v)
                | Entry::CPPFlag(v)
                | Entry::CFlag(v)
                | Entry::CXXFlag(v)
                | Entry::LDFlag(v)
                | Entry::LibraryPath(v)
                | Entry::LDLibraryPath(v)
                | Entry::LDRunPath(v)
                | Entry::RanLib(v)
                | Entry::CC(v)
                | Entry::CXX(v)
                | Entry::AR(v)
                | Entry::Strip(v)
                | Entry::GCCExecPrefix(v)
                | Entry::CollectGCCOptions(v)
                | Entry::Lang(v) => {
                    s.input = v.clone();
                    s.focus = FocusArea::Input;
                }
                Entry::CustomScalar { value, .. } | Entry::CustomPart { value, .. } => {
                    s.input = value.clone();
                    s.focus = FocusArea::Input;
                }
            }
        }

        s
    }

    pub fn update_filter(&mut self) {
        if self.search == self.last_search {
            return;
        }
        self.last_search = self.search.clone();
        self.filtered = self
            .all_options
            .iter()
            .filter(|opt| {
                opt.name
                    .to_lowercase()
                    .contains(&self.search.to_lowercase())
            })
            .cloned()
            .collect();
        if self.filtered.is_empty() {
            self.filtered = self.all_options.clone();
        }
        self.selected = 0;
    }

    /// Builds the entry to save on Enter, or records a `hint` and returns
    /// `None` when saving must be rejected.
    pub fn try_build_entry(&mut self) -> Option<Entry> {
        let opt = match self.filtered.get(self.selected) {
            Some(opt) => opt.clone(),
            None => {
                self.hint = Some("no variable type selected".to_string());
                return None;
            }
        };
        // Never save an empty part: an empty PATH segment means the current
        // directory in POSIX shells (F15).
        let value_is_empty = if is_path_part(&opt) {
            self.path.trim().is_empty()
        } else {
            self.input.trim().is_empty()
        };
        if value_is_empty {
            self.hint = Some("value must not be empty".to_string());
            return None;
        }
        Some(entry_from_state(&opt, self))
    }
}

fn entry_from_state(opt: &crate::tui::state::VarTypeOption, state: &EnvVarEditorState) -> Entry {
    if is_path_part(opt) {
        return Entry::Path(PathEntry {
            path: state.path.clone(),
            version: state.version.clone(),
            program: state.tool.clone(),
        });
    }

    // Builtins
    match opt.name.as_str() {
        "CPATH" => return Entry::CPath(state.input.clone()),
        "C_INCLUDE_PATH" => return Entry::CInclude(state.input.clone()),
        "CPLUS_INCLUDE_PATH" => return Entry::CPlusInclude(state.input.clone()),
        "OBJC_INCLUDE_PATH" => return Entry::OBJCInclude(state.input.clone()),
        "CPPFLAGS" => return Entry::CPPFlag(state.input.clone()),
        "CFLAGS" => return Entry::CFlag(state.input.clone()),
        "CXXFLAGS" => return Entry::CXXFlag(state.input.clone()),
        "LDFLAGS" => return Entry::LDFlag(state.input.clone()),
        "LIBRARY_PATH" => return Entry::LibraryPath(state.input.clone()),
        "LD_LIBRARY_PATH" => return Entry::LDLibraryPath(state.input.clone()),
        "LD_RUN_PATH" => return Entry::LDRunPath(state.input.clone()),
        "RANLIB" => return Entry::RanLib(state.input.clone()),
        "CC" => return Entry::CC(state.input.clone()),
        "CXX" => return Entry::CXX(state.input.clone()),
        "AR" => return Entry::AR(state.input.clone()),
        "STRIP" => return Entry::Strip(state.input.clone()),
        "GCC_EXEC_PREFIX" => return Entry::GCCExecPrefix(state.input.clone()),
        "COLLECT_GCC_OPTIONS" => return Entry::CollectGCCOptions(state.input.clone()),
        "LANG" => return Entry::Lang(state.input.clone()),
        _ => {}
    }

    // Custom vars
    match opt.kind {
        VarKind::Scalar => Entry::CustomScalar {
            name: opt.name.clone(),
            value: state.input.clone(),
        },
        VarKind::List => Entry::CustomPart {
            name: opt.name.clone(),
            value: state.input.clone(),
            separator: opt.separator.clone(),
        },
    }
}

/// Launches the edit/create env var widget.
/// Displays fuzzy search on the left and input fields on the right,
/// with an integrated preview (using default Prepend mode) of the export command for the current variable.
pub fn edit_env_var_dialog<B: Backend>(
    terminal: &mut Terminal<B>,
    options: &[crate::tui::state::VarTypeOption],
    initial: Option<&Entry>,
) -> Result<Option<Entry>> {
    let mut state = EnvVarEditorState::new(options, initial);

    loop {
        terminal.draw(|f| {
            let size = f.size();
            // Split into left (40%) for fuzzy search and right (60%) for input and preview.
            let chunks = Layout::default()
                .direction(Direction::Horizontal)
                .constraints([Constraint::Percentage(40), Constraint::Percentage(60)].as_ref())
                .split(centered_rect(80, 60, size));

            // Left pane: fuzzy search and options.
            let left_chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Length(3), Constraint::Min(0)].as_ref())
                .split(chunks[0]);

            let search_style = if state.focus == FocusArea::Search {
                Style::default().fg(Color::Yellow)
            } else {
                Style::default()
            };
            let search_para = Paragraph::new(state.search.as_ref()).block(
                Block::default()
                    .borders(Borders::ALL)
                    .style(search_style)
                    .title("Search Type"),
            );
            f.render_widget(search_para, left_chunks[0]);

            state.update_filter();
            let items: Vec<ListItem> = state
                .filtered
                .iter()
                .map(|opt| ListItem::new(opt.name.clone()))
                .collect();
            let mut list_state = ListState::default();
            list_state.select(Some(state.selected));
            let list = List::new(items)
                .block(Block::default().borders(Borders::ALL).title("Options"))
                .highlight_style(Style::default().bg(Color::Blue));
            f.render_stateful_widget(list, left_chunks[1], &mut list_state);

            // Right pane: input fields and preview.
            let right_chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Length(7), Constraint::Min(0)].as_ref())
                .split(chunks[1]);

            let input_style = if state.focus == FocusArea::Input {
                Style::default().fg(Color::Yellow)
            } else {
                Style::default()
            };

            if state
                .filtered
                .get(state.selected)
                .map(is_path_part)
                .unwrap_or(false)
            {
                // Multi-field input for types like PATH.
                let field_titles = ["Path", "Version", "Tool Name"];
                let values = [
                    state.path.clone(),
                    state.version.clone(),
                    state.tool.clone(),
                ];
                let field_items: Vec<ListItem> = field_titles
                    .iter()
                    .enumerate()
                    .map(|(i, title)| {
                        let indicator =
                            if state.focus == FocusArea::Input && state.active_input_field == i {
                                "> "
                            } else {
                                "  "
                            };
                        ListItem::new(format!("{}{}: {}", indicator, title, values[i]))
                    })
                    .collect();
                let title = match &state.hint {
                    Some(h) => format!("Multi-field Input ({h})"),
                    None => "Multi-field Input".to_string(),
                };
                let fields_list = List::new(field_items).block(
                    Block::default()
                        .borders(Borders::ALL)
                        .style(input_style)
                        .title(title),
                );
                f.render_widget(fields_list, right_chunks[0]);
            } else {
                // Single-field input.
                let current_type = state
                    .filtered
                    .get(state.selected)
                    .map(|opt| opt.name.clone())
                    .unwrap_or_else(|| "...".to_string());
                let title = match &state.hint {
                    Some(h) => format!("Enter value for {current_type} ({h})"),
                    None => format!("Enter value for {current_type}"),
                };
                let para = Paragraph::new(state.input.as_ref()).block(
                    Block::default()
                        .borders(Borders::ALL)
                        .style(input_style)
                        .title(title),
                );
                f.render_widget(para, right_chunks[0]);
            }

            // Bottom right: preview of export command for the current variable.
            let preview = if state
                .filtered
                .get(state.selected)
                .map(is_path_part)
                .unwrap_or(false)
            {
                let pe = PathEntry {
                    path: state.path.clone(),
                    version: state.version.clone(),
                    program: state.tool.clone(),
                };
                let entry = Entry::Path(pe);
                export::generate_export_line(&entry, OperationMode::Prepend)
            } else {
                let opt = state
                    .filtered
                    .get(state.selected)
                    .cloned()
                    .unwrap_or_else(|| crate::tui::state::VarTypeOption {
                        name: "CFLAGS".to_string(),
                        kind: VarKind::List,
                        separator: " ".to_string(),
                        editor: crate::tui::state::EditorStyle::Single,
                    });
                let entry = entry_from_state(&opt, &state);
                export::generate_export_line(&entry, OperationMode::Prepend)
            };
            let preview_para = Paragraph::new(preview).block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("Export Preview for this Variable"),
            );
            f.render_widget(preview_para, right_chunks[1]);
        })?;

        if let Some(key) = next_key_press(std::time::Duration::from_millis(100))? {
            // Ctrl+C cancels like Esc so the global quit chord is never dead here.
            if is_ctrl_c(&key) {
                return Ok(None);
            }
            state.hint = None;
            match key.code {
                KeyCode::Esc => return Ok(None),
                KeyCode::Enter => {
                    if let Some(entry) = state.try_build_entry() {
                        return Ok(Some(entry));
                    }
                }
                KeyCode::Tab => {
                    // Cycle focus among Search -> Options -> Input.
                    state.focus = match state.focus {
                        FocusArea::Search => FocusArea::Options,
                        FocusArea::Options => FocusArea::Input,
                        FocusArea::Input => FocusArea::Search,
                    };
                }
                KeyCode::Backspace => match state.focus {
                    FocusArea::Search => {
                        state.search.pop();
                        state.update_filter();
                    }
                    FocusArea::Options => {}
                    FocusArea::Input => {
                        if state
                            .filtered
                            .get(state.selected)
                            .map(is_path_part)
                            .unwrap_or(false)
                        {
                            match state.active_input_field {
                                0 => {
                                    state.path.pop();
                                }
                                1 => {
                                    state.version.pop();
                                }
                                2 => {
                                    state.tool.pop();
                                }
                                _ => {}
                            }
                        } else {
                            state.input.pop();
                        }
                    }
                },
                KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                    match state.focus {
                        FocusArea::Search => {
                            state.search.push(c);
                            state.update_filter();
                        }
                        FocusArea::Options => {}
                        FocusArea::Input => {
                            if state
                                .filtered
                                .get(state.selected)
                                .map(is_path_part)
                                .unwrap_or(false)
                            {
                                match state.active_input_field {
                                    0 => state.path.push(c),
                                    1 => state.version.push(c),
                                    2 => state.tool.push(c),
                                    _ => {}
                                }
                            } else {
                                state.input.push(c);
                            }
                        }
                    }
                }
                KeyCode::Up => match state.focus {
                    FocusArea::Options => {
                        if state.selected > 0 {
                            state.selected -= 1;
                        }
                    }
                    FocusArea::Input
                        if state
                            .filtered
                            .get(state.selected)
                            .map(is_path_part)
                            .unwrap_or(false)
                            && state.active_input_field > 0 =>
                    {
                        state.active_input_field -= 1;
                    }
                    _ => {}
                },
                KeyCode::Down => match state.focus {
                    FocusArea::Options => {
                        if state.selected < state.filtered.len().saturating_sub(1) {
                            state.selected += 1;
                        }
                    }
                    FocusArea::Input
                        if state
                            .filtered
                            .get(state.selected)
                            .map(is_path_part)
                            .unwrap_or(false)
                            && state.active_input_field < 2 =>
                    {
                        state.active_input_field += 1;
                    }
                    _ => {}
                },
                _ => {}
            }
        }
    }
}

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

    #[test]
    fn update_filter_does_not_reset_selected_when_search_is_unchanged() {
        let options = crate::tui::state::builtin_var_options();
        let mut s = EnvVarEditorState::new(&options, None);

        // Force one filter refresh.
        s.search.push('c');
        s.update_filter();
        assert!(
            s.filtered.len() > 2,
            "expected enough options for selection test"
        );

        // Simulate user moving selection in the options list.
        s.selected = 2;

        // Subsequent draws call update_filter again; selection must not be reset.
        s.update_filter();
        assert_eq!(s.selected, 2);
    }

    // F15: a dialog opened for a NEW entry must start on the value/path
    // field, not the search box, so typed text lands in the value.
    #[test]
    fn new_entry_dialog_starts_focused_on_input() {
        let options = crate::tui::state::builtin_var_options();
        let s = EnvVarEditorState::new(&options, None);
        assert_eq!(s.focus, FocusArea::Input);
    }

    // F15: Enter must not save an empty path part; an empty PATH segment
    // means the current directory in POSIX shells.
    #[test]
    fn try_build_entry_rejects_empty_path_part() {
        let options = crate::tui::state::builtin_var_options();
        let mut s = EnvVarEditorState::new(&options, None);
        assert_eq!(s.filtered[s.selected].name, "PATH");
        assert!(s.path.is_empty());
        assert!(s.try_build_entry().is_none());
        assert!(s.hint.is_some());
    }

    // F15: whitespace-only values are rejected like empty ones.
    #[test]
    fn try_build_entry_rejects_whitespace_only_value() {
        let options = crate::tui::state::builtin_var_options();
        let mut s = EnvVarEditorState::new(&options, None);
        let cpath = s.filtered.iter().position(|o| o.name == "CPATH").unwrap();
        s.selected = cpath;
        s.input = "   ".to_string();
        assert!(s.try_build_entry().is_none());
        assert!(s.hint.is_some());
    }

    #[test]
    fn try_build_entry_saves_non_empty_value() {
        let options = crate::tui::state::builtin_var_options();
        let mut s = EnvVarEditorState::new(&options, None);
        let cpath = s.filtered.iter().position(|o| o.name == "CPATH").unwrap();
        s.selected = cpath;
        s.input = "/opt/include".to_string();
        match s.try_build_entry() {
            Some(Entry::CPath(v)) => assert_eq!(v, "/opt/include"),
            other => panic!("expected CPath entry, got {other:?}"),
        }
    }
}