mirror of
https://github.com/rust-lang/rustlings.git
synced 2024-12-26 00:00:03 +03:00
Compare commits
9 commits
d3f819f86f
...
932bc25d88
Author | SHA1 | Date | |
---|---|---|---|
932bc25d88 | |||
bdc6dad8de | |||
ea73af9ba3 | |||
fc5fc0920f | |||
9705c161b4 | |||
8cac21511c | |||
396ee4d618 | |||
326169a7fa | |||
685e069c58 |
|
@ -13,4 +13,6 @@ disallowed-methods = [
|
||||||
# Use `thread::Builder::spawn` instead and handle the error.
|
# Use `thread::Builder::spawn` instead and handle the error.
|
||||||
"std::thread::spawn",
|
"std::thread::spawn",
|
||||||
"std::thread::Scope::spawn",
|
"std::thread::Scope::spawn",
|
||||||
|
# Return `ExitCode` instead.
|
||||||
|
"std::process::exit",
|
||||||
]
|
]
|
||||||
|
|
285
src/app_state.rs
285
src/app_state.rs
|
@ -1,16 +1,15 @@
|
||||||
use anyhow::{bail, Context, Result};
|
use anyhow::{bail, Context, Error, Result};
|
||||||
use crossterm::{
|
use crossterm::{cursor, terminal, QueueableCommand};
|
||||||
queue,
|
|
||||||
style::{Print, ResetColor, SetForegroundColor},
|
|
||||||
terminal,
|
|
||||||
};
|
|
||||||
use std::{
|
use std::{
|
||||||
env,
|
env,
|
||||||
fs::{File, OpenOptions},
|
fs::{File, OpenOptions},
|
||||||
io::{self, Read, Seek, StdoutLock, Write},
|
io::{Read, Seek, StdoutLock, Write},
|
||||||
path::{Path, MAIN_SEPARATOR_STR},
|
path::{Path, MAIN_SEPARATOR_STR},
|
||||||
process::{Command, Stdio},
|
process::{Command, Stdio},
|
||||||
sync::{atomic::AtomicUsize, mpsc, Arc},
|
sync::{
|
||||||
|
atomic::{AtomicUsize, Ordering::Relaxed},
|
||||||
|
mpsc,
|
||||||
|
},
|
||||||
thread,
|
thread,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -21,7 +20,7 @@ use crate::{
|
||||||
embedded::EMBEDDED_FILES,
|
embedded::EMBEDDED_FILES,
|
||||||
exercise::{Exercise, RunnableExercise},
|
exercise::{Exercise, RunnableExercise},
|
||||||
info_file::ExerciseInfo,
|
info_file::ExerciseInfo,
|
||||||
term::{self, progress_bar_with_success},
|
term::{self, CheckProgressVisualizer},
|
||||||
};
|
};
|
||||||
|
|
||||||
const STATE_FILE_NAME: &str = ".rustlings-state.txt";
|
const STATE_FILE_NAME: &str = ".rustlings-state.txt";
|
||||||
|
@ -42,12 +41,12 @@ pub enum StateFileStatus {
|
||||||
NotRead,
|
NotRead,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq)]
|
#[derive(Clone, Copy)]
|
||||||
enum AllExercisesResult {
|
pub enum CheckProgress {
|
||||||
|
None,
|
||||||
|
Checking,
|
||||||
|
Done,
|
||||||
Pending,
|
Pending,
|
||||||
Success,
|
|
||||||
Failed,
|
|
||||||
Error,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
|
@ -203,6 +202,11 @@ impl AppState {
|
||||||
self.n_done
|
self.n_done
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn n_pending(&self) -> u16 {
|
||||||
|
self.exercises.len() as u16 - self.n_done
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn current_exercise(&self) -> &Exercise {
|
pub fn current_exercise(&self) -> &Exercise {
|
||||||
&self.exercises[self.current_exercise_ind]
|
&self.exercises[self.current_exercise_ind]
|
||||||
|
@ -280,7 +284,7 @@ impl AppState {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the status of an exercise without saving. Returns `true` if the
|
// Set the status of an exercise without saving. Returns `true` if the
|
||||||
// status actually changed (and thus needs saving later)
|
// status actually changed (and thus needs saving later).
|
||||||
pub fn set_status(&mut self, exercise_ind: usize, done: bool) -> Result<bool> {
|
pub fn set_status(&mut self, exercise_ind: usize, done: bool) -> Result<bool> {
|
||||||
let exercise = self
|
let exercise = self
|
||||||
.exercises
|
.exercises
|
||||||
|
@ -288,23 +292,25 @@ impl AppState {
|
||||||
.context(BAD_INDEX_ERR)?;
|
.context(BAD_INDEX_ERR)?;
|
||||||
|
|
||||||
if exercise.done == done {
|
if exercise.done == done {
|
||||||
Ok(false)
|
return Ok(false);
|
||||||
} else {
|
}
|
||||||
|
|
||||||
exercise.done = done;
|
exercise.done = done;
|
||||||
if done {
|
if done {
|
||||||
self.n_done += 1;
|
self.n_done += 1;
|
||||||
} else {
|
} else {
|
||||||
self.n_done -= 1;
|
self.n_done -= 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Set the status of an exercise to "pending" and save
|
// Set the status of an exercise to "pending" and save.
|
||||||
pub fn set_pending(&mut self, exercise_ind: usize) -> Result<()> {
|
pub fn set_pending(&mut self, exercise_ind: usize) -> Result<()> {
|
||||||
if self.set_status(exercise_ind, false)? {
|
if self.set_status(exercise_ind, false)? {
|
||||||
self.write()?;
|
self.write()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -402,174 +408,114 @@ impl AppState {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return the exercise index of the first pending exercise found.
|
fn check_all_exercises_impl(&mut self, stdout: &mut StdoutLock) -> Result<Option<usize>> {
|
||||||
pub fn check_all_exercises(
|
let term_width = terminal::size()
|
||||||
&mut self,
|
.context("Failed to get the terminal size")?
|
||||||
stdout: &mut StdoutLock,
|
.0;
|
||||||
final_check: bool,
|
let mut progress_visualizer = CheckProgressVisualizer::build(stdout, term_width)?;
|
||||||
) -> Result<Option<usize>> {
|
|
||||||
if !final_check {
|
|
||||||
stdout.write_all(INTERMEDIATE_CHECK_MSG)?;
|
|
||||||
} else {
|
|
||||||
stdout.write_all(FINAL_CHECK_MSG)?;
|
|
||||||
}
|
|
||||||
let n_exercises = self.exercises.len();
|
|
||||||
|
|
||||||
let (mut checked_count, mut results) = thread::scope(|s| {
|
let next_exercise_ind = AtomicUsize::new(0);
|
||||||
let (tx, rx) = mpsc::channel();
|
let mut progresses = vec![CheckProgress::None; self.exercises.len()];
|
||||||
let exercise_ind = Arc::new(AtomicUsize::default());
|
|
||||||
|
|
||||||
let num_core = thread::available_parallelism()
|
thread::scope(|s| {
|
||||||
|
let (exercise_progress_sender, exercise_progress_receiver) = mpsc::channel();
|
||||||
|
let n_threads = thread::available_parallelism()
|
||||||
.map_or(DEFAULT_CHECK_PARALLELISM, |count| count.get());
|
.map_or(DEFAULT_CHECK_PARALLELISM, |count| count.get());
|
||||||
(0..num_core).for_each(|_| {
|
|
||||||
let tx = tx.clone();
|
for _ in 0..n_threads {
|
||||||
let exercise_ind = exercise_ind.clone();
|
let exercise_progress_sender = exercise_progress_sender.clone();
|
||||||
let this = &self;
|
let next_exercise_ind = &next_exercise_ind;
|
||||||
let _ = thread::Builder::new().spawn_scoped(s, move || {
|
let slf = &self;
|
||||||
loop {
|
thread::Builder::new()
|
||||||
let exercise_ind =
|
.spawn_scoped(s, move || loop {
|
||||||
exercise_ind.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
|
let exercise_ind = next_exercise_ind.fetch_add(1, Relaxed);
|
||||||
let Some(exercise) = this.exercises.get(exercise_ind) else {
|
let Some(exercise) = slf.exercises.get(exercise_ind) else {
|
||||||
// No more exercises
|
// No more exercises.
|
||||||
break;
|
break;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Notify the progress bar that this exercise is pending
|
if exercise_progress_sender
|
||||||
if tx.send((exercise_ind, None)).is_err() {
|
.send((exercise_ind, CheckProgress::Checking))
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
break;
|
break;
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = exercise.run_exercise(None, &this.cmd_runner);
|
let success = exercise.run_exercise(None, &slf.cmd_runner);
|
||||||
|
let progress = match success {
|
||||||
|
Ok(true) => CheckProgress::Done,
|
||||||
|
Ok(false) => CheckProgress::Pending,
|
||||||
|
Err(_) => CheckProgress::None,
|
||||||
|
};
|
||||||
|
|
||||||
// Notify the progress bar that this exercise is done
|
if exercise_progress_sender
|
||||||
if tx.send((exercise_ind, Some(result))).is_err() {
|
.send((exercise_ind, progress))
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
});
|
.context("Failed to spawn a thread to check all exercises")?;
|
||||||
});
|
|
||||||
|
|
||||||
// Drop this `tx`, since the `rx` loop will not stop while there is
|
|
||||||
// at least one tx alive (i.e. we want the loop to block only while
|
|
||||||
// there are `tx` clones, i.e. threads)
|
|
||||||
drop(tx);
|
|
||||||
|
|
||||||
// Print the legend
|
|
||||||
queue!(
|
|
||||||
stdout,
|
|
||||||
Print("Color legend: "),
|
|
||||||
SetForegroundColor(term::PROGRESS_FAILED_COLOR),
|
|
||||||
Print("Failure"),
|
|
||||||
ResetColor,
|
|
||||||
Print(" - "),
|
|
||||||
SetForegroundColor(term::PROGRESS_SUCCESS_COLOR),
|
|
||||||
Print("Success"),
|
|
||||||
ResetColor,
|
|
||||||
Print(" - "),
|
|
||||||
SetForegroundColor(term::PROGRESS_PENDING_COLOR),
|
|
||||||
Print("Checking"),
|
|
||||||
ResetColor,
|
|
||||||
Print("\n"),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
// We expect at least a few "pending" notifications shortly, so don't
|
|
||||||
// bother printing the initial state of the progress bar and flushing
|
|
||||||
// stdout
|
|
||||||
|
|
||||||
let line_width = terminal::size().unwrap().0;
|
|
||||||
let mut results = vec![AllExercisesResult::Pending; n_exercises];
|
|
||||||
let mut pending = 0;
|
|
||||||
let mut success = 0;
|
|
||||||
let mut failed = 0;
|
|
||||||
|
|
||||||
while let Ok((exercise_ind, result)) = rx.recv() {
|
|
||||||
match result {
|
|
||||||
None => {
|
|
||||||
pending += 1;
|
|
||||||
}
|
|
||||||
Some(Err(_)) => {
|
|
||||||
results[exercise_ind] = AllExercisesResult::Error;
|
|
||||||
}
|
|
||||||
Some(Ok(true)) => {
|
|
||||||
results[exercise_ind] = AllExercisesResult::Success;
|
|
||||||
pending -= 1;
|
|
||||||
success += 1;
|
|
||||||
}
|
|
||||||
Some(Ok(false)) => {
|
|
||||||
results[exercise_ind] = AllExercisesResult::Failed;
|
|
||||||
pending -= 1;
|
|
||||||
failed += 1;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
write!(stdout, "\r").unwrap();
|
// Drop this sender to detect when the last thread is done.
|
||||||
progress_bar_with_success(
|
drop(exercise_progress_sender);
|
||||||
stdout,
|
|
||||||
pending,
|
while let Ok((exercise_ind, progress)) = exercise_progress_receiver.recv() {
|
||||||
failed,
|
progresses[exercise_ind] = progress;
|
||||||
success,
|
progress_visualizer.update(&progresses)?;
|
||||||
n_exercises as u16,
|
|
||||||
line_width,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
stdout.flush()?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok::<_, io::Error>((success, results))
|
Ok::<_, Error>(())
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
let mut first_pending_exercise_ind = None;
|
||||||
|
for exercise_ind in 0..progresses.len() {
|
||||||
|
match progresses[exercise_ind] {
|
||||||
|
CheckProgress::Done => {
|
||||||
|
self.set_status(exercise_ind, true)?;
|
||||||
|
}
|
||||||
|
CheckProgress::Pending => {
|
||||||
|
self.set_status(exercise_ind, false)?;
|
||||||
|
if first_pending_exercise_ind.is_none() {
|
||||||
|
first_pending_exercise_ind = Some(exercise_ind);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CheckProgress::None | CheckProgress::Checking => {
|
||||||
// If we got an error while checking all exercises in parallel,
|
// If we got an error while checking all exercises in parallel,
|
||||||
// it could be because we exceeded the limit of open file descriptors.
|
// it could be because we exceeded the limit of open file descriptors.
|
||||||
// Therefore, re-try those one at a time (i.e. sequentially).
|
// Therefore, try running exercises with errors sequentially.
|
||||||
results
|
progresses[exercise_ind] = CheckProgress::Checking;
|
||||||
.iter_mut()
|
progress_visualizer.update(&progresses)?;
|
||||||
.enumerate()
|
|
||||||
.filter(|(_, result)| {
|
|
||||||
**result == AllExercisesResult::Pending || **result == AllExercisesResult::Error
|
|
||||||
})
|
|
||||||
.try_for_each(|(exercise_ind, result)| {
|
|
||||||
let exercise = self.exercises.get(exercise_ind).context(BAD_INDEX_ERR)?;
|
|
||||||
*result = match exercise
|
|
||||||
.run_exercise(None, &self.cmd_runner)
|
|
||||||
.context("Sequential retry")
|
|
||||||
{
|
|
||||||
Ok(true) => AllExercisesResult::Success,
|
|
||||||
Ok(false) => AllExercisesResult::Failed,
|
|
||||||
Err(err) => bail!(err),
|
|
||||||
};
|
|
||||||
checked_count += 1;
|
|
||||||
write!(stdout, "\rProgress: {checked_count}/{n_exercises}")?;
|
|
||||||
stdout.flush()?;
|
|
||||||
Ok(())
|
|
||||||
})?;
|
|
||||||
|
|
||||||
// Update the state of each exercise and return the first that failed
|
let exercise = &self.exercises[exercise_ind];
|
||||||
let first_fail = results
|
let success = exercise.run_exercise(None, &self.cmd_runner)?;
|
||||||
.iter()
|
if success {
|
||||||
.enumerate()
|
progresses[exercise_ind] = CheckProgress::Done;
|
||||||
.filter_map(|(exercise_ind, result)| {
|
} else {
|
||||||
match result {
|
progresses[exercise_ind] = CheckProgress::Pending;
|
||||||
AllExercisesResult::Success => self
|
if first_pending_exercise_ind.is_none() {
|
||||||
.set_status(exercise_ind, true)
|
first_pending_exercise_ind = Some(exercise_ind);
|
||||||
.map_or_else(|err| Some(Err(err)), |_| None),
|
|
||||||
AllExercisesResult::Failed => self
|
|
||||||
.set_status(exercise_ind, false)
|
|
||||||
.map_or_else(|err| Some(Err(err)), |_| Some(Ok(exercise_ind))),
|
|
||||||
// The sequential check done earlier will have converted all
|
|
||||||
// exercises to Success/Failed, or bailed, so those are unreachable
|
|
||||||
AllExercisesResult::Pending | AllExercisesResult::Error => unreachable!(),
|
|
||||||
}
|
}
|
||||||
})
|
|
||||||
.try_fold(None::<usize>, |current_min, index| {
|
|
||||||
match (current_min, index) {
|
|
||||||
(_, Err(err)) => Err(err),
|
|
||||||
(None, Ok(index)) => Ok(Some(index)),
|
|
||||||
(Some(current_min), Ok(index)) => Ok(Some(current_min.min(index))),
|
|
||||||
}
|
}
|
||||||
})?;
|
self.set_status(exercise_ind, success)?;
|
||||||
|
progress_visualizer.update(&progresses)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
self.write()?;
|
self.write()?;
|
||||||
|
|
||||||
Ok(first_fail)
|
Ok(first_pending_exercise_ind)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the exercise index of the first pending exercise found.
|
||||||
|
pub fn check_all_exercises(&mut self, stdout: &mut StdoutLock) -> Result<Option<usize>> {
|
||||||
|
stdout.queue(cursor::Hide)?;
|
||||||
|
let res = self.check_all_exercises_impl(stdout);
|
||||||
|
stdout.queue(cursor::Show)?;
|
||||||
|
|
||||||
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Mark the current exercise as done and move on to the next pending exercise if one exists.
|
/// Mark the current exercise as done and move on to the next pending exercise if one exists.
|
||||||
|
@ -596,18 +542,12 @@ impl AppState {
|
||||||
stdout.write_all(b"\n")?;
|
stdout.write_all(b"\n")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(pending_exercise_ind) = self.check_all_exercises(stdout, true)? {
|
if let Some(first_pending_exercise_ind) = self.check_all_exercises(stdout)? {
|
||||||
stdout.write_all(b"\n\n")?;
|
self.set_current_exercise_ind(first_pending_exercise_ind)?;
|
||||||
|
|
||||||
self.current_exercise_ind = pending_exercise_ind;
|
|
||||||
self.exercises[pending_exercise_ind].done = false;
|
|
||||||
|
|
||||||
return Ok(ExercisesProgress::NewPending);
|
return Ok(ExercisesProgress::NewPending);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write that the last exercise is done.
|
|
||||||
self.write()?;
|
|
||||||
|
|
||||||
self.render_final_message(stdout)?;
|
self.render_final_message(stdout)?;
|
||||||
|
|
||||||
Ok(ExercisesProgress::AllDone)
|
Ok(ExercisesProgress::AllDone)
|
||||||
|
@ -629,11 +569,6 @@ impl AppState {
|
||||||
|
|
||||||
const BAD_INDEX_ERR: &str = "The current exercise index is higher than the number of exercises";
|
const BAD_INDEX_ERR: &str = "The current exercise index is higher than the number of exercises";
|
||||||
const STATE_FILE_HEADER: &[u8] = b"DON'T EDIT THIS FILE!\n\n";
|
const STATE_FILE_HEADER: &[u8] = b"DON'T EDIT THIS FILE!\n\n";
|
||||||
const INTERMEDIATE_CHECK_MSG: &[u8] = b"Checking all exercises
|
|
||||||
";
|
|
||||||
const FINAL_CHECK_MSG: &[u8] = b"All exercises seem to be done.
|
|
||||||
Recompiling and running all exercises to make sure that all of them are actually done.
|
|
||||||
";
|
|
||||||
const FENISH_LINE: &str = "+----------------------------------------------------+
|
const FENISH_LINE: &str = "+----------------------------------------------------+
|
||||||
| You made it to the Fe-nish line! |
|
| You made it to the Fe-nish line! |
|
||||||
+-------------------------- ------------------------+
|
+-------------------------- ------------------------+
|
||||||
|
|
60
src/main.rs
60
src/main.rs
|
@ -1,14 +1,10 @@
|
||||||
use anyhow::{bail, Context, Result};
|
use anyhow::{bail, Context, Result};
|
||||||
use app_state::StateFileStatus;
|
use app_state::StateFileStatus;
|
||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
use crossterm::{
|
|
||||||
style::{Color, Print, ResetColor, SetForegroundColor},
|
|
||||||
QueueableCommand,
|
|
||||||
};
|
|
||||||
use std::{
|
use std::{
|
||||||
io::{self, IsTerminal, Write},
|
io::{self, IsTerminal, Write},
|
||||||
path::Path,
|
path::Path,
|
||||||
process::exit,
|
process::ExitCode,
|
||||||
};
|
};
|
||||||
use term::{clear_terminal, press_enter_prompt};
|
use term::{clear_terminal, press_enter_prompt};
|
||||||
|
|
||||||
|
@ -51,8 +47,8 @@ enum Subcommands {
|
||||||
/// The name of the exercise
|
/// The name of the exercise
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
},
|
},
|
||||||
/// Run all the exercises, marking them as done or pending accordingly.
|
/// Check all the exercises, marking them as done or pending accordingly.
|
||||||
RunAll,
|
CheckAll,
|
||||||
/// Reset a single exercise
|
/// Reset a single exercise
|
||||||
Reset {
|
Reset {
|
||||||
/// The name of the exercise
|
/// The name of the exercise
|
||||||
|
@ -68,22 +64,26 @@ enum Subcommands {
|
||||||
Dev(DevCommands),
|
Dev(DevCommands),
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<ExitCode> {
|
||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
|
|
||||||
if cfg!(not(debug_assertions)) && Path::new("dev/rustlings-repo.txt").exists() {
|
if cfg!(not(debug_assertions)) && Path::new("dev/rustlings-repo.txt").exists() {
|
||||||
bail!("{OLD_METHOD_ERR}");
|
bail!("{OLD_METHOD_ERR}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
'priority_cmd: {
|
||||||
match args.command {
|
match args.command {
|
||||||
Some(Subcommands::Init) => return init::init().context("Initialization failed"),
|
Some(Subcommands::Init) => init::init().context("Initialization failed")?,
|
||||||
Some(Subcommands::Dev(dev_command)) => return dev_command.run(),
|
Some(Subcommands::Dev(dev_command)) => dev_command.run()?,
|
||||||
_ => (),
|
_ => break 'priority_cmd,
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(ExitCode::SUCCESS);
|
||||||
}
|
}
|
||||||
|
|
||||||
if !Path::new("exercises").is_dir() {
|
if !Path::new("exercises").is_dir() {
|
||||||
println!("{PRE_INIT_MSG}");
|
println!("{PRE_INIT_MSG}");
|
||||||
exit(1);
|
return Ok(ExitCode::FAILURE);
|
||||||
}
|
}
|
||||||
|
|
||||||
let info_file = InfoFile::parse()?;
|
let info_file = InfoFile::parse()?;
|
||||||
|
@ -142,34 +142,32 @@ fn main() -> Result<()> {
|
||||||
if let Some(name) = name {
|
if let Some(name) = name {
|
||||||
app_state.set_current_exercise_by_name(&name)?;
|
app_state.set_current_exercise_by_name(&name)?;
|
||||||
}
|
}
|
||||||
run::run(&mut app_state)?;
|
return run::run(&mut app_state);
|
||||||
}
|
}
|
||||||
Some(Subcommands::RunAll) => {
|
Some(Subcommands::CheckAll) => {
|
||||||
let mut stdout = io::stdout().lock();
|
let mut stdout = io::stdout().lock();
|
||||||
if let Some(first_fail) = app_state.check_all_exercises(&mut stdout, false)? {
|
if let Some(first_pending_exercise_ind) = app_state.check_all_exercises(&mut stdout)? {
|
||||||
let pending = app_state
|
|
||||||
.exercises()
|
|
||||||
.iter()
|
|
||||||
.filter(|exercise| !exercise.done)
|
|
||||||
.count();
|
|
||||||
if app_state.current_exercise().done {
|
if app_state.current_exercise().done {
|
||||||
app_state.set_current_exercise_ind(first_fail)?;
|
app_state.set_current_exercise_ind(first_pending_exercise_ind)?;
|
||||||
}
|
}
|
||||||
stdout
|
|
||||||
.queue(Print("\n"))?
|
stdout.write_all(b"\n\n")?;
|
||||||
.queue(SetForegroundColor(Color::Red))?
|
let pending = app_state.n_pending();
|
||||||
.queue(Print(format!("{pending}")))?
|
|
||||||
.queue(ResetColor)?;
|
|
||||||
if pending == 1 {
|
if pending == 1 {
|
||||||
stdout.queue(Print(" exercise has some errors: "))?;
|
stdout.write_all(b"One exercise pending: ")?;
|
||||||
} else {
|
} else {
|
||||||
stdout.queue(Print(" exercises have errors, including "))?;
|
write!(
|
||||||
|
stdout,
|
||||||
|
"{pending}/{} exercises pending. The first: ",
|
||||||
|
app_state.exercises().len(),
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
app_state
|
app_state
|
||||||
.current_exercise()
|
.current_exercise()
|
||||||
.terminal_file_link(&mut stdout)?;
|
.terminal_file_link(&mut stdout)?;
|
||||||
stdout.write_all(b".\n")?;
|
stdout.write_all(b"\n")?;
|
||||||
exit(1);
|
|
||||||
|
return Ok(ExitCode::FAILURE);
|
||||||
} else {
|
} else {
|
||||||
app_state.render_final_message(&mut stdout)?;
|
app_state.render_final_message(&mut stdout)?;
|
||||||
}
|
}
|
||||||
|
@ -189,7 +187,7 @@ fn main() -> Result<()> {
|
||||||
Some(Subcommands::Init | Subcommands::Dev(_)) => (),
|
Some(Subcommands::Init | Subcommands::Dev(_)) => (),
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(ExitCode::SUCCESS)
|
||||||
}
|
}
|
||||||
|
|
||||||
const OLD_METHOD_ERR: &str =
|
const OLD_METHOD_ERR: &str =
|
||||||
|
|
|
@ -5,7 +5,7 @@ use crossterm::{
|
||||||
};
|
};
|
||||||
use std::{
|
use std::{
|
||||||
io::{self, Write},
|
io::{self, Write},
|
||||||
process::exit,
|
process::ExitCode,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
@ -13,7 +13,7 @@ use crate::{
|
||||||
exercise::{solution_link_line, RunnableExercise, OUTPUT_CAPACITY},
|
exercise::{solution_link_line, RunnableExercise, OUTPUT_CAPACITY},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn run(app_state: &mut AppState) -> Result<()> {
|
pub fn run(app_state: &mut AppState) -> Result<ExitCode> {
|
||||||
let exercise = app_state.current_exercise();
|
let exercise = app_state.current_exercise();
|
||||||
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
||||||
let success = exercise.run_exercise(Some(&mut output), app_state.cmd_runner())?;
|
let success = exercise.run_exercise(Some(&mut output), app_state.cmd_runner())?;
|
||||||
|
@ -29,7 +29,8 @@ pub fn run(app_state: &mut AppState) -> Result<()> {
|
||||||
.current_exercise()
|
.current_exercise()
|
||||||
.terminal_file_link(&mut stdout)?;
|
.terminal_file_link(&mut stdout)?;
|
||||||
stdout.write_all(b" with errors\n")?;
|
stdout.write_all(b" with errors\n")?;
|
||||||
exit(1);
|
|
||||||
|
return Ok(ExitCode::FAILURE);
|
||||||
}
|
}
|
||||||
|
|
||||||
stdout.queue(SetForegroundColor(Color::Green))?;
|
stdout.queue(SetForegroundColor(Color::Green))?;
|
||||||
|
@ -55,5 +56,5 @@ pub fn run(app_state: &mut AppState) -> Result<()> {
|
||||||
ExercisesProgress::AllDone => (),
|
ExercisesProgress::AllDone => (),
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(ExitCode::SUCCESS)
|
||||||
}
|
}
|
||||||
|
|
155
src/term.rs
155
src/term.rs
|
@ -1,6 +1,6 @@
|
||||||
use crossterm::{
|
use crossterm::{
|
||||||
cursor::MoveTo,
|
cursor::MoveTo,
|
||||||
style::{Attribute, Color, SetAttribute, SetForegroundColor},
|
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
|
||||||
terminal::{Clear, ClearType},
|
terminal::{Clear, ClearType},
|
||||||
Command, QueueableCommand,
|
Command, QueueableCommand,
|
||||||
};
|
};
|
||||||
|
@ -9,9 +9,7 @@ use std::{
|
||||||
io::{self, BufRead, StdoutLock, Write},
|
io::{self, BufRead, StdoutLock, Write},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const PROGRESS_FAILED_COLOR: Color = Color::Red;
|
use crate::app_state::CheckProgress;
|
||||||
pub const PROGRESS_SUCCESS_COLOR: Color = Color::Green;
|
|
||||||
pub const PROGRESS_PENDING_COLOR: Color = Color::Blue;
|
|
||||||
|
|
||||||
pub struct MaxLenWriter<'a, 'b> {
|
pub struct MaxLenWriter<'a, 'b> {
|
||||||
pub stdout: &'a mut StdoutLock<'b>,
|
pub stdout: &'a mut StdoutLock<'b>,
|
||||||
|
@ -89,26 +87,87 @@ impl<'a> CountedWrite<'a> for StdoutLock<'a> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Simple terminal progress bar
|
pub struct CheckProgressVisualizer<'a, 'b> {
|
||||||
|
stdout: &'a mut StdoutLock<'b>,
|
||||||
|
n_cols: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'b> CheckProgressVisualizer<'a, 'b> {
|
||||||
|
const CHECKING_COLOR: Color = Color::Blue;
|
||||||
|
const DONE_COLOR: Color = Color::Green;
|
||||||
|
const PENDING_COLOR: Color = Color::Red;
|
||||||
|
|
||||||
|
pub fn build(stdout: &'a mut StdoutLock<'b>, term_width: u16) -> io::Result<Self> {
|
||||||
|
clear_terminal(stdout)?;
|
||||||
|
stdout.write_all("Checking all exercises…\n".as_bytes())?;
|
||||||
|
|
||||||
|
// Legend
|
||||||
|
stdout.write_all(b"Color of exercise number: ")?;
|
||||||
|
stdout.queue(SetForegroundColor(Self::CHECKING_COLOR))?;
|
||||||
|
stdout.write_all(b"Checking")?;
|
||||||
|
stdout.queue(ResetColor)?;
|
||||||
|
stdout.write_all(b" - ")?;
|
||||||
|
stdout.queue(SetForegroundColor(Self::DONE_COLOR))?;
|
||||||
|
stdout.write_all(b"Done")?;
|
||||||
|
stdout.queue(ResetColor)?;
|
||||||
|
stdout.write_all(b" - ")?;
|
||||||
|
stdout.queue(SetForegroundColor(Self::PENDING_COLOR))?;
|
||||||
|
stdout.write_all(b"Pending")?;
|
||||||
|
stdout.queue(ResetColor)?;
|
||||||
|
stdout.write_all(b"\n")?;
|
||||||
|
|
||||||
|
// Exercise numbers with up to 3 digits.
|
||||||
|
// +1 because the last column doesn't end with a whitespace.
|
||||||
|
let n_cols = usize::from(term_width + 1) / 4;
|
||||||
|
|
||||||
|
Ok(Self { stdout, n_cols })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&mut self, progresses: &[CheckProgress]) -> io::Result<()> {
|
||||||
|
self.stdout.queue(MoveTo(0, 2))?;
|
||||||
|
|
||||||
|
let mut exercise_num = 1;
|
||||||
|
for exercise_progress in progresses {
|
||||||
|
match exercise_progress {
|
||||||
|
CheckProgress::None => (),
|
||||||
|
CheckProgress::Checking => {
|
||||||
|
self.stdout
|
||||||
|
.queue(SetForegroundColor(Self::CHECKING_COLOR))?;
|
||||||
|
}
|
||||||
|
CheckProgress::Done => {
|
||||||
|
self.stdout.queue(SetForegroundColor(Self::DONE_COLOR))?;
|
||||||
|
}
|
||||||
|
CheckProgress::Pending => {
|
||||||
|
self.stdout.queue(SetForegroundColor(Self::PENDING_COLOR))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
write!(self.stdout, "{exercise_num:<3}")?;
|
||||||
|
self.stdout.queue(ResetColor)?;
|
||||||
|
|
||||||
|
if exercise_num != progresses.len() {
|
||||||
|
if exercise_num % self.n_cols == 0 {
|
||||||
|
self.stdout.write_all(b"\n")?;
|
||||||
|
} else {
|
||||||
|
self.stdout.write_all(b" ")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
exercise_num += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.stdout.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn progress_bar<'a>(
|
pub fn progress_bar<'a>(
|
||||||
writer: &mut impl CountedWrite<'a>,
|
writer: &mut impl CountedWrite<'a>,
|
||||||
progress: u16,
|
progress: u16,
|
||||||
total: u16,
|
total: u16,
|
||||||
line_width: u16,
|
term_width: u16,
|
||||||
) -> io::Result<()> {
|
|
||||||
progress_bar_with_success(writer, 0, 0, progress, total, line_width)
|
|
||||||
}
|
|
||||||
/// Terminal progress bar with three states (pending + failed + success)
|
|
||||||
pub fn progress_bar_with_success<'a>(
|
|
||||||
writer: &mut impl CountedWrite<'a>,
|
|
||||||
pending: u16,
|
|
||||||
failed: u16,
|
|
||||||
success: u16,
|
|
||||||
total: u16,
|
|
||||||
line_width: u16,
|
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
debug_assert!(total < 1000);
|
debug_assert!(total < 1000);
|
||||||
debug_assert!((pending + failed + success) <= total);
|
debug_assert!(progress <= total);
|
||||||
|
|
||||||
const PREFIX: &[u8] = b"Progress: [";
|
const PREFIX: &[u8] = b"Progress: [";
|
||||||
const PREFIX_WIDTH: u16 = PREFIX.len() as u16;
|
const PREFIX_WIDTH: u16 = PREFIX.len() as u16;
|
||||||
|
@ -116,70 +175,28 @@ pub fn progress_bar_with_success<'a>(
|
||||||
const WRAPPER_WIDTH: u16 = PREFIX_WIDTH + POSTFIX_WIDTH;
|
const WRAPPER_WIDTH: u16 = PREFIX_WIDTH + POSTFIX_WIDTH;
|
||||||
const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4;
|
const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4;
|
||||||
|
|
||||||
if line_width < MIN_LINE_WIDTH {
|
if term_width < MIN_LINE_WIDTH {
|
||||||
writer.write_ascii(b"Progress: ")?;
|
writer.write_ascii(b"Progress: ")?;
|
||||||
// Integers are in ASCII.
|
// Integers are in ASCII.
|
||||||
return writer.write_ascii(format!("{}/{total}", failed + success).as_bytes());
|
return writer.write_ascii(format!("{progress}/{total}").as_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
let stdout = writer.stdout();
|
let stdout = writer.stdout();
|
||||||
stdout.write_all(PREFIX)?;
|
stdout.write_all(PREFIX)?;
|
||||||
|
|
||||||
let width = line_width - WRAPPER_WIDTH;
|
let width = term_width - WRAPPER_WIDTH;
|
||||||
let mut failed_end = (width * failed) / total;
|
let filled = (width * progress) / total;
|
||||||
let mut success_end = (width * (failed + success)) / total;
|
|
||||||
let mut pending_end = (width * (failed + success + pending)) / total;
|
|
||||||
|
|
||||||
// In case the range boundaries overlap, "pending" has priority over both
|
stdout.queue(SetForegroundColor(Color::Green))?;
|
||||||
// "failed" and "success" (don't show the bar as "complete" when we are
|
for _ in 0..filled {
|
||||||
// still checking some things).
|
|
||||||
// "Failed" has priority over "success" (don't show 100% success if we
|
|
||||||
// have some failures, at the risk of showing 100% failures even with
|
|
||||||
// a few successes).
|
|
||||||
//
|
|
||||||
// "Failed" already has priority over "success" because it's displayed
|
|
||||||
// first. But "pending" is last so we need to fix "success"/"failed".
|
|
||||||
if pending > 0 {
|
|
||||||
pending_end = pending_end.max(1);
|
|
||||||
if pending_end == success_end {
|
|
||||||
success_end -= 1;
|
|
||||||
}
|
|
||||||
if pending_end == failed_end {
|
|
||||||
failed_end -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// This will replace the last character of the "pending" range with
|
|
||||||
// the arrow char ('>'). This ensures that even if the progress bar
|
|
||||||
// is filled (everything either done or pending), we'll still see
|
|
||||||
// the '>' as long as we are not fully done.
|
|
||||||
pending_end -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if failed > 0 {
|
|
||||||
stdout.queue(SetForegroundColor(PROGRESS_FAILED_COLOR))?;
|
|
||||||
for _ in 0..failed_end {
|
|
||||||
stdout.write_all(b"#")?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stdout.queue(SetForegroundColor(PROGRESS_SUCCESS_COLOR))?;
|
|
||||||
for _ in failed_end..success_end {
|
|
||||||
stdout.write_all(b"#")?;
|
stdout.write_all(b"#")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if pending > 0 {
|
if filled < width {
|
||||||
stdout.queue(SetForegroundColor(PROGRESS_PENDING_COLOR))?;
|
|
||||||
|
|
||||||
for _ in success_end..pending_end {
|
|
||||||
stdout.write_all(b"#")?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if pending_end < width {
|
|
||||||
stdout.write_all(b">")?;
|
stdout.write_all(b">")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let width_minus_filled = width - pending_end;
|
let width_minus_filled = width - filled;
|
||||||
if width_minus_filled > 1 {
|
if width_minus_filled > 1 {
|
||||||
let red_part_width = width_minus_filled - 1;
|
let red_part_width = width_minus_filled - 1;
|
||||||
stdout.queue(SetForegroundColor(Color::Red))?;
|
stdout.queue(SetForegroundColor(Color::Red))?;
|
||||||
|
@ -190,7 +207,7 @@ pub fn progress_bar_with_success<'a>(
|
||||||
|
|
||||||
stdout.queue(SetForegroundColor(Color::Reset))?;
|
stdout.queue(SetForegroundColor(Color::Reset))?;
|
||||||
|
|
||||||
write!(stdout, "] {:>3}/{}", failed + success, total)
|
write!(stdout, "] {progress:>3}/{total}")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn clear_terminal(stdout: &mut StdoutLock) -> io::Result<()> {
|
pub fn clear_terminal(stdout: &mut StdoutLock) -> io::Result<()> {
|
||||||
|
|
|
@ -108,7 +108,7 @@ fn run_watch(
|
||||||
{
|
{
|
||||||
ExercisesProgress::AllDone => break,
|
ExercisesProgress::AllDone => break,
|
||||||
ExercisesProgress::NewPending => watch_state.run_current_exercise(&mut stdout)?,
|
ExercisesProgress::NewPending => watch_state.run_current_exercise(&mut stdout)?,
|
||||||
ExercisesProgress::CurrentPending => (),
|
ExercisesProgress::CurrentPending => watch_state.render(&mut stdout)?,
|
||||||
},
|
},
|
||||||
WatchEvent::Input(InputEvent::Reset) => watch_state.reset_exercise(&mut stdout)?,
|
WatchEvent::Input(InputEvent::Reset) => watch_state.reset_exercise(&mut stdout)?,
|
||||||
WatchEvent::Input(InputEvent::Quit) => {
|
WatchEvent::Input(InputEvent::Quit) => {
|
||||||
|
|
|
@ -157,8 +157,9 @@ impl<'a> WatchState<'a> {
|
||||||
|
|
||||||
/// Move on to the next exercise if the current one is done.
|
/// Move on to the next exercise if the current one is done.
|
||||||
pub fn next_exercise(&mut self, stdout: &mut StdoutLock) -> Result<ExercisesProgress> {
|
pub fn next_exercise(&mut self, stdout: &mut StdoutLock) -> Result<ExercisesProgress> {
|
||||||
if self.done_status == DoneStatus::Pending {
|
match self.done_status {
|
||||||
return Ok(ExercisesProgress::CurrentPending);
|
DoneStatus::DoneWithSolution(_) | DoneStatus::DoneWithoutSolution => (),
|
||||||
|
DoneStatus::Pending => return Ok(ExercisesProgress::CurrentPending),
|
||||||
}
|
}
|
||||||
|
|
||||||
self.app_state.done_current_exercise::<true>(stdout)
|
self.app_state.done_current_exercise::<true>(stdout)
|
||||||
|
@ -280,16 +281,15 @@ impl<'a> WatchState<'a> {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn check_all_exercises(&mut self, stdout: &mut StdoutLock) -> Result<ExercisesProgress> {
|
pub fn check_all_exercises(&mut self, stdout: &mut StdoutLock) -> Result<ExercisesProgress> {
|
||||||
stdout.write_all(b"\n")?;
|
if let Some(first_pending_exercise_ind) = self.app_state.check_all_exercises(stdout)? {
|
||||||
|
// Only change exercise if the current one is done.
|
||||||
if let Some(first_fail) = self.app_state.check_all_exercises(stdout, false)? {
|
|
||||||
// Only change exercise if the current one is done...
|
|
||||||
if self.app_state.current_exercise().done {
|
if self.app_state.current_exercise().done {
|
||||||
self.app_state.set_current_exercise_ind(first_fail)?;
|
self.app_state
|
||||||
}
|
.set_current_exercise_ind(first_pending_exercise_ind)?;
|
||||||
// ...but always pretend it's a "new" anyway because that refreshes
|
|
||||||
// the display
|
|
||||||
Ok(ExercisesProgress::NewPending)
|
Ok(ExercisesProgress::NewPending)
|
||||||
|
} else {
|
||||||
|
Ok(ExercisesProgress::CurrentPending)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
self.app_state.render_final_message(stdout)?;
|
self.app_state.render_final_message(stdout)?;
|
||||||
Ok(ExercisesProgress::AllDone)
|
Ok(ExercisesProgress::AllDone)
|
||||||
|
|
Loading…
Reference in a new issue