2024-04-07 00:17:53 +01:00
|
|
|
use anyhow::Result;
|
2024-04-07 18:29:16 +01:00
|
|
|
use notify_debouncer_mini::{new_debouncer, notify::RecursiveMode};
|
2024-04-07 00:17:53 +01:00
|
|
|
use std::{
|
2024-04-07 18:29:16 +01:00
|
|
|
io::{self, BufRead, Write},
|
2024-04-07 00:17:53 +01:00
|
|
|
path::Path,
|
2024-04-07 18:29:16 +01:00
|
|
|
sync::mpsc::{channel, sync_channel},
|
2024-04-07 00:17:53 +01:00
|
|
|
thread,
|
|
|
|
time::Duration,
|
|
|
|
};
|
|
|
|
|
2024-04-07 18:29:16 +01:00
|
|
|
mod state;
|
|
|
|
|
|
|
|
use crate::{exercise::Exercise, state_file::StateFile};
|
|
|
|
|
|
|
|
use self::state::WatchState;
|
2024-04-07 00:17:53 +01:00
|
|
|
|
|
|
|
enum Event {
|
|
|
|
Hint,
|
|
|
|
Clear,
|
|
|
|
Quit,
|
|
|
|
}
|
|
|
|
|
2024-04-07 18:01:08 +01:00
|
|
|
pub fn watch(state_file: &StateFile, exercises: &[Exercise]) -> Result<()> {
|
2024-04-07 00:17:53 +01:00
|
|
|
let (tx, rx) = channel();
|
|
|
|
let mut debouncer = new_debouncer(Duration::from_secs(1), tx)?;
|
|
|
|
debouncer
|
|
|
|
.watcher()
|
|
|
|
.watch(Path::new("exercises"), RecursiveMode::Recursive)?;
|
|
|
|
|
2024-04-07 18:29:16 +01:00
|
|
|
let mut watch_state = WatchState::new(state_file, exercises, rx);
|
2024-04-07 00:17:53 +01:00
|
|
|
|
|
|
|
watch_state.run_exercise()?;
|
|
|
|
watch_state.render()?;
|
|
|
|
|
|
|
|
let (tx, rx) = sync_channel(0);
|
|
|
|
thread::spawn(move || {
|
|
|
|
let mut stdin = io::stdin().lock();
|
|
|
|
let mut stdin_buf = String::with_capacity(8);
|
|
|
|
|
|
|
|
loop {
|
|
|
|
stdin.read_line(&mut stdin_buf).unwrap();
|
|
|
|
|
|
|
|
let event = match stdin_buf.trim() {
|
|
|
|
"h" | "hint" => Some(Event::Hint),
|
|
|
|
"c" | "clear" => Some(Event::Clear),
|
|
|
|
"q" | "quit" => Some(Event::Quit),
|
|
|
|
_ => None,
|
|
|
|
};
|
|
|
|
|
|
|
|
stdin_buf.clear();
|
|
|
|
|
|
|
|
if tx.send(event).is_err() {
|
|
|
|
break;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
loop {
|
|
|
|
watch_state.try_recv_event()?;
|
|
|
|
|
|
|
|
if let Ok(event) = rx.try_recv() {
|
|
|
|
match event {
|
|
|
|
Some(Event::Hint) => {
|
2024-04-07 18:29:16 +01:00
|
|
|
watch_state.show_hint()?;
|
2024-04-07 00:17:53 +01:00
|
|
|
}
|
|
|
|
Some(Event::Clear) => {
|
|
|
|
watch_state.render()?;
|
|
|
|
}
|
|
|
|
Some(Event::Quit) => break,
|
|
|
|
None => {
|
2024-04-07 18:29:16 +01:00
|
|
|
watch_state.handle_invalid_cmd()?;
|
2024-04-07 00:17:53 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-07 18:29:16 +01:00
|
|
|
watch_state.into_writer().write_all(b"
|
2024-04-07 00:17:53 +01:00
|
|
|
We hope you're enjoying learning Rust!
|
|
|
|
If you want to continue working on the exercises at a later point, you can simply run `rustlings` again.
|
|
|
|
")?;
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|