cahier 0.1.3

A terminal session recorder and manager.
Documentation
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
use anyhow::Result;
use reedline::{
    ColumnarMenu, Emacs, FileBackedHistory, History, HistoryItem, KeyCode, KeyModifiers, Reedline,
    ReedlineEvent, ReedlineMenu, SearchDirection, SearchQuery, Signal,
};
use std::collections::HashMap;
use std::io::Write;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use crate::alias;
use crate::command::{self, CommandContext, CommandResult, Registry};
use crate::common::{self, MAX_HISTORY_ENTRIES};
use crate::completion::CahierCompleter;
use crate::config::Config;
use crate::db;
use crate::executor::{self, Job};
use crate::highlighter::SyntectHighlighter;
use crate::prompt::CahierPrompt;

/// Resolves the absolute path to the database
fn resolve_db_path() -> String {
    let db_path = common::db_path();
    let db_path_buf = std::fs::canonicalize(&db_path).unwrap_or(db_path);
    db_path_buf.to_string_lossy().to_string()
}

/// Initializes the Reedline editor with history, completion, keybindings, etc.
fn setup_line_editor(
    config: &Config,
    current_env: Arc<Mutex<HashMap<String, String>>>,
    aliases: Arc<Mutex<HashMap<String, String>>>,
    builtins: Vec<String>,
) -> Result<(Reedline, FileBackedHistory)> {
    let disk_history =
        FileBackedHistory::with_file(MAX_HISTORY_ENTRIES, common::history_path())
            .map_err(|e| anyhow::anyhow!("Error creating history file: {:?}", e))?;
    let mut session_history = FileBackedHistory::new(MAX_HISTORY_ENTRIES);
    let entries = disk_history
        .search(SearchQuery::everything(SearchDirection::Forward, None))
        .map_err(|e| anyhow::anyhow!("Error loading history file: {:?}", e))?;
    for entry in entries {
        let _ = session_history.save(entry);
    }

    let mut keybindings = reedline::default_emacs_keybindings();
    keybindings.add_binding(
        KeyModifiers::from_bits_truncate(0),
        KeyCode::Tab,
        ReedlineEvent::Menu("completion_menu".to_string()),
    );
    let edit_mode = Emacs::new(keybindings);

    let line_editor = Reedline::create()
        .with_history(Box::new(session_history))
        .with_completer(Box::new(CahierCompleter::new(
            current_env,
            aliases,
            builtins,
        )))
        .with_quick_completions(true)
        .with_menu(ReedlineMenu::EngineCompleter(Box::new(
            ColumnarMenu::default().with_name("completion_menu"),
        )))
        .with_edit_mode(Box::new(edit_mode))
        .with_highlighter(Box::new(SyntectHighlighter::new(config.theme.clone())));

    Ok((line_editor, disk_history))
}

/// Processes the input string to handle aliases and the 'nr' prefix
fn process_input(input: &str, aliases: &Arc<Mutex<HashMap<String, String>>>) -> (String, bool) {
    // Expand aliases
    let expanded_input_raw = alias::expand_alias(input, aliases);

    // Check for nr prefix to skip logging
    let trimmed = expanded_input_raw.trim_start();
    if let Some(stripped) = trimmed.strip_prefix("nr ") {
        // If we found 'nr', we need to try expanding aliases again
        // because the command after 'nr' might be an alias
        (alias::expand_alias(stripped, aliases), false)
    } else {
        (expanded_input_raw, true)
    }
}

/// Executes an external command in the PTY
fn execute_external_command(
    input: &str,
    expanded_input: &str,
    should_log: bool,
    context: &mut CommandContext,
    config: &Config,
) -> Result<()> {
    let start = Instant::now();

    // Check if command should have output captured
    // Use the expanded command name for this check
    // Note: If should_log is false (due to 'nr' prefix), we also disable output capture
    // to ensure no persistent record (file or DB) is created.
    let cmd_name = expanded_input.split_whitespace().next().unwrap_or("");
    let is_ignored = config
        .ignored_outputs
        .iter()
        .any(|ignored| ignored == cmd_name);

    if is_ignored {
        context.should_log = false;
    }

    let capture_output = should_log && !is_ignored;

    match executor::execute_in_pty(
        expanded_input,
        context.max_output_size,
        context.pty_writer,
        context.current_env,
        capture_output,
        false,
    ) {
        Ok(res) => {
            println!(); // Add newline between command output and next prompt

            // Log the ORIGINAL input
            if let Err(e) = command::handle_execution_result(res, start, input, context) {
                eprintln!("Error processing execution result: {}", e);
                context.prompt.set_last_success(false);
                context.prompt.set_last_duration(Some(start.elapsed()));
            }
        }
        Err(e) => {
            eprintln!("Execution error: {}", e);
            context.prompt.set_last_success(false);
            context.prompt.set_last_duration(Some(start.elapsed()));
        }
    }
    Ok(())
}

