use std::time::Instant;
use easy_repl::{Repl, CommandStatus, Critical, command};
use anyhow::{self, Context};
fn may_throw(description: String) -> Result<(), std::io::Error> {
Err(std::io::Error::new(std::io::ErrorKind::Other, description))
}
fn main() -> anyhow::Result<()> {
let start = Instant::now();
let mut repl = Repl::builder()
.add("ok", command! {
"Run a command that just succeeds",
() => || Ok(CommandStatus::Done)
})
.add("error", command! {
"Command with recoverable error handled by the REPL",
(text:String) => |text| {
may_throw(text)?;
Ok(CommandStatus::Done)
},
})
.add("critical", command! {
"Command returns a critical error that must be handled outside of REPL",
(text:String) => |text| {
may_throw(text).into_critical()?;
Ok(CommandStatus::Done)
},
})
.add("roulette", command! {
"Feeling lucky?",
() => || {
let ns = Instant::now().duration_since(start).as_nanos();
let cylinder = ns % 6;
match cylinder {
0 => may_throw("Bang!".into()).into_critical()?,
1..=2 => may_throw("Blank cartridge?".into())?,
_ => (),
}
Ok(CommandStatus::Done)
},
})
.build().context("Failed to create repl")?;
repl.run().context("Critical REPL error")?;
Ok(())
}