eclipse-cli 0.13.4

Command-line interface for eclipse
//! Interactive line editing and persistent history for the REPL.
//!
//! On a terminal the REPL reads with `rustyline` (cursor movement, Emacs keys, up/down
//! history, Ctrl-R search). Without a TTY (a pipe, a file, CI) it falls back to plain
//! line reading, exactly as before, and touches no history file.
//!
//! Tab completes a slash command (`commands::COMMANDS`) while the command word is being typed,
//! and lists the candidates when several match; anywhere else Tab edits as the editor always
//! did.
//!
//! History lives in `<state_dir>/history` (default `~/.eclipse/state/history`),
//! owner-only (`0600`) because prompts can contain sensitive text. It keeps the most
//! recent `[cli] history_size` entries and skips consecutive duplicates.

use eclipse_core::commands::{self, Completion, Front};
use rustyline::completion::{Completer, Pair};
use rustyline::error::ReadlineError;
use rustyline::highlight::Highlighter;
use rustyline::hint::Hinter;
use rustyline::history::DefaultHistory;
use rustyline::validate::Validator;
use rustyline::{CompletionType, Config, Context, Editor, Helper};
use std::io::{BufRead, IsTerminal, Write};
use std::path::{Path, PathBuf};

/// `<state>/history`. The state directory comes from the config, so a profile keeps its
/// own REPL history beside its own sessions.
pub fn history_path(state_dir: Option<PathBuf>) -> Option<PathBuf> {
    state_dir.map(|d| d.join("history"))
}

/// Tab completion for the command word, and nothing else.
pub struct CommandHelper;

impl CommandHelper {
    fn candidates(line: &str, pos: usize) -> Vec<Pair> {
        // Only at the end of the line: completing in the middle would leave the tail behind.
        if pos != line.len() {
            return Vec::new();
        }
        let found = match commands::complete(line, Front::Repl) {
            Completion::Unique(c) => vec![c],
            Completion::Several(found) => found,
            Completion::None => return Vec::new(),
        };
        found
            .into_iter()
            .map(|c| Pair {
                display: c.spelling(line).to_string(),
                replacement: c.fill(line),
            })
            .collect()
    }
}

impl Completer for CommandHelper {
    type Candidate = Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Pair>)> {
        Ok((0, Self::candidates(line, pos)))
    }
}

impl Hinter for CommandHelper {
    type Hint = String;
}
impl Highlighter for CommandHelper {}
impl Validator for CommandHelper {}
impl Helper for CommandHelper {}

type LineEditor = Editor<CommandHelper, DefaultHistory>;

/// What one attempt to read a line produced.
pub enum Input {
    Line(String),
    /// Ctrl-C at the prompt: discard the line and prompt again.
    Interrupted,
    /// End of input (Ctrl-D or closed stdin).
    Eof,
}

/// A line reader with history; see the module docs.
pub enum LineReader {
    Editing(Box<Editing>),
    Plain,
}

pub struct Editing {
    editor: LineEditor,
    path: Option<PathBuf>,
}

impl LineReader {
    /// Interactive editing when both stdin and stdout are terminals, else plain reads.
    pub fn detect(history: Option<PathBuf>, history_size: usize) -> LineReader {
        if std::io::stdin().is_terminal() && std::io::stdout().is_terminal() {
            match Editing::new(history, history_size) {
                Ok(e) => return LineReader::Editing(Box::new(e)),
                Err(e) => eprintln!("warning: line editing unavailable ({e}); using plain input"),
            }
        }
        LineReader::Plain
    }

    /// Print `prompt` and read one line. `plain_prompt` is shown by the plain reader
    /// (it may carry colour codes, which the line editor cannot measure).
    pub fn read(&mut self, prompt: &str, plain_prompt: &str) -> std::io::Result<Input> {
        match self {
            LineReader::Plain => {
                print!("{plain_prompt}");
                std::io::stdout().flush()?;
                let mut line = String::new();
                if std::io::stdin().lock().read_line(&mut line)? == 0 {
                    return Ok(Input::Eof);
                }
                Ok(Input::Line(line))
            }
            LineReader::Editing(e) => {
                // Blocking terminal I/O: tell the runtime so other tasks keep running.
                match tokio::task::block_in_place(|| e.editor.readline(prompt)) {
                    Ok(line) => Ok(Input::Line(line)),
                    Err(ReadlineError::Interrupted) => Ok(Input::Interrupted),
                    Err(ReadlineError::Eof) => Ok(Input::Eof),
                    Err(e) => Err(std::io::Error::other(e)),
                }
            }
        }
    }

