Compare commits

..

No commits in common. "4bb6bda9f6416e30233342e73fc9a8486faa3f98" and "c8d217ad50a7117fe35735b4083f2aa1e2b47d97" have entirely different histories.

10 changed files with 148 additions and 285 deletions

View file

@ -46,7 +46,6 @@ pub enum Mode {
} }
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InfoFile { pub struct InfoFile {
pub exercises: Vec<Exercise>, pub exercises: Vec<Exercise>,
} }
@ -66,7 +65,6 @@ impl InfoFile {
// Deserialized from the `info.toml` file. // Deserialized from the `info.toml` file.
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Exercise { pub struct Exercise {
// Name of the exercise // Name of the exercise
pub name: String, pub name: String,

View file

@ -28,10 +28,13 @@ pub fn list(state_file: &mut StateFile, exercises: &'static [Exercise]) -> Resul
let key = loop { let key = loop {
match event::read()? { match event::read()? {
Event::Key(key) => match key.kind { Event::Key(key) => {
KeyEventKind::Press | KeyEventKind::Repeat => break key, if key.kind != KeyEventKind::Press {
KeyEventKind::Release => (), continue;
}, }
break key;
}
// Redraw // Redraw
Event::Resize(_, _) => continue 'outer, Event::Resize(_, _) => continue 'outer,
// Ignore // Ignore

View file

@ -7,7 +7,7 @@ use ratatui::{
Frame, Frame,
}; };
use crate::{exercise::Exercise, progress_bar::progress_bar_ratatui, state_file::StateFile}; use crate::{exercise::Exercise, progress_bar::progress_bar, state_file::StateFile};
#[derive(Copy, Clone, PartialEq, Eq)] #[derive(Copy, Clone, PartialEq, Eq)]
pub enum Filter { pub enum Filter {
@ -166,11 +166,11 @@ impl UiState {
); );
frame.render_widget( frame.render_widget(
Paragraph::new(progress_bar_ratatui( Paragraph::new(Span::raw(progress_bar(
self.progress, self.progress,
self.exercises.len() as u16, self.exercises.len() as u16,
area.width, area.width,
)?) )?))
.block(Block::default().borders(Borders::BOTTOM)), .block(Block::default().borders(Borders::BOTTOM)),
Rect { Rect {
x: 0, x: 0,
@ -186,7 +186,7 @@ impl UiState {
"↓/j ↑/k home/g end/G │ filter <d>one/<p>ending │ <r>eset │ <c>ontinue at │ <q>uit", "↓/j ↑/k home/g end/G │ filter <d>one/<p>ending │ <r>eset │ <c>ontinue at │ <q>uit",
) )
} else { } else {
self.message.as_str().light_blue() self.message.as_str().blue()
}; };
frame.render_widget( frame.render_widget(
message, message,

View file

@ -16,11 +16,9 @@ mod watch;
use self::{ use self::{
consts::WELCOME, consts::WELCOME,
exercise::{Exercise, InfoFile}, exercise::{Exercise, InfoFile},
list::list,
run::run, run::run,
state_file::StateFile, state_file::StateFile,
verify::{verify, VerifyState}, verify::{verify, VerifyState},
watch::{watch, WatchExit},
}; };
/// 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
@ -54,6 +52,8 @@ enum Subcommands {
/// The name of the exercise /// The name of the exercise
name: String, name: String,
}, },
/// List the exercises available in Rustlings
List,
} }
fn find_exercise(name: &str, exercises: &'static [Exercise]) -> Result<(usize, &'static Exercise)> { fn find_exercise(name: &str, exercises: &'static [Exercise]) -> Result<(usize, &'static Exercise)> {
@ -112,17 +112,14 @@ If you are just starting with Rustlings, run the command `rustlings init` to ini
let mut state_file = StateFile::read_or_default(exercises); let mut state_file = StateFile::read_or_default(exercises);
match args.command { match args.command {
None | Some(Subcommands::Watch) => loop { None | Some(Subcommands::Watch) => {
match watch(&mut state_file, exercises)? { watch::watch(&state_file, exercises)?;
WatchExit::Shutdown => break, }
// It is much easier to exit the watch mode, launch the list mode and then restart
// the watch mode instead of trying to pause the watch threads and correct the
// watch state.
WatchExit::List => list(&mut state_file, exercises)?,
}
},
// `Init` is handled above. // `Init` is handled above.
Some(Subcommands::Init) => (), Some(Subcommands::Init) => (),
Some(Subcommands::List) => {
list::list(&mut state_file, exercises)?;
}
Some(Subcommands::Run { name }) => { Some(Subcommands::Run { name }) => {
let (_, exercise) = find_exercise(&name, exercises)?; let (_, exercise) = find_exercise(&name, exercises)?;
run(exercise).unwrap_or_else(|_| exit(1)); run(exercise).unwrap_or_else(|_| exit(1));

View file

@ -1,97 +1,41 @@
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use ratatui::text::{Line, Span};
use std::fmt::Write; use std::fmt::Write;
const PREFIX: &str = "Progress: [";
const PREFIX_WIDTH: u16 = PREFIX.len() as u16;
// Leaving the last char empty (_) for `total` > 99.
const POSTFIX_WIDTH: u16 = "] xxx/xx exercises_".len() as u16;
const WRAPPER_WIDTH: u16 = PREFIX_WIDTH + POSTFIX_WIDTH;
const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4;
const PROGRESS_EXCEEDS_MAX_ERR: &str =
"The progress of the progress bar is higher than the maximum";
pub fn progress_bar(progress: u16, total: u16, line_width: u16) -> Result<String> { pub fn progress_bar(progress: u16, total: u16, line_width: u16) -> Result<String> {
use crossterm::style::Stylize;
if progress > total { if progress > total {
bail!(PROGRESS_EXCEEDS_MAX_ERR); bail!("The progress of the progress bar is higher than the maximum");
} }
if line_width < MIN_LINE_WIDTH { // "Progress: [".len() == 11
// "] xxx/xx exercises_".len() == 19 (leaving the last char empty for `total` > 99)
// 11 + 19 = 30
let wrapper_width = 30;
// If the line width is too low for a progress bar, just show the ratio.
if line_width < wrapper_width + 4 {
return Ok(format!("Progress: {progress}/{total} exercises")); return Ok(format!("Progress: {progress}/{total} exercises"));
} }
let mut line = String::with_capacity(usize::from(line_width)); let mut line = String::with_capacity(usize::from(line_width));
line.push_str(PREFIX); line.push_str("Progress: [");
let width = line_width - WRAPPER_WIDTH; let remaining_width = line_width.saturating_sub(wrapper_width);
let filled = (width * progress) / total; let filled = (remaining_width * progress) / total;
let mut green_part = String::with_capacity(usize::from(filled + 1));
for _ in 0..filled { for _ in 0..filled {
green_part.push('#'); line.push('=');
} }
if filled < width { if filled < remaining_width {
green_part.push('>'); line.push('>');
}
write!(line, "{}", green_part.green()).unwrap();
let width_minus_filled = width - filled;
if width_minus_filled > 1 {
let red_part_width = width_minus_filled - 1;
let mut red_part = String::with_capacity(usize::from(red_part_width));
for _ in 0..red_part_width {
red_part.push('-');
}
write!(line, "{}", red_part.red()).unwrap();
} }
writeln!(line, "] {progress:>3}/{total} exercises").unwrap(); for _ in 0..(remaining_width - filled).saturating_sub(1) {
line.push(' ');
}
line.write_fmt(format_args!("] {progress:>3}/{total} exercises"))
.unwrap();
Ok(line) Ok(line)
} }
pub fn progress_bar_ratatui(progress: u16, total: u16, line_width: u16) -> Result<Line<'static>> {
use ratatui::style::Stylize;
if progress > total {
bail!(PROGRESS_EXCEEDS_MAX_ERR);
}
if line_width < MIN_LINE_WIDTH {
return Ok(Line::raw(format!("Progress: {progress}/{total} exercises")));
}
let mut spans = Vec::with_capacity(4);
spans.push(Span::raw(PREFIX));
let width = line_width - WRAPPER_WIDTH;
let filled = (width * progress) / total;
let mut green_part = String::with_capacity(usize::from(filled + 1));
for _ in 0..filled {
green_part.push('#');
}
if filled < width {
green_part.push('>');
}
spans.push(green_part.green());
let width_minus_filled = width - filled;
if width_minus_filled > 1 {
let red_part_width = width_minus_filled - 1;
let mut red_part = String::with_capacity(usize::from(red_part_width));
for _ in 0..red_part_width {
red_part.push('-');
}
spans.push(red_part.red());
}
spans.push(Span::raw(format!("] {progress:>3}/{total} exercises")));
Ok(Line::from(spans))
}

View file

@ -5,7 +5,6 @@ use std::fs;
use crate::exercise::Exercise; use crate::exercise::Exercise;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StateFile { pub struct StateFile {
next_exercise_ind: usize, next_exercise_ind: usize,
progress: Vec<bool>, progress: Vec<bool>,
@ -34,6 +33,7 @@ impl StateFile {
} }
fn write(&self) -> Result<()> { fn write(&self) -> Result<()> {
// TODO: Capacity
let mut buf = Vec::with_capacity(1024); let mut buf = Vec::with_capacity(1024);
serde_json::ser::to_writer(&mut buf, self).context("Failed to serialize the state")?; serde_json::ser::to_writer(&mut buf, self).context("Failed to serialize the state")?;
fs::write(".rustlings-state.json", buf) fs::write(".rustlings-state.json", buf)

View file

@ -1,49 +1,109 @@
use anyhow::{Error, Result}; use anyhow::Result;
use notify_debouncer_mini::{ use notify_debouncer_mini::{
new_debouncer, new_debouncer,
notify::{self, RecursiveMode}, notify::{self, RecursiveMode},
DebounceEventResult, DebouncedEventKind,
}; };
use std::{ use std::{
io::{self, Write}, io::{self, BufRead, Write},
path::Path, path::Path,
sync::mpsc::channel, sync::mpsc::{channel, Sender},
thread, thread,
time::Duration, time::Duration,
}; };
mod debounce_event;
mod state; mod state;
mod terminal_event;
use crate::{exercise::Exercise, state_file::StateFile}; use crate::{exercise::Exercise, state_file::StateFile};
use self::{ use self::state::WatchState;
debounce_event::DebounceEventHandler,
state::WatchState, enum InputEvent {
terminal_event::{terminal_event_handler, InputEvent}, Hint,
}; Clear,
Quit,
Unrecognized,
}
enum WatchEvent { enum WatchEvent {
Input(InputEvent), Input(InputEvent),
FileChange { exercise_ind: usize }, FileChange { exercise_ind: usize },
NotifyErr(notify::Error), NotifyErr(notify::Error),
TerminalEventErr(io::Error), StdinErr(io::Error),
TerminalResize, TerminalResize,
} }
/// Returned by the watch mode to indicate what to do afterwards. struct DebouceEventHandler {
pub enum WatchExit { tx: Sender<WatchEvent>,
/// Exit the program. exercises: &'static [Exercise],
Shutdown,
/// Enter the list mode and restart the watch mode afterwards.
List,
} }
pub fn watch(state_file: &mut StateFile, exercises: &'static [Exercise]) -> Result<WatchExit> { impl notify_debouncer_mini::DebounceEventHandler for DebouceEventHandler {
fn handle_event(&mut self, event: DebounceEventResult) {
let event = match event {
Ok(event) => {
let Some(exercise_ind) = event
.iter()
.filter_map(|event| {
if event.kind != DebouncedEventKind::Any
|| !event.path.extension().is_some_and(|ext| ext == "rs")
{
return None;
}
self.exercises
.iter()
.position(|exercise| event.path.ends_with(&exercise.path))
})
.min()
else {
return;
};
WatchEvent::FileChange { exercise_ind }
}
Err(e) => WatchEvent::NotifyErr(e),
};
// An error occurs when the receiver is dropped.
// After dropping the receiver, the debouncer guard should also be dropped.
let _ = self.tx.send(event);
}
}
fn input_handler(tx: Sender<WatchEvent>) {
let mut stdin = io::stdin().lock();
let mut stdin_buf = String::with_capacity(8);
loop {
if let Err(e) = stdin.read_line(&mut stdin_buf) {
// If `send` returns an error, then the receiver is dropped and
// a shutdown has been already initialized.
let _ = tx.send(WatchEvent::StdinErr(e));
return;
}
let event = match stdin_buf.trim() {
"h" | "hint" => InputEvent::Hint,
"c" | "clear" => InputEvent::Clear,
"q" | "quit" => InputEvent::Quit,
_ => InputEvent::Unrecognized,
};
stdin_buf.clear();
if tx.send(WatchEvent::Input(event)).is_err() {
// The receiver was dropped.
return;
}
}
}
pub fn watch(state_file: &StateFile, exercises: &'static [Exercise]) -> Result<()> {
let (tx, rx) = channel(); let (tx, rx) = channel();
let mut debouncer = new_debouncer( let mut debouncer = new_debouncer(
Duration::from_secs(1), Duration::from_secs(1),
DebounceEventHandler { DebouceEventHandler {
tx: tx.clone(), tx: tx.clone(),
exercises, exercises,
}, },
@ -58,34 +118,27 @@ pub fn watch(state_file: &mut StateFile, exercises: &'static [Exercise]) -> Resu
watch_state.run_exercise()?; watch_state.run_exercise()?;
watch_state.render()?; watch_state.render()?;
thread::spawn(move || terminal_event_handler(tx)); thread::spawn(move || input_handler(tx));
while let Ok(event) = rx.recv() { while let Ok(event) = rx.recv() {
match event { match event {
WatchEvent::Input(InputEvent::Hint) => { WatchEvent::Input(InputEvent::Hint) => {
watch_state.show_hint()?; watch_state.show_hint()?;
} }
WatchEvent::Input(InputEvent::List) => { WatchEvent::Input(InputEvent::Clear) | WatchEvent::TerminalResize => {
return Ok(WatchExit::List);
}
WatchEvent::TerminalResize => {
watch_state.render()?; watch_state.render()?;
} }
WatchEvent::Input(InputEvent::Quit) => break, WatchEvent::Input(InputEvent::Quit) => break,
WatchEvent::Input(InputEvent::Unrecognized(cmd)) => { WatchEvent::Input(InputEvent::Unrecognized) => {
watch_state.handle_invalid_cmd(&cmd)?; watch_state.handle_invalid_cmd()?;
} }
WatchEvent::FileChange { exercise_ind } => { WatchEvent::FileChange { exercise_ind } => {
// TODO: bool // TODO: bool
watch_state.run_exercise_with_ind(exercise_ind)?; watch_state.run_exercise_with_ind(exercise_ind)?;
watch_state.render()?; watch_state.render()?;
} }
WatchEvent::NotifyErr(e) => { WatchEvent::NotifyErr(e) => return Err(e.into()),
return Err(Error::from(e).context("Exercise file watcher failed")) WatchEvent::StdinErr(e) => return Err(e.into()),
}
WatchEvent::TerminalEventErr(e) => {
return Err(Error::from(e).context("Terminal event listener failed"))
}
} }
} }
@ -94,5 +147,5 @@ 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. If you want to continue working on the exercises at a later point, you can simply run `rustlings` again.
")?; ")?;
Ok(WatchExit::Shutdown) Ok(())
} }

View file

@ -1,44 +0,0 @@
use notify_debouncer_mini::{DebounceEventResult, DebouncedEventKind};
use std::sync::mpsc::Sender;
use crate::exercise::Exercise;
use super::WatchEvent;
pub struct DebounceEventHandler {
pub tx: Sender<WatchEvent>,
pub exercises: &'static [Exercise],
}
impl notify_debouncer_mini::DebounceEventHandler for DebounceEventHandler {
fn handle_event(&mut self, event: DebounceEventResult) {
let event = match event {
Ok(event) => {
let Some(exercise_ind) = event
.iter()
.filter_map(|event| {
if event.kind != DebouncedEventKind::Any
|| !event.path.extension().is_some_and(|ext| ext == "rs")
{
return None;
}
self.exercises
.iter()
.position(|exercise| event.path.ends_with(&exercise.path))
})
.min()
else {
return;
};
WatchEvent::FileChange { exercise_ind }
}
Err(e) => WatchEvent::NotifyErr(e),
};
// An error occurs when the receiver is dropped.
// After dropping the receiver, the debouncer guard should also be dropped.
let _ = self.tx.send(event);
}
}

View file

@ -6,7 +6,7 @@ use crossterm::{
}; };
use std::{ use std::{
fmt::Write as _, fmt::Write as _,
io::{self, StdoutLock, Write}, io::{self, StdoutLock, Write as _},
}; };
use crate::{ use crate::{
@ -20,31 +20,36 @@ pub struct WatchState<'a> {
exercises: &'static [Exercise], exercises: &'static [Exercise],
exercise: &'static Exercise, exercise: &'static Exercise,
current_exercise_ind: usize, current_exercise_ind: usize,
progress: u16,
stdout: Option<Vec<u8>>, stdout: Option<Vec<u8>>,
stderr: Option<Vec<u8>>, stderr: Option<Vec<u8>>,
message: Option<String>, message: Option<String>,
hint_displayed: bool, prompt: Vec<u8>,
} }
impl<'a> WatchState<'a> { impl<'a> WatchState<'a> {
pub fn new(state_file: &StateFile, exercises: &'static [Exercise]) -> Self { pub fn new(state_file: &StateFile, exercises: &'static [Exercise]) -> Self {
let current_exercise_ind = state_file.next_exercise_ind(); let current_exercise_ind = state_file.next_exercise_ind();
let progress = state_file.progress().iter().filter(|done| **done).count() as u16;
let exercise = &exercises[current_exercise_ind]; let exercise = &exercises[current_exercise_ind];
let writer = io::stdout().lock(); let writer = io::stdout().lock();
let prompt = format!(
"\n\n{}int/{}lear/{}uit? ",
"h".bold(),
"c".bold(),
"q".bold()
)
.into_bytes();
Self { Self {
writer, writer,
exercises, exercises,
exercise, exercise,
current_exercise_ind, current_exercise_ind,
progress,
stdout: None, stdout: None,
stderr: None, stderr: None,
message: None, message: None,
hint_displayed: false, prompt,
} }
} }
@ -113,32 +118,19 @@ You can keep working on this exercise or jump into the next one by removing the
} }
pub fn show_prompt(&mut self) -> io::Result<()> { pub fn show_prompt(&mut self) -> io::Result<()> {
self.writer.write_all(b"\n\n")?; self.writer.write_all(&self.prompt)?;
if !self.hint_displayed {
self.writer.write_fmt(format_args!("{}int/", 'h'.bold()))?;
}
self.writer
.write_fmt(format_args!("{}ist/{}uit? ", 'l'.bold(), 'q'.bold()))?;
self.writer.flush() self.writer.flush()
} }
pub fn render(&mut self) -> Result<()> { pub fn render(&mut self) -> Result<()> {
// Prevent having the first line shifted after clearing because of the prompt.
self.writer.write_all(b"\n")?;
self.writer.execute(Clear(ClearType::All))?; self.writer.execute(Clear(ClearType::All))?;
if let Some(stdout) = &self.stdout { if let Some(stdout) = &self.stdout {
self.writer.write_all(stdout)?; self.writer.write_all(stdout)?;
self.writer.write_all(b"\n")?;
} }
if let Some(stderr) = &self.stderr { if let Some(stderr) = &self.stderr {
self.writer.write_all(stderr)?; self.writer.write_all(stderr)?;
self.writer.write_all(b"\n")?;
} }
if let Some(message) = &self.message { if let Some(message) = &self.message {
@ -146,41 +138,26 @@ You can keep working on this exercise or jump into the next one by removing the
} }
self.writer.write_all(b"\n")?; self.writer.write_all(b"\n")?;
if self.hint_displayed {
self.writer
.write_fmt(format_args!("\n{}\n", "Hint".bold().cyan().underlined()))?;
self.writer.write_all(self.exercise.hint.as_bytes())?;
self.writer.write_all(b"\n\n")?;
}
let line_width = size()?.0; let line_width = size()?.0;
let progress_bar = progress_bar(self.progress, self.exercises.len() as u16, line_width)?; let progress_bar = progress_bar(
self.current_exercise_ind as u16,
self.exercises.len() as u16,
line_width,
)?;
self.writer.write_all(progress_bar.as_bytes())?; self.writer.write_all(progress_bar.as_bytes())?;
self.writer.write_all(b"Current exercise: ")?;
self.writer.write_fmt(format_args!(
"{}",
self.exercise.path.to_string_lossy().bold()
))?;
self.show_prompt()?; self.show_prompt()?;
Ok(()) Ok(())
} }
pub fn show_hint(&mut self) -> Result<()> { pub fn show_hint(&mut self) -> io::Result<()> {
self.hint_displayed = true; self.writer.write_all(self.exercise.hint.as_bytes())?;
self.render() self.show_prompt()
} }
pub fn handle_invalid_cmd(&mut self, cmd: &str) -> io::Result<()> { pub fn handle_invalid_cmd(&mut self) -> io::Result<()> {
self.writer.write_all(b"Invalid command: ")?; self.writer.write_all(b"Invalid command")?;
self.writer.write_all(cmd.as_bytes())?;
if cmd.len() > 1 {
self.writer
.write_all(b" (confusing input can occur after resizing the terminal)")?;
}
self.show_prompt() self.show_prompt()
} }
} }

View file

@ -1,65 +0,0 @@
use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use std::sync::mpsc::Sender;
use super::WatchEvent;
pub enum InputEvent {
Hint,
List,
Quit,
Unrecognized(String),
}
pub fn terminal_event_handler(tx: Sender<WatchEvent>) {
let mut input = String::with_capacity(8);
let last_input_event = loop {
let terminal_event = match event::read() {
Ok(v) => v,
Err(e) => {
// If `send` returns an error, then the receiver is dropped and
// a shutdown has been already initialized.
let _ = tx.send(WatchEvent::TerminalEventErr(e));
return;
}
};
match terminal_event {
Event::Key(key) => {
match key.kind {
KeyEventKind::Release => continue,
KeyEventKind::Press | KeyEventKind::Repeat => (),
}
match key.code {
KeyCode::Enter => {
let input_event = match input.trim() {
"h" | "hint" => InputEvent::Hint,
"l" | "list" => break InputEvent::List,
"q" | "quit" => break InputEvent::Quit,
_ => InputEvent::Unrecognized(input.clone()),
};
if tx.send(WatchEvent::Input(input_event)).is_err() {
return;
}
input.clear();
}
KeyCode::Char(c) => {
input.push(c);
}
_ => (),
}
}
Event::Resize(_, _) => {
if tx.send(WatchEvent::TerminalResize).is_err() {
return;
}
}
Event::FocusGained | Event::FocusLost | Event::Mouse(_) | Event::Paste(_) => continue,
}
};
let _ = tx.send(WatchEvent::Input(last_input_event));
}