1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-14 16:33:45 -05:00
denoland-deno/cli/ops/repl.rs

68 lines
1.8 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.
2019-08-26 08:50:21 -04:00
use super::dispatch_json::{blocking_json, Deserialize, JsonOp, Value};
use crate::op_error::OpError;
use crate::repl;
use crate::repl::Repl;
use crate::state::State;
use deno_core::*;
use std::sync::Arc;
use std::sync::Mutex;
2019-08-26 08:50:21 -04:00
pub fn init(i: &mut Isolate, s: &State) {
2020-02-25 09:14:27 -05:00
i.register_op("op_repl_start", s.stateful_json_op(op_repl_start));
i.register_op("op_repl_readline", s.stateful_json_op(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,
2020-01-24 15:10:49 -05:00
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, OpError> {
2019-08-26 08:50:21 -04:00
let args: ReplStartArgs = serde_json::from_value(args)?;
2019-08-26 08:50:21 -04:00
debug!("op_repl_start {}", args.history_file);
let history_path =
repl::history_path(&state.borrow().global_state.dir, &args.history_file);
let repl = repl::Repl::new(history_path);
let mut state = state.borrow_mut();
let resource = ReplResource(Arc::new(Mutex::new(repl)));
let rid = state.resource_table.add("repl", Box::new(resource));
Ok(JsonOp::Sync(json!(rid)))
2019-08-26 08:50:21 -04:00
}
#[derive(Deserialize)]
struct ReplReadlineArgs {
rid: i32,
prompt: String,
}
fn op_repl_readline(
state: &State,
2019-08-26 08:50:21 -04:00
args: Value,
2020-01-24 15:10:49 -05:00
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, OpError> {
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);
let state = state.borrow();
let resource = state
.resource_table
.get::<ReplResource>(rid)
.ok_or_else(OpError::bad_resource_id)?;
let repl = resource.0.clone();
2019-08-26 08:50:21 -04:00
blocking_json(false, move || {
let line = repl.lock().unwrap().readline(&prompt)?;
2019-08-26 08:50:21 -04:00
Ok(json!(line))
})
}