    /// Remember an accepted line (no-op for the plain reader). Saved immediately, so a
    /// crash or kill does not lose the session's history.
    pub fn remember(&mut self, line: &str) {
        if let LineReader::Editing(e) = self {
            e.remember(line);
        }
    }
}

impl Editing {
    pub fn new(path: Option<PathBuf>, max_history: usize) -> Result<Self, ReadlineError> {
        let config = Config::builder()
            // rustyline rejects 0, and a history of nothing is never what someone means by
            // a small number, so anything under 1 falls back to the default.
            .max_history_size(max_history.max(1))?
            .history_ignore_dups(true)?
            .auto_add_history(false)
            // Several candidates are listed at once, not cycled through one Tab at a time:
            // listing is how a person finds out what the choices are.
            .completion_type(CompletionType::List)
            .completion_show_all_if_ambiguous(true)
            .build();
        let mut editor = LineEditor::with_config(config)?;
        editor.set_helper(Some(CommandHelper));
        if let Some(p) = &path {
            if let Err(e) = load_history(&mut editor, p) {
                eprintln!("warning: cannot read history {}: {e}", p.display());
            }
        }
        Ok(Self { editor, path })
    }

    fn remember(&mut self, line: &str) {
        if line.trim().is_empty() {
            return;
        }
        if self.editor.add_history_entry(line).is_err() {
            return;
        }
        if let Some(p) = &self.path {
            if let Err(e) = save_history(&mut self.editor, p) {
                eprintln!("warning: cannot write history {}: {e}", p.display());
            }
        }
    }

    #[cfg(test)]
    fn entries(&self) -> Vec<String> {
        self.editor.history().iter().cloned().collect()
    }
}

/// Load `path` into the editor; a missing file is an empty history.
pub fn load_history(editor: &mut LineEditor, path: &Path) -> rustyline::Result<()> {
    if !path.exists() {
        return Ok(());
    }
    editor.load_history(path)
}

/// Write the history to `path`, creating the directory and keeping the file `0600`.
pub fn save_history(editor: &mut LineEditor, path: &Path) -> rustyline::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    if !path.exists() {
        // Create it owner-only before any text is written to it.
        let mut opts = std::fs::OpenOptions::new();
        opts.write(true).create(true).truncate(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
        }
        opts.open(path)?;
    }
    editor.save_history(path)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
    }
    Ok(())
}

