bath 0.4.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
// src/export.rs

use crate::config::{Entry, EnvProfile};
use crate::db;
use anyhow::Result;
use std::collections::HashMap;

#[derive(Clone, Copy)]
pub enum OperationMode {
    Prepend,
    Append,
    Replace,
}

fn shell_double_quote_literal(s: &str) -> String {
    // Escape for inside double quotes.
    //
    // Intentionally does NOT escape '$' so things like $HOME and ${VAR}
    // expand at eval-time as requested.
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            _ => out.push(ch),
        }
    }
    out
}

fn export_assignment(var_name: &str, value: &str, sep: &str, mode: OperationMode) -> String {
    let escaped_value = shell_double_quote_literal(value);
    match mode {
        OperationMode::Prepend => {
            // Only insert the separator + existing var if it is non-empty:
            // VAR="<new>${VAR:+<sep>}${VAR}"
            //
            // This is functionally equivalent to `${VAR:+<sep>${VAR}}` but reads clearer.
            let tail = format!("${{{}:+{}}}${{{}}}", var_name, sep, var_name);
            format!("export {}=\"{}{}\";", var_name, escaped_value, tail)
        }
        OperationMode::Append => {
            // Only insert the existing var + separator if it is non-empty:
            // VAR="${VAR:+${VAR}<sep>}<new>"
            let head = format!("${{{}:+${{{}}}{}}}", var_name, var_name, sep);
            format!("export {}=\"{}{}\";", var_name, head, escaped_value)
        }
        OperationMode::Replace => format!("export {}=\"{}\";", var_name, escaped_value),
    }
}

fn entry_value(entry: &Entry) -> String {
    match entry {
        Entry::Path(pe) => pe.path.clone(),
        Entry::CPath(s)
        | Entry::CInclude(s)
        | Entry::CPlusInclude(s)
        | Entry::OBJCInclude(s)
        | Entry::CPPFlag(s)
        | Entry::CFlag(s)
        | Entry::CXXFlag(s)
        | Entry::LDFlag(s)
        | Entry::LibraryPath(s)
        | Entry::LDLibraryPath(s)
        | Entry::LDRunPath(s)
        | Entry::RanLib(s)
        | Entry::CC(s)
        | Entry::CXX(s)
        | Entry::AR(s)
        | Entry::Strip(s)
        | Entry::GCCExecPrefix(s)
        | Entry::CollectGCCOptions(s)
        | Entry::Lang(s) => s.clone(),
        Entry::CustomScalar { value, .. } => value.clone(),
        Entry::CustomPart { value, .. } => value.clone(),
    }
}

/// Generates an export command for a single Entry (treated as the new value).
pub fn generate_export_line(entry: &Entry, mode: OperationMode) -> String {
    let var_name = entry.var_name();
    let value = entry_value(entry);
    let sep = entry.separator();
    export_assignment(var_name.as_ref(), &value, sep.as_ref(), mode)
}

/// Resolves the separator used to join a var's parts into its final value:
/// the first stored entry's separator, falling back to `fallback` (typically
/// the var def's separator) only when the var has no parts yet.
///
/// The Preview pane and export must share this resolution so the preview
/// always predicts exactly what export emits, even when a def's separator
/// was edited after entries were stored.
pub fn join_separator(parts: &[Entry], fallback: &str) -> String {
    parts
        .first()
        .map(|e| e.separator().into_owned())
        .unwrap_or_else(|| fallback.to_string())
}

/// Generates the full export commands for a given profile.
pub fn generate_full_export(profile: &EnvProfile, mode: OperationMode) -> String {
    // One export line per variable, with parts joined in the order they were added.
    //
    // This keeps editing at the parts level in storage/UI, but export happens at the
    // variable level (e.g. one PATH assignment).
    let mut order: Vec<String> = Vec::new();
    let mut groups: HashMap<String, Vec<Entry>> = HashMap::new();

    for entry in &profile.entries {
        let var = entry.var_name().into_owned();
        if !groups.contains_key(&var) {
            order.push(var.clone());
        }
        groups.entry(var).or_default().push(entry.clone());
    }

    let mut lines = Vec::new();
    for var in order {
        if let Some(parts) = groups.remove(&var) {
            let sep = join_separator(&parts, ":");
            let joined = parts.iter().map(entry_value).collect::<Vec<_>>().join(&sep);
            lines.push(export_assignment(&var, &joined, &sep, mode));
        }
    }
    lines.join("\n")
}

/// Exports the given profile as export commands (without a shebang)
/// so you can eval the commands in your shell.
pub fn export_profile(profile_name: &str, mode: OperationMode) -> Result<()> {
    let conn = db::establish_connection()?;
    let profile: EnvProfile = db::load_profile(&conn, profile_name)?;
    let out = generate_full_export(&profile, mode);
    if !out.is_empty() {
        println!("{out}");
    }
    Ok(())
}

