rustlings/src/verify.rs

224 lines
6.6 KiB
Rust
Raw Normal View History

2024-03-31 10:55:33 -04:00
use anyhow::{bail, Result};
use console::style;
use indicatif::{ProgressBar, ProgressStyle};
2024-03-31 10:55:33 -04:00
use std::{
env,
io::{stdout, Write},
process::Output,
time::Duration,
};
use crate::exercise::{Exercise, Mode, State};
2019-01-09 14:33:43 -05:00
2024-04-01 12:38:01 -04:00
pub enum VerifyState<'a> {
AllExercisesDone,
Failed(&'a Exercise),
}
// Verify that the provided container of Exercise objects
// can be compiled and run without any failures.
// Any such failures will be reported to the end user.
// If the Exercise being verified is a test, the verbose boolean
// determines whether or not the test harness outputs are displayed.
pub fn verify<'a>(
2024-04-01 12:21:56 -04:00
pending_exercises: impl IntoIterator<Item = &'a Exercise>,
progress: (usize, usize),
2020-08-10 10:42:54 -04:00
verbose: bool,
success_hints: bool,
2024-04-01 12:38:01 -04:00
) -> Result<VerifyState<'a>> {
2023-02-27 15:17:45 -05:00
let (num_done, total) = progress;
let bar = ProgressBar::new(total as u64);
2023-02-27 15:17:45 -05:00
let mut percentage = num_done as f32 / total as f32 * 100.0;
2023-08-26 17:35:07 -04:00
bar.set_style(
ProgressStyle::default_bar()
.template("Progress: [{bar:60.green/red}] {pos}/{len} {msg}")
.expect("Progressbar template should be valid!")
.progress_chars("#>-"),
);
bar.set_position(num_done as u64);
2024-03-26 12:49:05 -04:00
bar.set_message(format!("({percentage:.1} %)"));
2024-04-01 12:21:56 -04:00
for exercise in pending_exercises {
2019-11-18 12:11:22 -05:00
let compile_result = match exercise.mode {
2024-04-01 12:38:01 -04:00
Mode::Test => compile_and_test(exercise, RunMode::Interactive, verbose, success_hints)?,
Mode::Compile => compile_and_run_interactively(exercise, success_hints)?,
Mode::Clippy => compile_only(exercise, success_hints)?,
};
2024-04-01 12:38:01 -04:00
if !compile_result {
return Ok(VerifyState::Failed(exercise));
}
2023-02-27 15:17:45 -05:00
percentage += 100.0 / total as f32;
bar.inc(1);
2024-03-26 12:49:05 -04:00
bar.set_message(format!("({percentage:.1} %)"));
}
2024-04-01 12:21:56 -04:00
bar.finish();
println!("You completed all exercises!");
2024-04-01 12:38:01 -04:00
Ok(VerifyState::AllExercisesDone)
2019-01-09 14:33:43 -05:00
}
2024-03-26 12:49:48 -04:00
#[derive(PartialEq, Eq)]
enum RunMode {
Interactive,
NonInteractive,
}
// Compile and run the resulting test harness of the given Exercise
2024-03-31 10:55:33 -04:00
pub fn test(exercise: &Exercise, verbose: bool) -> Result<()> {
compile_and_test(exercise, RunMode::NonInteractive, verbose, false)?;
Ok(())
}
// Invoke the rust compiler without running the resulting binary
2024-03-31 10:55:33 -04:00
fn compile_only(exercise: &Exercise, success_hints: bool) -> Result<bool> {
2019-03-11 10:09:20 -04:00
let progress_bar = ProgressBar::new_spinner();
progress_bar.set_message(format!("Compiling {exercise}..."));
2023-08-26 17:35:07 -04:00
progress_bar.enable_steady_tick(Duration::from_millis(100));
2024-03-31 10:55:33 -04:00
let _ = exercise.run()?;
2019-03-11 10:09:20 -04:00
progress_bar.finish_and_clear();
2019-01-09 14:33:43 -05:00
2024-03-31 12:25:54 -04:00
prompt_for_completion(exercise, None, success_hints)
}
// Compile the given Exercise and run the resulting binary in an interactive mode
2024-03-31 10:55:33 -04:00
fn compile_and_run_interactively(exercise: &Exercise, success_hints: bool) -> Result<bool> {
2019-03-11 10:09:20 -04:00
let progress_bar = ProgressBar::new_spinner();
2024-03-31 10:55:33 -04:00
progress_bar.set_message(format!("Running {exercise}..."));
2023-08-26 17:35:07 -04:00
progress_bar.enable_steady_tick(Duration::from_millis(100));
2024-03-31 10:55:33 -04:00
let output = exercise.run()?;
progress_bar.finish_and_clear();
2024-03-31 10:55:33 -04:00
if !output.status.success() {
warn!("Ran {} with errors", exercise);
{
let mut stdout = stdout().lock();
stdout.write_all(&output.stdout)?;
stdout.write_all(&output.stderr)?;
stdout.flush()?;
}
2024-03-31 10:55:33 -04:00
bail!("TODO");
}
2024-03-31 12:25:54 -04:00
prompt_for_completion(exercise, Some(output), success_hints)
}
// Compile the given Exercise as a test harness and display
// the output if verbose is set to true
2023-08-26 17:35:07 -04:00
fn compile_and_test(
exercise: &Exercise,
run_mode: RunMode,
verbose: bool,
success_hints: bool,
2024-03-31 10:55:33 -04:00
) -> Result<bool> {
let progress_bar = ProgressBar::new_spinner();
progress_bar.set_message(format!("Testing {exercise}..."));
2023-08-26 17:35:07 -04:00
progress_bar.enable_steady_tick(Duration::from_millis(100));
2024-03-31 10:55:33 -04:00
let output = exercise.run()?;
progress_bar.finish_and_clear();
2024-03-31 10:55:33 -04:00
if !output.status.success() {
warn!(
"Testing of {} failed! Please try again. Here's the output:",
exercise
);
{
let mut stdout = stdout().lock();
stdout.write_all(&output.stdout)?;
stdout.write_all(&output.stderr)?;
stdout.flush()?;
}
2024-03-31 10:55:33 -04:00
bail!("TODO");
2019-01-09 14:33:43 -05:00
}
2024-03-31 10:55:33 -04:00
if verbose {
stdout().write_all(&output.stdout)?;
}
if run_mode == RunMode::Interactive {
2024-03-31 12:25:54 -04:00
prompt_for_completion(exercise, None, success_hints)
2024-03-31 10:55:33 -04:00
} else {
Ok(true)
}
}
2023-08-26 17:35:07 -04:00
fn prompt_for_completion(
exercise: &Exercise,
2024-03-31 10:55:33 -04:00
prompt_output: Option<Output>,
2023-08-26 17:35:07 -04:00
success_hints: bool,
2024-03-31 12:25:54 -04:00
) -> Result<bool> {
let context = match exercise.state()? {
State::Done => return Ok(true),
State::Pending(context) => context,
};
match exercise.mode {
Mode::Compile => success!("Successfully ran {}!", exercise),
Mode::Test => success!("Successfully tested {}!", exercise),
Mode::Clippy => success!("Successfully compiled {}!", exercise),
}
let no_emoji = env::var("NO_EMOJI").is_ok();
let clippy_success_msg = if no_emoji {
"The code is compiling, and Clippy is happy!"
} else {
"The code is compiling, and 📎 Clippy 📎 is happy!"
};
let success_msg = match exercise.mode {
Mode::Compile => "The code is compiling!",
Mode::Test => "The code is compiling, and the tests pass!",
Mode::Clippy => clippy_success_msg,
};
2024-03-26 12:49:05 -04:00
if no_emoji {
2024-03-26 12:49:05 -04:00
println!("\n~*~ {success_msg} ~*~\n");
} else {
2024-03-29 14:29:38 -04:00
println!("\n🎉 🎉 {success_msg} 🎉 🎉\n");
}
if let Some(output) = prompt_output {
2024-03-31 10:55:33 -04:00
let separator = separator();
println!("Output:\n{separator}");
stdout().write_all(&output.stdout).unwrap();
println!("\n{separator}\n");
}
if success_hints {
2024-03-26 12:49:05 -04:00
println!(
"Hints:\n{separator}\n{}\n{separator}\n",
exercise.hint,
separator = separator(),
);
}
println!("You can keep working on this exercise,");
println!(
"or jump into the next one by removing the {} comment:",
style("`I AM NOT DONE`").bold()
);
println!();
for context_line in context {
let formatted_line = if context_line.important {
format!("{}", style(context_line.line).bold())
} else {
2024-03-23 17:08:25 -04:00
context_line.line
};
println!(
"{:>2} {} {}",
style(context_line.number).blue().bold(),
style("|").blue(),
2024-03-26 12:49:05 -04:00
formatted_line,
);
}
2024-03-31 12:25:54 -04:00
Ok(false)
}
fn separator() -> console::StyledObject<&'static str> {
style("====================").bold()
}