/// rustyline editors manage terminal file descriptors; creating them from several
/// test threads at once was observed to produce spurious EACCES errors in the
/// sandboxed test environment, so tests that build one run one at a time. The same
/// window breaks any test that creates directories (the process umask is briefly
/// restrictive), so those take this lock too.
#[cfg(test)]
pub(crate) fn serial() -> std::sync::MutexGuard<'static, ()> {
    static EDITOR_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    EDITOR_LOCK.lock().unwrap_or_else(|e| e.into_inner())
}

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

    /// The cap production gets when `[cli] history_size` is not set — the core config's default,
    /// not a second copy of the number that can drift from it.
    fn history_cap() -> usize {
        eclipse_core::config::Config::default().cli.history_size
    }

    #[test]
    fn history_path_is_under_the_given_state_dir() {
        assert_eq!(
            history_path(Some(PathBuf::from("/home/u/.eclipse/state"))).unwrap(),
            PathBuf::from("/home/u/.eclipse/state/history")
        );
        assert!(history_path(None).is_none());
    }

    #[test]
    fn history_round_trips_through_the_file() {
        let _serial = serial();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state/eclipse/history");
        let mut first = Editing::new(Some(path.clone()), history_cap()).unwrap();
        assert!(
            first.entries().is_empty(),
            "a missing file is an empty history"
        );
        for line in ["hello", "/help", "two  words", "hello", "hello", "   "] {
            first.remember(line);
        }
        // Consecutive duplicates and blank lines are not recorded.
        assert_eq!(first.entries(), ["hello", "/help", "two  words", "hello"]);
        assert!(path.exists());

        let second = Editing::new(Some(path.clone()), history_cap()).unwrap();
        assert_eq!(second.entries(), first.entries());

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            assert_eq!(path.metadata().unwrap().permissions().mode() & 0o777, 0o600);
        }
    }

    #[test]
    fn a_configured_history_size_is_what_gets_kept() {
        let _serial = serial();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("history");
        let mut e = Editing::new(Some(path.clone()), 3).unwrap();
        for i in 0..10 {
            e.remember(&format!("line {i}"));
        }
        assert_eq!(e.entries().len(), 3);
        // Zero is never what someone means: rustyline rejects it and a history of nothing is
        // useless, so it falls back to one entry rather than failing to start.
        assert!(Editing::new(None, 0).is_ok());
    }

    #[test]
    fn history_is_capped_and_multiline_entries_survive() {
        let _serial = serial();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("history");
        let mut e = Editing::new(Some(path.clone()), history_cap()).unwrap();
        for i in 0..history_cap() + 5 {
            e.editor.add_history_entry(format!("line {i}")).unwrap();
        }
        e.remember("a\nb");
        let reloaded = Editing::new(Some(path), history_cap()).unwrap().entries();
        assert_eq!(reloaded.len(), history_cap());
        assert_eq!(reloaded.last().unwrap(), "a\nb");
        assert_eq!(reloaded[0], "line 6");
    }

    #[test]
    fn an_unreadable_history_file_does_not_stop_the_repl() {
        let _serial = serial();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("history");
        std::fs::write(&path, [0xff, 0xfe, 0x00, b'\n']).unwrap();
        let e = Editing::new(Some(path), history_cap()).unwrap();
        assert!(e.entries().len() <= 1);
    }

    fn answers(line: &str) -> Vec<(String, String)> {
        let history = DefaultHistory::new();
        let ctx = Context::new(&history);
        let (start, found) = CommandHelper
            .complete(line, line.len(), &ctx)
            .expect("completing cannot fail");
        assert_eq!(start, 0, "the whole line is replaced");
        found
            .into_iter()
            .map(|p| (p.display, p.replacement))
            .collect()
    }

    #[test]
    fn tab_on_a_unique_prefix_offers_that_one_command() {
        assert_eq!(answers("/ne"), [("/new".to_string(), "/new".to_string())]);
        assert_eq!(
            answers("/st"),
            [("/status".to_string(), "/status".to_string())]
        );
    }

    #[test]
    fn tab_on_a_bare_slash_offers_what_the_repl_has_and_not_the_full_screen_commands() {
        let shown: Vec<String> = answers("/").into_iter().map(|(d, _)| d).collect();
        assert_eq!(
            shown,
            [
                "/new",
                "/retry",
                "/bg",
                "/tasks",
                "/id",
                "/profile",
                "/gateway",
                "/goal",
                "/loop",
                "/cron",
                "/reasoning",
                "/settings",
                "/set",
                "/yolo",
                "/status",
                "/compress",
                "/archive",
                "/help",
                "/exit"
            ]
        );
        assert!(answers("/cl").is_empty());
        assert!(answers("/mo").is_empty());
    }

    #[test]
    fn tab_in_ordinary_prose_offers_nothing() {
        for line in ["hello", "tell me about /ne", "", "/new ", "/ne w"] {
            assert!(answers(line).is_empty(), "{line:?}");
        }
    }

    #[test]
    fn an_alias_completes_to_what_was_typed_and_the_cursor_must_be_at_the_end() {
        assert_eq!(answers("/qu"), [("/quit".to_string(), "/quit".to_string())]);
        assert!(CommandHelper::candidates("/ne", 2).is_empty());
    }
}