Improvements to watch mode

This commit is contained in:
mo8it 2024-03-23 18:51:25 +01:00
parent 9c6f56b836
commit 3dce7e5696
3 changed files with 58 additions and 37 deletions

7
Cargo.lock generated
View file

@ -536,6 +536,7 @@ dependencies = [
"regex", "regex",
"serde", "serde",
"serde_json", "serde_json",
"shlex",
"toml", "toml",
] ]
@ -594,6 +595,12 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]] [[package]]
name = "strsim" name = "strsim"
version = "0.11.0" version = "0.11.0"

View file

@ -18,6 +18,7 @@ notify-debouncer-mini = "0.4.1"
regex = "1.10.3" regex = "1.10.3"
serde_json = "1.0.114" serde_json = "1.0.114"
serde = { version = "1.0.197", features = ["derive"] } serde = { version = "1.0.197", features = ["derive"] }
shlex = "1.3.0"
toml = "0.8.10" toml = "0.8.10"
[[bin]] [[bin]]

View file

@ -6,6 +6,7 @@ use clap::{Parser, Subcommand};
use console::Emoji; use console::Emoji;
use notify_debouncer_mini::notify::{self, RecursiveMode}; use notify_debouncer_mini::notify::{self, RecursiveMode};
use notify_debouncer_mini::{new_debouncer, DebouncedEventKind}; use notify_debouncer_mini::{new_debouncer, DebouncedEventKind};
use shlex::Shlex;
use std::ffi::OsStr; use std::ffi::OsStr;
use std::fs; use std::fs;
use std::io::{self, prelude::*}; use std::io::{self, prelude::*};
@ -25,6 +26,16 @@ mod project;
mod run; mod run;
mod verify; mod verify;
const WATCH_MODE_HELP_MESSAGE: &str = "Commands available to you in watch mode:
hint - prints the current exercise's hint
clear - clears the screen
quit - quits watch mode
!<cmd> - executes a command, like `!rustc --explain E0381`
help - displays this help message
Watch mode automatically re-evaluates the current exercise
when you edit a file's contents.";
/// Rustlings is a collection of small exercises to get you used to writing and reading Rust code /// Rustlings is a collection of small exercises to get you used to writing and reading Rust code
#[derive(Parser)] #[derive(Parser)]
#[command(version)] #[command(version)]
@ -246,15 +257,23 @@ fn main() {
} }
fn spawn_watch_shell( fn spawn_watch_shell(
failed_exercise_hint: &Arc<Mutex<Option<String>>>, failed_exercise_hint: Arc<Mutex<Option<String>>>,
should_quit: Arc<AtomicBool>, should_quit: Arc<AtomicBool>,
) { ) {
let failed_exercise_hint = Arc::clone(failed_exercise_hint);
println!("Welcome to watch mode! You can type 'help' to get an overview of the commands you can use here."); println!("Welcome to watch mode! You can type 'help' to get an overview of the commands you can use here.");
thread::spawn(move || loop {
thread::spawn(move || {
let mut input = String::new(); let mut input = String::new();
match io::stdin().read_line(&mut input) { let mut stdin = io::stdin().lock();
Ok(_) => {
loop {
// Recycle input buffer.
input.clear();
if let Err(e) = stdin.read_line(&mut input) {
println!("error reading command: {e}");
}
let input = input.trim(); let input = input.trim();
if input == "hint" { if input == "hint" {
if let Some(hint) = &*failed_exercise_hint.lock().unwrap() { if let Some(hint) = &*failed_exercise_hint.lock().unwrap() {
@ -262,32 +281,26 @@ fn spawn_watch_shell(
} }
} else if input == "clear" { } else if input == "clear" {
println!("\x1B[2J\x1B[1;1H"); println!("\x1B[2J\x1B[1;1H");
} else if input.eq("quit") { } else if input == "quit" {
should_quit.store(true, Ordering::SeqCst); should_quit.store(true, Ordering::SeqCst);
println!("Bye!"); println!("Bye!");
} else if input.eq("help") { } else if input == "help" {
println!("Commands available to you in watch mode:"); println!("{WATCH_MODE_HELP_MESSAGE}");
println!(" hint - prints the current exercise's hint");
println!(" clear - clears the screen");
println!(" quit - quits watch mode");
println!(" !<cmd> - executes a command, like `!rustc --explain E0381`");
println!(" help - displays this help message");
println!();
println!("Watch mode automatically re-evaluates the current exercise");
println!("when you edit a file's contents.")
} else if let Some(cmd) = input.strip_prefix('!') { } else if let Some(cmd) = input.strip_prefix('!') {
let parts: Vec<&str> = cmd.split_whitespace().collect(); let mut parts = Shlex::new(cmd);
if parts.is_empty() {
let Some(program) = parts.next() else {
println!("no command provided"); println!("no command provided");
} else if let Err(e) = Command::new(parts[0]).args(&parts[1..]).status() { continue;
println!("failed to execute command `{}`: {}", cmd, e); };
if let Err(e) = Command::new(program).args(parts).status() {
println!("failed to execute command `{cmd}`: {e}");
} }
} else { } else {
println!("unknown command: {input}"); println!("unknown command: {input}\n{WATCH_MODE_HELP_MESSAGE}");
} }
} }
Err(error) => println!("error reading command: {error}"),
}
}); });
} }
@ -348,7 +361,7 @@ fn watch(
Ok(_) => return Ok(WatchStatus::Finished), Ok(_) => return Ok(WatchStatus::Finished),
Err(exercise) => Arc::new(Mutex::new(Some(to_owned_hint(exercise)))), Err(exercise) => Arc::new(Mutex::new(Some(to_owned_hint(exercise)))),
}; };
spawn_watch_shell(&failed_exercise_hint, Arc::clone(&should_quit)); spawn_watch_shell(Arc::clone(&failed_exercise_hint), Arc::clone(&should_quit));
loop { loop {
match rx.recv_timeout(Duration::from_secs(1)) { match rx.recv_timeout(Duration::from_secs(1)) {
Ok(event) => match event { Ok(event) => match event {