1
0
mirror of https://github.com/rust-lang/rustlings.git synced 2024-11-08 09:09:17 +01:00

Check that all solutions run successfully

This commit is contained in:
mo8it 2024-06-01 21:48:15 +02:00
parent 8e9c99ae5b
commit 611f9d8722
7 changed files with 169 additions and 86 deletions

@ -11,7 +11,7 @@ use std::{
use crate::{ use crate::{
clear_terminal, clear_terminal,
embedded::EMBEDDED_FILES, embedded::EMBEDDED_FILES,
exercise::{Exercise, OUTPUT_CAPACITY}, exercise::{Exercise, RunnableExercise, OUTPUT_CAPACITY},
info_file::ExerciseInfo, info_file::ExerciseInfo,
DEBUG_PROFILE, DEBUG_PROFILE,
}; };
@ -40,6 +40,25 @@ struct CargoMetadata {
target_directory: PathBuf, target_directory: PathBuf,
} }
pub fn parse_target_dir() -> Result<PathBuf> {
// Get the target directory from Cargo.
let metadata_output = Command::new("cargo")
.arg("metadata")
.arg("-q")
.arg("--format-version")
.arg("1")
.arg("--no-deps")
.stdin(Stdio::null())
.stderr(Stdio::inherit())
.output()
.context(CARGO_METADATA_ERR)?
.stdout;
serde_json::de::from_slice::<CargoMetadata>(&metadata_output)
.context("Failed to read the field `target_directory` from the `cargo metadata` output")
.map(|metadata| metadata.target_directory)
}
pub struct AppState { pub struct AppState {
current_exercise_ind: usize, current_exercise_ind: usize,
exercises: Vec<Exercise>, exercises: Vec<Exercise>,
@ -104,23 +123,7 @@ impl AppState {
exercise_infos: Vec<ExerciseInfo>, exercise_infos: Vec<ExerciseInfo>,
final_message: String, final_message: String,
) -> Result<(Self, StateFileStatus)> { ) -> Result<(Self, StateFileStatus)> {
// Get the target directory from Cargo. let target_dir = parse_target_dir()?;
let metadata_output = Command::new("cargo")
.arg("metadata")
.arg("-q")
.arg("--format-version")
.arg("1")
.arg("--no-deps")
.stdin(Stdio::null())
.stderr(Stdio::inherit())
.output()
.context(CARGO_METADATA_ERR)?
.stdout;
let target_dir = serde_json::de::from_slice::<CargoMetadata>(&metadata_output)
.context(
"Failed to read the field `target_directory` from the `cargo metadata` output",
)?
.target_directory;
let exercises = exercise_infos let exercises = exercise_infos
.into_iter() .into_iter()
@ -381,7 +384,7 @@ impl AppState {
write!(writer, "Running {exercise} ... ")?; write!(writer, "Running {exercise} ... ")?;
writer.flush()?; writer.flush()?;
let success = exercise.run(&mut output, &self.target_dir)?; let success = exercise.run_exercise(&mut output, &self.target_dir)?;
if !success { if !success {
writeln!(writer, "{}\n", "FAILED".red())?; writeln!(writer, "{}\n", "FAILED".red())?;

@ -35,7 +35,7 @@ pub fn run_cmd(mut cmd: Command, description: &str, output: &mut Vec<u8>) -> Res
pub struct CargoCmd<'a> { pub struct CargoCmd<'a> {
pub subcommand: &'a str, pub subcommand: &'a str,
pub args: &'a [&'a str], pub args: &'a [&'a str],
pub exercise_name: &'a str, pub bin_name: &'a str,
pub description: &'a str, pub description: &'a str,
/// RUSTFLAGS="-A warnings" /// RUSTFLAGS="-A warnings"
pub hide_warnings: bool, pub hide_warnings: bool,
@ -65,7 +65,7 @@ impl<'a> CargoCmd<'a> {
.arg("always") .arg("always")
.arg("-q") .arg("-q")
.arg("--bin") .arg("--bin")
.arg(self.exercise_name) .arg(self.bin_name)
.args(self.args); .args(self.args);
if self.hide_warnings { if self.hide_warnings {

@ -2,12 +2,14 @@ use anyhow::{anyhow, bail, Context, Error, Result};
use std::{ use std::{
cmp::Ordering, cmp::Ordering,
fs::{self, read_dir, OpenOptions}, fs::{self, read_dir, OpenOptions},
io::Read, io::{self, Read, Write},
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use crate::{ use crate::{
app_state::parse_target_dir,
cargo_toml::{append_bins, bins_start_end_ind, BINS_BUFFER_CAPACITY}, cargo_toml::{append_bins, bins_start_end_ind, BINS_BUFFER_CAPACITY},
exercise::{RunnableExercise, OUTPUT_CAPACITY},
info_file::{ExerciseInfo, InfoFile}, info_file::{ExerciseInfo, InfoFile},
CURRENT_FORMAT_VERSION, DEBUG_PROFILE, CURRENT_FORMAT_VERSION, DEBUG_PROFILE,
}; };
@ -17,6 +19,29 @@ fn forbidden_char(input: &str) -> Option<char> {
input.chars().find(|c| !c.is_alphanumeric() && *c != '_') input.chars().find(|c| !c.is_alphanumeric() && *c != '_')
} }
// Check that the Cargo.toml file is up-to-date.
fn check_cargo_toml(
exercise_infos: &[ExerciseInfo],
current_cargo_toml: &str,
exercise_path_prefix: &[u8],
) -> Result<()> {
let (bins_start_ind, bins_end_ind) = bins_start_end_ind(current_cargo_toml)?;
let old_bins = &current_cargo_toml.as_bytes()[bins_start_ind..bins_end_ind];
let mut new_bins = Vec::with_capacity(BINS_BUFFER_CAPACITY);
append_bins(&mut new_bins, exercise_infos, exercise_path_prefix);
if old_bins != new_bins {
if DEBUG_PROFILE {
bail!("The file `dev/Cargo.toml` is outdated. Please run `cargo run -- dev update` to update it");
}
bail!("The file `Cargo.toml` is outdated. Please run `rustlings dev update` to update it");
}
Ok(())
}
// Check the info of all exercises and return their paths in a set. // Check the info of all exercises and return their paths in a set.
fn check_info_file_exercises(info_file: &InfoFile) -> Result<hashbrown::HashSet<PathBuf>> { fn check_info_file_exercises(info_file: &InfoFile) -> Result<hashbrown::HashSet<PathBuf>> {
let mut names = hashbrown::HashSet::with_capacity(info_file.exercises.len()); let mut names = hashbrown::HashSet::with_capacity(info_file.exercises.len());
@ -136,24 +161,20 @@ fn check_exercises(info_file: &InfoFile) -> Result<()> {
Ok(()) Ok(())
} }
// Check that the Cargo.toml file is up-to-date. fn check_solutions(info_file: &InfoFile) -> Result<()> {
fn check_cargo_toml( let target_dir = parse_target_dir()?;
exercise_infos: &[ExerciseInfo], let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
current_cargo_toml: &str,
exercise_path_prefix: &[u8],
) -> Result<()> {
let (bins_start_ind, bins_end_ind) = bins_start_end_ind(current_cargo_toml)?;
let old_bins = &current_cargo_toml.as_bytes()[bins_start_ind..bins_end_ind]; for exercise_info in &info_file.exercises {
let mut new_bins = Vec::with_capacity(BINS_BUFFER_CAPACITY); let success = exercise_info.run_solution(&mut output, &target_dir)?;
append_bins(&mut new_bins, exercise_infos, exercise_path_prefix); if !success {
io::stderr().write_all(&output)?;
if old_bins != new_bins { bail!(
if DEBUG_PROFILE { "Failed to run the solution of the exercise {}",
bail!("The file `dev/Cargo.toml` is outdated. Please run `cargo run -- dev update` to update it"); exercise_info.name,
);
} }
bail!("The file `Cargo.toml` is outdated. Please run `rustlings dev update` to update it");
} }
Ok(()) Ok(())
@ -161,7 +182,6 @@ fn check_cargo_toml(
pub fn check() -> Result<()> { pub fn check() -> Result<()> {
let info_file = InfoFile::parse()?; let info_file = InfoFile::parse()?;
check_exercises(&info_file)?;
// A hack to make `cargo run -- dev check` work when developing Rustlings. // A hack to make `cargo run -- dev check` work when developing Rustlings.
if DEBUG_PROFILE { if DEBUG_PROFILE {
@ -176,6 +196,9 @@ pub fn check() -> Result<()> {
check_cargo_toml(&info_file.exercises, &current_cargo_toml, b"")?; check_cargo_toml(&info_file.exercises, &current_cargo_toml, b"")?;
} }
check_exercises(&info_file)?;
check_solutions(&info_file)?;
println!("\nEverything looks fine!"); println!("\nEverything looks fine!");
Ok(()) Ok(())

@ -17,30 +17,16 @@ use crate::{
/// The initial capacity of the output buffer. /// The initial capacity of the output buffer.
pub const OUTPUT_CAPACITY: usize = 1 << 14; pub const OUTPUT_CAPACITY: usize = 1 << 14;
/// See `info_file::ExerciseInfo` // Run an exercise binary and append its output to the `output` buffer.
pub struct Exercise { // Compilation must be done before calling this method.
pub dir: Option<&'static str>, fn run_bin(bin_name: &str, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
pub name: &'static str,
/// Path of the exercise file starting with the `exercises/` directory.
pub path: &'static str,
pub test: bool,
pub strict_clippy: bool,
pub hint: String,
pub done: bool,
}
impl Exercise {
// Run the exercise's binary and append its output to the `output` buffer.
// Compilation should be done before calling this method.
fn run_bin(&self, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
writeln!(output, "{}", "Output".underlined())?; writeln!(output, "{}", "Output".underlined())?;
// 7 = "/debug/".len() // 7 = "/debug/".len()
let mut bin_path = let mut bin_path = PathBuf::with_capacity(target_dir.as_os_str().len() + 7 + bin_name.len());
PathBuf::with_capacity(target_dir.as_os_str().len() + 7 + self.name.len());
bin_path.push(target_dir); bin_path.push(target_dir);
bin_path.push("debug"); bin_path.push("debug");
bin_path.push(self.name); bin_path.push(bin_name);
let success = run_cmd(Command::new(&bin_path), &bin_path.to_string_lossy(), output)?; let success = run_cmd(Command::new(&bin_path), &bin_path.to_string_lossy(), output)?;
@ -60,9 +46,38 @@ impl Exercise {
Ok(success) Ok(success)
} }
/// Compile, check and run the exercise. /// See `info_file::ExerciseInfo`
/// The output is written to the `output` buffer after clearing it. pub struct Exercise {
pub fn run(&self, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> { pub dir: Option<&'static str>,
pub name: &'static str,
/// Path of the exercise file starting with the `exercises/` directory.
pub path: &'static str,
pub test: bool,
pub strict_clippy: bool,
pub hint: String,
pub done: bool,
}
impl Exercise {
pub fn terminal_link(&self) -> StyledContent<TerminalFileLink<'_>> {
style(TerminalFileLink(self.path)).underlined().blue()
}
}
impl Display for Exercise {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.path.fmt(f)
}
}
pub trait RunnableExercise {
fn name(&self) -> &str;
fn strict_clippy(&self) -> bool;
fn test(&self) -> bool;
// Compile, check and run the exercise or its solution (depending on `bin_name´).
// The output is written to the `output` buffer after clearing it.
fn run(&self, bin_name: &str, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
output.clear(); output.clear();
// Developing the official Rustlings. // Developing the official Rustlings.
@ -71,7 +86,7 @@ impl Exercise {
let build_success = CargoCmd { let build_success = CargoCmd {
subcommand: "build", subcommand: "build",
args: &[], args: &[],
exercise_name: self.name, bin_name,
description: "cargo build …", description: "cargo build …",
hide_warnings: false, hide_warnings: false,
target_dir, target_dir,
@ -87,7 +102,7 @@ impl Exercise {
output.clear(); output.clear();
// `--profile test` is required to also check code with `[cfg(test)]`. // `--profile test` is required to also check code with `[cfg(test)]`.
let clippy_args: &[&str] = if self.strict_clippy { let clippy_args: &[&str] = if self.strict_clippy() {
&["--profile", "test", "--", "-D", "warnings"] &["--profile", "test", "--", "-D", "warnings"]
} else { } else {
&["--profile", "test"] &["--profile", "test"]
@ -95,7 +110,7 @@ impl Exercise {
let clippy_success = CargoCmd { let clippy_success = CargoCmd {
subcommand: "clippy", subcommand: "clippy",
args: clippy_args, args: clippy_args,
exercise_name: self.name, bin_name,
description: "cargo clippy …", description: "cargo clippy …",
hide_warnings: false, hide_warnings: false,
target_dir, target_dir,
@ -107,14 +122,14 @@ impl Exercise {
return Ok(false); return Ok(false);
} }
if !self.test { if !self.test() {
return self.run_bin(output, target_dir); return run_bin(bin_name, output, target_dir);
} }
let test_success = CargoCmd { let test_success = CargoCmd {
subcommand: "test", subcommand: "test",
args: &["--", "--color", "always", "--show-output"], args: &["--", "--color", "always", "--show-output"],
exercise_name: self.name, bin_name,
description: "cargo test …", description: "cargo test …",
// Hide warnings because they are shown by Clippy. // Hide warnings because they are shown by Clippy.
hide_warnings: true, hide_warnings: true,
@ -124,18 +139,43 @@ impl Exercise {
} }
.run()?; .run()?;
let run_success = self.run_bin(output, target_dir)?; let run_success = run_bin(bin_name, output, target_dir)?;
Ok(test_success && run_success) Ok(test_success && run_success)
} }
pub fn terminal_link(&self) -> StyledContent<TerminalFileLink<'_>> { /// Compile, check and run the exercise.
style(TerminalFileLink(self.path)).underlined().blue() /// The output is written to the `output` buffer after clearing it.
#[inline]
fn run_exercise(&self, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
self.run(self.name(), output, target_dir)
}
/// Compile, check and run the exercise's solution.
/// The output is written to the `output` buffer after clearing it.
fn run_solution(&self, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
let name = self.name();
let mut bin_name = String::with_capacity(name.len());
bin_name.push_str(name);
bin_name.push_str("_sol");
self.run(&bin_name, output, target_dir)
} }
} }
impl Display for Exercise { impl RunnableExercise for Exercise {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { #[inline]
self.path.fmt(f) fn name(&self) -> &str {
self.name
}
#[inline]
fn strict_clippy(&self) -> bool {
self.strict_clippy
}
#[inline]
fn test(&self) -> bool {
self.test
} }
} }

@ -2,7 +2,7 @@ use anyhow::{bail, Context, Error, Result};
use serde::Deserialize; use serde::Deserialize;
use std::{fs, io::ErrorKind}; use std::{fs, io::ErrorKind};
use crate::embedded::EMBEDDED_FILES; use crate::{embedded::EMBEDDED_FILES, exercise::RunnableExercise};
/// Deserialized from the `info.toml` file. /// Deserialized from the `info.toml` file.
#[derive(Deserialize)] #[derive(Deserialize)]
@ -75,6 +75,23 @@ impl ExerciseInfo {
} }
} }
impl RunnableExercise for ExerciseInfo {
#[inline]
fn name(&self) -> &str {
&self.name
}
#[inline]
fn strict_clippy(&self) -> bool {
self.strict_clippy
}
#[inline]
fn test(&self) -> bool {
self.test
}
}
/// The deserialized `info.toml` file. /// The deserialized `info.toml` file.
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct InfoFile { pub struct InfoFile {

@ -4,14 +4,14 @@ use std::io::{self, Write};
use crate::{ use crate::{
app_state::{AppState, ExercisesProgress}, app_state::{AppState, ExercisesProgress},
exercise::OUTPUT_CAPACITY, exercise::{RunnableExercise, OUTPUT_CAPACITY},
terminal_link::TerminalFileLink, terminal_link::TerminalFileLink,
}; };
pub fn run(app_state: &mut AppState) -> Result<()> { pub fn run(app_state: &mut AppState) -> Result<()> {
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(&mut output, app_state.target_dir())?; let success = exercise.run_exercise(&mut output, app_state.target_dir())?;
let mut stdout = io::stdout().lock(); let mut stdout = io::stdout().lock();
stdout.write_all(&output)?; stdout.write_all(&output)?;

@ -8,7 +8,7 @@ use std::io::{self, StdoutLock, Write};
use crate::{ use crate::{
app_state::{AppState, ExercisesProgress}, app_state::{AppState, ExercisesProgress},
clear_terminal, clear_terminal,
exercise::OUTPUT_CAPACITY, exercise::{RunnableExercise, OUTPUT_CAPACITY},
progress_bar::progress_bar, progress_bar::progress_bar,
terminal_link::TerminalFileLink, terminal_link::TerminalFileLink,
}; };
@ -54,7 +54,7 @@ impl<'a> WatchState<'a> {
let success = self let success = self
.app_state .app_state
.current_exercise() .current_exercise()
.run(&mut self.output, self.app_state.target_dir())?; .run_exercise(&mut self.output, self.app_state.target_dir())?;
if success { if success {
self.done_status = self.done_status =
if let Some(solution_path) = self.app_state.current_solution_path()? { if let Some(solution_path) = self.app_state.current_solution_path()? {