2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2020-09-05 20:34:02 -04:00
|
|
|
|
2019-01-14 01:30:38 -05:00
|
|
|
use crate::deno_dir::DenoDir;
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::AnyError;
|
2020-05-07 12:01:27 -04:00
|
|
|
use rustyline::Editor;
|
2019-10-11 13:12:39 -04:00
|
|
|
use std::fs;
|
2018-11-05 12:55:59 -05:00
|
|
|
use std::path::PathBuf;
|
|
|
|
|
|
|
|
pub struct Repl {
|
|
|
|
editor: Editor<()>,
|
|
|
|
history_file: PathBuf,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Repl {
|
2018-11-05 01:21:21 -05:00
|
|
|
pub fn new(history_file: PathBuf) -> Self {
|
|
|
|
let mut repl = Self {
|
2018-11-05 12:55:59 -05:00
|
|
|
editor: Editor::<()>::new(),
|
|
|
|
history_file,
|
|
|
|
};
|
|
|
|
|
|
|
|
repl.load_history();
|
|
|
|
repl
|
|
|
|
}
|
|
|
|
|
2019-01-15 07:06:25 -05:00
|
|
|
fn load_history(&mut self) {
|
2018-11-05 12:55:59 -05:00
|
|
|
debug!("Loading REPL history: {:?}", self.history_file);
|
|
|
|
self
|
|
|
|
.editor
|
|
|
|
.load_history(&self.history_file.to_str().unwrap())
|
2019-07-31 17:11:37 -04:00
|
|
|
.map_err(|e| {
|
|
|
|
debug!("Unable to load history file: {:?} {}", self.history_file, e)
|
|
|
|
})
|
2018-11-05 12:55:59 -05:00
|
|
|
// ignore this error (e.g. it occurs on first load)
|
|
|
|
.unwrap_or(())
|
|
|
|
}
|
|
|
|
|
2020-09-14 12:48:57 -04:00
|
|
|
fn save_history(&mut self) -> Result<(), AnyError> {
|
2019-10-11 13:12:39 -04:00
|
|
|
fs::create_dir_all(self.history_file.parent().unwrap())?;
|
2018-11-05 12:55:59 -05:00
|
|
|
self
|
|
|
|
.editor
|
|
|
|
.save_history(&self.history_file.to_str().unwrap())
|
|
|
|
.map(|_| debug!("Saved REPL history to: {:?}", self.history_file))
|
|
|
|
.map_err(|e| {
|
|
|
|
eprintln!("Unable to save REPL history: {:?} {}", self.history_file, e);
|
2020-08-25 18:22:15 -04:00
|
|
|
e.into()
|
2018-11-05 12:55:59 -05:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-09-14 12:48:57 -04:00
|
|
|
pub fn readline(&mut self, prompt: &str) -> Result<String, AnyError> {
|
2018-11-05 12:55:59 -05:00
|
|
|
self
|
|
|
|
.editor
|
|
|
|
.readline(&prompt)
|
|
|
|
.map(|line| {
|
2019-06-18 09:28:56 -04:00
|
|
|
self.editor.add_history_entry(line.clone());
|
2018-11-05 12:55:59 -05:00
|
|
|
line
|
2019-07-31 17:11:37 -04:00
|
|
|
})
|
2020-09-14 12:48:57 -04:00
|
|
|
.map_err(AnyError::from)
|
2020-08-25 18:22:15 -04:00
|
|
|
|
2019-02-11 14:01:28 -05:00
|
|
|
// Forward error to TS side for processing
|
2018-11-05 12:55:59 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for Repl {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
self.save_history().unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn history_path(dir: &DenoDir, history_file: &str) -> PathBuf {
|
|
|
|
let mut p: PathBuf = dir.root.clone();
|
|
|
|
p.push(history_file);
|
|
|
|
p
|
|
|
|
}
|