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};
pub fn history_path(state_dir: Option<PathBuf>) -> Option<PathBuf> {
state_dir.map(|d| d.join("history"))
}
pub struct CommandHelper;
impl CommandHelper {
fn candidates(line: &str, pos: usize) -> Vec<Pair> {
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>;
pub enum Input {
Line(String),
Interrupted,
Eof,
}
pub enum LineReader {
Editing(Box<Editing>),
Plain,
}
pub struct Editing {
editor: LineEditor,
path: Option<PathBuf>,
}
impl LineReader {
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
}
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) => {
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)),
}
}
}
}
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()
.max_history_size(max_history.max(1))?
.history_ignore_dups(true)?
.auto_add_history(false)
.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()
}
}
pub fn load_history(editor: &mut LineEditor, path: &Path) -> rustyline::Result<()> {
if !path.exists() {
return Ok(());
}
editor.load_history(path)
}
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() {
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(())
}
#[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::*;
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);
}
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);
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());
}
}