1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-02 09:34:19 -04:00
denoland-deno/cli/ops/repl.rs

75 lines
1.9 KiB
Rust
Raw Normal View History

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
use crate::repl;
use crate::repl::Repl;
use crate::state::State;
use deno_core::BufVec;
use deno_core::ErrBox;
2020-09-05 20:34:02 -04:00
use deno_core::OpRegistry;
use deno_core::ZeroCopyBuf;
2020-09-05 20:34:02 -04:00
use serde_derive::Deserialize;
use serde_json::Value;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::Mutex;
2019-08-26 08:50:21 -04:00
2020-09-05 20:34:02 -04:00
pub fn init(s: &Rc<State>) {
s.register_op_json_sync("op_repl_start", op_repl_start);
s.register_op_json_async("op_repl_readline", op_repl_readline);
}
struct ReplResource(Arc<Mutex<Repl>>);
2019-08-26 08:50:21 -04:00
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ReplStartArgs {
history_file: String,
}
fn op_repl_start(
state: &State,
2019-08-26 08:50:21 -04:00
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
2019-08-26 08:50:21 -04:00
let args: ReplStartArgs = serde_json::from_value(args)?;
debug!("op_repl_start {}", args.history_file);
let history_path =
repl::history_path(&state.global_state.dir, &args.history_file);
let repl = repl::Repl::new(history_path);
let resource = ReplResource(Arc::new(Mutex::new(repl)));
2020-09-05 20:34:02 -04:00
let rid = state
.resource_table
.borrow_mut()
.add("repl", Box::new(resource));
Ok(json!(rid))
2019-08-26 08:50:21 -04:00
}
#[derive(Deserialize)]
struct ReplReadlineArgs {
rid: i32,
prompt: String,
}
async fn op_repl_readline(
2020-09-05 20:34:02 -04:00
state: Rc<State>,
2019-08-26 08:50:21 -04:00
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
2019-08-26 08:50:21 -04:00
let args: ReplReadlineArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
2019-08-26 08:50:21 -04:00
let prompt = args.prompt;
debug!("op_repl_readline {} {}", rid, prompt);
2020-09-05 20:34:02 -04:00
let resource_table = state.resource_table.borrow();
let resource = resource_table
.get::<ReplResource>(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
let repl = resource.0.clone();
drop(resource_table);
tokio::task::spawn_blocking(move || {
let line = repl.lock().unwrap().readline(&prompt)?;
2019-08-26 08:50:21 -04:00
Ok(json!(line))
})
.await
.unwrap()
}