type ExportTerminal = ratatui::Terminal<ratatui::backend::CrosstermBackend<std::io::Stdout>>;

/// Event loop of the export picker: draws the profile list and reads keys
/// through the shared press-only helper (`tui::util::next_key_press`), so
/// release/repeat events are dropped like in every other event loop.
/// Returns the picked profile index, or `None` when cancelled (Esc/Ctrl+C).
fn run_export_picker(
    terminal: &mut ExportTerminal,
    profiles: &[EnvProfile],
) -> Result<Option<usize>> {
    use crossterm::event::KeyCode;
    use ratatui::layout::{Constraint, Direction, Layout};
    use ratatui::style::Style;
    use ratatui::widgets::{Block, Borders, List, ListItem, ListState};

    let mut list_state = ListState::default();
    list_state.select(Some(0));
    let items: Vec<ListItem> = profiles
        .iter()
        .map(|p| ListItem::new(p.name.clone()))
        .collect();

    loop {
        terminal.draw(|f| {
            let size = f.size();
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Length(3), Constraint::Min(0)].as_ref())
                .split(size);
            let block = Block::default()
                .borders(Borders::ALL)
                .title("Select a profile to export (Enter: select, Esc: cancel)");
            let list = List::new(items.clone())
                .block(block)
                .highlight_style(Style::default().bg(ratatui::style::Color::Blue));
            f.render_stateful_widget(list, chunks[1], &mut list_state);
        })?;

        if let Some(key) = crate::tui::util::next_key_press(std::time::Duration::from_millis(200))?
        {
            // Ctrl+C cancels like Esc so the global quit chord is never dead here.
            if crate::tui::util::is_ctrl_c(&key) {
                return Ok(None);
            }
            match key.code {
                KeyCode::Esc => return Ok(None),
                KeyCode::Down => {
                    let i = match list_state.selected() {
                        Some(i) if i >= profiles.len() - 1 => 0,
                        Some(i) => i + 1,
                        None => 0,
                    };
                    list_state.select(Some(i));
                }
                KeyCode::Up => {
                    let i = match list_state.selected() {
                        Some(0) | None => profiles.len() - 1,
                        Some(i) => i - 1,
                    };
                    list_state.select(Some(i));
                }
                KeyCode::Enter => {
                    if let Some(i) = list_state.selected() {
                        return Ok(Some(i));
                    }
                }
                _ => {}
            }
        }
    }
}

/// Best-effort terminal restore for the export picker: every step is
/// attempted even when an earlier one fails, and the first error is reported
/// afterwards (same pattern as `tui::app::restore_terminal`).
fn restore_export_terminal(terminal: &mut ExportTerminal) -> Result<()> {
    use crossterm::execute;
    use crossterm::terminal::{disable_raw_mode, LeaveAlternateScreen};

    let raw = disable_raw_mode();
    let screen = execute!(terminal.backend_mut(), LeaveAlternateScreen);
    let cursor = terminal.show_cursor();
    raw?;
    screen?;
    cursor?;
    Ok(())
}