/// Runs the interactive REPL loop
///
/// # Arguments
/// * `db` - Database instance for logging commands
/// * `max_output_size` - Maximum output size before redirecting to file
/// * `pty_writer` - Shared writer for Ctrl+C signal handling
pub fn run_repl(
    db: db::Database,
    max_output_size: usize,
    pty_writer: Arc<Mutex<Option<Box<dyn Write + Send>>>>,
    config: Config,
    initial_command: Option<String>,
) -> Result<()> {
    println!("Cahier started.");

    let db_path_str = resolve_db_path();

    println!("Database: {}", db_path_str);
    println!("Max output size: {} bytes", max_output_size);

    // Resolve absolute path for environment store
    let env_store_path = common::env_store_path();

    // Initialize current environment
    let mut env_map: HashMap<String, String> = std::env::vars().collect();

    if config.restore_env {
        println!("Restoring environment...");
        match crate::env_store::load_env(&env_store_path) {
            Ok(persisted_env) => {
                // Try to restore working directory first
                if let Some(pwd) = persisted_env.get("PWD") {
                    match std::env::set_current_dir(pwd) {
                        Ok(_) => {
                            // Successfully restored, merge all persisted variables
                            for (k, v) in persisted_env {
                                env_map.insert(k, v);
                            }
                        }
                        Err(e) => {
                            eprintln!(
                                "Warning: Failed to restore working directory ({}): {}",
                                pwd, e
                            );
                            // Directory doesn't exist, merge persisted vars but update PWD to current dir
                            for (k, v) in persisted_env {
                                env_map.insert(k, v);
                            }
                            // Update PWD to reflect actual current directory
                            if let Ok(cwd) = std::env::current_dir() {
                                env_map
                                    .insert("PWD".to_string(), cwd.to_string_lossy().to_string());
                            }
                        }
                    }
                } else {
                    // No PWD in persisted env, just merge
                    for (k, v) in persisted_env {
                        env_map.insert(k, v);
                    }
                }
            }
            Err(e) => {
                eprintln!("Failed to load persisted environment: {}", e);
            }
        }
    } else {
        // Ensure PWD in env map matches actual current dir when not restoring
        if let Ok(cwd) = std::env::current_dir() {
            env_map.insert("PWD".to_string(), cwd.to_string_lossy().to_string());
        }
    }

    let current_env: Arc<Mutex<HashMap<String, String>>> = Arc::new(Mutex::new(env_map));

    let mut registry = Registry::new();
    registry.register(Box::new(command::CdCommand));
    registry.register(Box::new(command::JobsCommand));
    registry.register(Box::new(command::ExitCommand));
    registry.register(Box::new(command::FgCommand));
    registry.register(Box::new(command::AliasCommand));
    registry.register(Box::new(command::UnaliasCommand));
    registry.register(Box::new(command::EditCommand));

    // Load aliases from user shell if configured
    let aliases_map = if config.load_aliases {
        println!("Loading aliases...");
        let map = alias::load_aliases_from_shell(Duration::from_secs(2));
        println!("Loaded {} aliases.", map.len());
        map
    } else {
        HashMap::new()
    };
    let aliases = Arc::new(Mutex::new(aliases_map));

    let builtins = registry.command_names();

    let (mut line_editor, mut disk_history) =
        setup_line_editor(&config, current_env.clone(), aliases.clone(), builtins)?;

    let mut prompt = CahierPrompt::new();

    let mut jobs: Vec<Job> = Vec::new();

    // Add initial command to history if provided
    if let Some(cmd) = initial_command {
        let _ = line_editor
            .history_mut()
            .save(HistoryItem::from_command_line(&cmd));
        let (_, should_log) = process_input(&cmd, &aliases);
        if should_log {
            let _ = disk_history.save(HistoryItem::from_command_line(&cmd));
        }
        // Also sync history to disk to ensure it persists
        let _ = disk_history.sync();
        // Try to run edit commands
        line_editor.run_edit_commands(&[reedline::EditCommand::InsertString(cmd)]);
    }

    let mut next_command: Option<String> = None;

    loop {
        let sig = line_editor.read_line(&prompt);
        match sig {
            Ok(Signal::Success(buffer)) => {
                let input = buffer.trim();
                if input.is_empty() {
                    continue;
                }

                let start_total = Instant::now();

                let (expanded_input, should_log) = process_input(input, &aliases);

                if should_log {
                    let _ = disk_history.save(HistoryItem::from_command_line(input));
                }

                // Check for built-in commands
                let args_owned = shlex::split(&expanded_input).unwrap_or_default();
                let args: Vec<&str> = args_owned.iter().map(|s| s.as_str()).collect();

                let mut context = CommandContext {
                    db: &db,
                    current_env: &current_env,
                    jobs: &mut jobs,
                    pty_writer: &pty_writer,
                    max_output_size,
                    prompt: &mut prompt,
                    aliases: &aliases,
                    should_log,
                    db_path: &db_path_str,
                    next_command: &mut next_command,
                };

                if let Some(cmd_name) = args.first() {
                    if let Some(cmd) = registry.get(cmd_name) {
                        match cmd.execute(&args[1..], &mut context) {
                            Ok(CommandResult::Exit) => break,
                            Ok(CommandResult::Continue) => {
                                if config.restore_env {
                                    if let Ok(env) = context.current_env.lock() {
                                        if let Err(e) =
                                            crate::env_store::save_env(&env, &env_store_path)
                                        {
                                            eprintln!("Failed to save environment: {}", e);
                                        }
                                    }
                                }

                                if let Some(cmd) = next_command.take() {
                                    let _ = line_editor
                                        .history_mut()
                                        .save(HistoryItem::from_command_line(&cmd));
                                    let (_, should_log) = process_input(&cmd, &aliases);
                                    if should_log {
                                        let _ =
                                            disk_history.save(HistoryItem::from_command_line(&cmd));
                                    }
                                    let _ = disk_history.sync();
                                    line_editor.run_edit_commands(&[
                                        reedline::EditCommand::InsertString(cmd),
                                    ]);
                                }
                                println!();
                                continue;
                            }
                            Err(e) => {
                                eprintln!("Error executing {}: {}", cmd_name, e);
                                prompt.set_last_success(false);
                                prompt.set_last_duration(Some(start_total.elapsed()));
                                continue;
                            }
                        }
                    }
                }

                execute_external_command(
                    input,
                    &expanded_input,
                    should_log,
                    &mut context,
                    &config,
                )?;

                if config.restore_env {
                    if let Ok(env) = context.current_env.lock() {
                        if let Err(e) = crate::env_store::save_env(&env, &env_store_path) {
                            eprintln!("Failed to save environment: {}", e);
                        }
                    }
                }
            }
            Ok(Signal::CtrlC) => {
                // Handle Ctrl+C at prompt - just continue to next prompt
                println!("^C");
                prompt.set_last_success(false);
                prompt.set_last_duration(None);
                continue;
            }
            Ok(Signal::CtrlD) => {
                // Handle Ctrl+D - exit the REPL
                break;
            }
            Err(e) => {
                eprintln!("Error: {:?}", e);
                break;
            }
        }

        // Handle pending command from edit
        if let Some(cmd) = next_command.take() {
            let _ = line_editor
                .history_mut()
                .save(HistoryItem::from_command_line(&cmd));
            let (_, should_log) = process_input(&cmd, &aliases);
            if should_log {
                let _ = disk_history.save(HistoryItem::from_command_line(&cmd));
            }
            // Also sync history to disk to ensure it persists
            let _ = disk_history.sync();
            // Inject the command into the next prompt
            line_editor.run_edit_commands(&[reedline::EditCommand::InsertString(cmd)]);
        }
    }

    // Sync the persisted history to disk
    let _ = disk_history.sync();

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use reedline::History;
    use tempfile::tempdir;

    #[test]
    fn nr_commands_stay_in_memory_only() -> Result<()> {
        let temp = tempdir()?;
        let history_path = temp.path().join("cahier_history.txt");

        let mut disk_history =
            FileBackedHistory::with_file(MAX_HISTORY_ENTRIES, history_path.clone())?;
        let mut session_history = FileBackedHistory::new(MAX_HISTORY_ENTRIES);

        let aliases = Arc::new(Mutex::new(HashMap::new()));
        let commands = ["echo one", "nr echo secret", "echo two"];

        for &cmd in &commands {
            let _ = session_history.save(HistoryItem::from_command_line(cmd));
            let (_, should_log) = process_input(cmd, &aliases);
            if should_log {
                let _ = disk_history.save(HistoryItem::from_command_line(cmd));
            }
        }

        disk_history.sync()?;

        let on_disk = std::fs::read_to_string(&history_path)?;
        assert!(on_disk.contains("echo one"));
        assert!(on_disk.contains("echo two"));
        assert!(!on_disk.contains("nr echo secret"));

        let session_entries = session_history
            .search(SearchQuery::everything(SearchDirection::Forward, None))?;
        let session_commands: Vec<String> = session_entries
            .into_iter()
            .map(|entry| entry.command_line)
            .collect();
        assert!(session_commands.contains(&"nr echo secret".to_string()));

        Ok(())
    }
}