/// Launches an interactive ratatui TUI to select a profile to export.
/// When a profile is selected, its export commands (according to the given mode)
/// are printed to stdout.
pub fn interactive_export(mode: OperationMode) -> Result<()> {
    use crossterm::execute;
    use crossterm::terminal::{
        disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
    };
    use ratatui::backend::CrosstermBackend;
    use ratatui::Terminal;
    use std::io::stdout;

    let conn = db::establish_connection()?;
    let profiles = db::load_all_profiles(&conn)?;
    if profiles.is_empty() {
        println!("No profiles available to export.");
        return Ok(());
    }

    enable_raw_mode()?;
    let mut out = stdout();
    // Between enable_raw_mode succeeding and the guarded picker below, an Err
    // propagating via `?` would leave raw mode (and possibly the alternate
    // screen) behind. Restore explicitly instead, same as tui::app::run.
    if let Err(e) = execute!(out, EnterAlternateScreen) {
        let _ = disable_raw_mode();
        let _ = execute!(stdout(), LeaveAlternateScreen);
        return Err(e.into());
    }
    let backend = CrosstermBackend::new(out);
    let mut terminal = match Terminal::new(backend) {
        Ok(terminal) => terminal,
        Err(e) => {
            let _ = disable_raw_mode();
            let _ = execute!(stdout(), LeaveAlternateScreen);
            return Err(e.into());
        }
    };

    // Run the picker and always restore the terminal afterwards, even when
    // the picker returned an error.
    let picked = run_export_picker(&mut terminal, &profiles);
    let restored = restore_export_terminal(&mut terminal);
    let picked = picked?;
    restored?;

    // Print only after the alternate screen is left, so the output lands in
    // the caller's scrollback instead of being wiped with the TUI.
    if let Some(i) = picked {
        export_profile(&profiles[i].name, mode)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Entry, PathEntry};

    #[test]
    fn replace_mode_uses_double_quotes_and_escapes_inner_double_quotes() {
        let e = Entry::CC("O\"Reilly".to_string());
        assert_eq!(
            generate_export_line(&e, OperationMode::Replace),
            "export CC=\"O\\\"Reilly\";"
        );
    }

    #[test]
    fn replace_mode_allows_shell_expansion_of_dollar_vars() {
        let e = Entry::CC("/opt/$HOME/bin".to_string());
        assert_eq!(
            generate_export_line(&e, OperationMode::Replace),
            "export CC=\"/opt/$HOME/bin\";"
        );
    }

    #[test]
    fn prepend_mode_generates_single_export_per_var_with_all_parts_in_order() {
        let profile = EnvProfile {
            name: "p".to_string(),
            entries: vec![
                Entry::Path(PathEntry {
                    path: "/p1".to_string(),
                    program: "tool".to_string(),
                    version: "1".to_string(),
                }),
                Entry::Path(PathEntry {
                    path: "/p2".to_string(),
                    program: "tool".to_string(),
                    version: "2".to_string(),
                }),
                Entry::CFlag("-O2 -Wall".to_string()),
            ],
        };

        let out = generate_full_export(&profile, OperationMode::Prepend);

        let path_lines: Vec<&str> = out
            .lines()
            .filter(|l| l.starts_with("export PATH="))
            .collect();
        assert_eq!(path_lines.len(), 1, "expected a single PATH export line");
        assert_eq!(path_lines[0], "export PATH=\"/p1:/p2${PATH:+:}${PATH}\";");

        let cflag_lines: Vec<&str> = out
            .lines()
            .filter(|l| l.starts_with("export CFLAGS="))
            .collect();
        assert_eq!(cflag_lines.len(), 1, "expected a single CFLAGS export line");
        assert_eq!(
            cflag_lines[0],
            "export CFLAGS=\"-O2 -Wall${CFLAGS:+ }${CFLAGS}\";"
        );
    }

    #[test]
    fn append_mode_uses_parameter_expansion_to_avoid_leading_separators() {
        let profile = EnvProfile {
            name: "p".to_string(),
            entries: vec![
                Entry::Path(PathEntry {
                    path: "/p1".to_string(),
                    program: "tool".to_string(),
                    version: "1".to_string(),
                }),
                Entry::Path(PathEntry {
                    path: "/p2".to_string(),
                    program: "tool".to_string(),
                    version: "2".to_string(),
                }),
            ],
        };

        let out = generate_full_export(&profile, OperationMode::Append);
        let path_lines: Vec<&str> = out
            .lines()
            .filter(|l| l.starts_with("export PATH="))
            .collect();
        assert_eq!(path_lines.len(), 1, "expected a single PATH export line");
        assert_eq!(path_lines[0], "export PATH=\"${PATH:+${PATH}:}/p1:/p2\";");
    }

    #[test]
    fn join_separator_prefers_stored_entry_separator_over_def_separator() {
        let parts = vec![Entry::CustomPart {
            name: "FOO".to_string(),
            value: "a".to_string(),
            separator: ";".to_string(),
        }];
        assert_eq!(join_separator(&parts, ":"), ";");
        assert_eq!(
            join_separator(&[], ":"),
            ":",
            "with no stored parts, the def separator is the only choice"
        );
    }

    #[test]
    fn preview_join_predicts_export_when_def_and_entry_separators_disagree() {
        // Entries stored with ';' while the (later-edited) def says ':'.
        let entries = vec![
            Entry::CustomPart {
                name: "FOO".to_string(),
                value: "a".to_string(),
                separator: ";".to_string(),
            },
            Entry::CustomPart {
                name: "FOO".to_string(),
                value: "b".to_string(),
                separator: ";".to_string(),
            },
        ];
        let profile = EnvProfile {
            name: "p".to_string(),
            entries: entries.clone(),
        };

        // Mirror the Preview pane's separator resolution (def separator ':'
        // as the fallback): the value it shows must be exactly what export
        // emits.
        let sep = join_separator(&entries, ":");
        let shown = entries
            .iter()
            .map(entry_value)
            .collect::<Vec<_>>()
            .join(&sep);

        let out = generate_full_export(&profile, OperationMode::Replace);
        assert_eq!(out, format!("export FOO=\"{shown}\";"));
    }

    #[test]
    fn statements_end_with_semicolon() {
        let e = Entry::CFlag("-O2 -Wall".to_string());
        let line = generate_export_line(&e, OperationMode::Replace);
        assert!(line.ends_with(';'), "line did not end with ';': {line}");
    }
}