Compare commits

..

No commits in common. "a2d1cb3b2246f50ea36408f2be1962f5dc69d09b" and "71f31d74bce5c657ab8a583c0a12a205e50e32cb" have entirely different histories.

10 changed files with 156 additions and 179 deletions

8
Cargo.lock generated
View file

@ -368,9 +368,9 @@ dependencies = [
[[package]]
name = "libc"
version = "0.2.158"
version = "0.2.156"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439"
checksum = "a5f43f184355eefb8d17fc948dbecf6c13be3c141f20d834ae842193a448c72a"
[[package]]
name = "libredox"
@ -746,9 +746,9 @@ dependencies = [
[[package]]
name = "syn"
version = "2.0.75"
version = "2.0.74"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6af063034fc1935ede7be0122941bafa9bacb949334d090b77ca98b5817c7d9"
checksum = "1fceb41e3d546d0bd83421d3409b1460cc7444cd389341a4c880fe7a042cb3d7"
dependencies = [
"proc-macro2",
"quote",

View file

@ -1,6 +1,7 @@
use std::{sync::mpsc, thread, time::Duration};
struct Queue {
length: u32,
first_half: Vec<u32>,
second_half: Vec<u32>,
}
@ -8,6 +9,7 @@ struct Queue {
impl Queue {
fn new() -> Self {
Self {
length: 10,
first_half: vec![1, 2, 3, 4, 5],
second_half: vec![6, 7, 8, 9, 10],
}
@ -46,15 +48,17 @@ mod tests {
fn threads3() {
let (tx, rx) = mpsc::channel();
let queue = Queue::new();
let queue_length = queue.length;
send_tx(queue, tx);
let mut received = Vec::with_capacity(10);
for value in rx {
received.push(value);
let mut total_received: u32 = 0;
for received in rx {
println!("Got: {received}");
total_received += 1;
}
received.sort();
assert_eq!(received, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
println!("Number of received values: {total_received}");
assert_eq!(total_received, queue_length);
}
}

View file

@ -1,6 +1,7 @@
use std::{sync::mpsc, thread, time::Duration};
struct Queue {
length: u32,
first_half: Vec<u32>,
second_half: Vec<u32>,
}
@ -8,6 +9,7 @@ struct Queue {
impl Queue {
fn new() -> Self {
Self {
length: 10,
first_half: vec![1, 2, 3, 4, 5],
second_half: vec![6, 7, 8, 9, 10],
}
@ -48,15 +50,17 @@ mod tests {
fn threads3() {
let (tx, rx) = mpsc::channel();
let queue = Queue::new();
let queue_length = queue.length;
send_tx(queue, tx);
let mut received = Vec::with_capacity(10);
for value in rx {
received.push(value);
let mut total_received: u32 = 0;
for received in rx {
println!("Got: {received}");
total_received += 1;
}
received.sort();
assert_eq!(received, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
println!("Number of received values: {total_received}");
assert_eq!(total_received, queue_length);
}
}

View file

@ -74,14 +74,12 @@ impl CmdRunner {
bail!("The command `cargo metadata …` failed. Are you in the `rustlings/` directory?");
}
let metadata: CargoMetadata = serde_json::de::from_slice(&metadata_output.stdout)
let target_dir = serde_json::de::from_slice::<CargoMetadata>(&metadata_output.stdout)
.context(
"Failed to read the field `target_directory` from the output of the command `cargo metadata …`",
)?;
)?.target_directory;
Ok(Self {
target_dir: metadata.target_directory,
})
Ok(Self { target_dir })
}
pub fn cargo<'out>(

View file

@ -97,12 +97,7 @@ fn check_info_file_exercises(info_file: &InfoFile) -> Result<HashSet<PathBuf>> {
bail!("Didn't find any `// TODO` comment in the file `{path}`.\nYou need to have at least one such comment to guide the user.");
}
let contains_tests = file_buf.contains("#[test]\n");
if exercise_info.test {
if !contains_tests {
bail!("The file `{path}` doesn't contain any tests. If you don't want to add tests to this exercise, set `test = false` for this exercise in the `info.toml` file");
}
} else if contains_tests {
if !exercise_info.test && file_buf.contains("#[test]") {
bail!("The file `{path}` contains tests annotated with `#[test]` but the exercise `{name}` has `test = false` in the `info.toml` file");
}
@ -165,72 +160,61 @@ fn check_unexpected_files(dir: &str, allowed_rust_files: &HashSet<PathBuf>) -> R
Ok(())
}
fn check_exercises_unsolved(
info_file: &'static InfoFile,
cmd_runner: &'static CmdRunner,
) -> Result<()> {
let mut stdout = io::stdout().lock();
stdout.write_all(b"Running all exercises to check that they aren't already solved...\n")?;
fn check_exercises_unsolved(info_file: &InfoFile, cmd_runner: &CmdRunner) -> Result<()> {
println!(
"Running all exercises to check that they aren't already solved. This may take a while…\n",
);
thread::scope(|s| {
let handles = info_file
.exercises
.iter()
.filter_map(|exercise_info| {
if exercise_info.skip_check_unsolved {
return None;
}
let handles = info_file
.exercises
.iter()
.filter_map(|exercise_info| {
if exercise_info.skip_check_unsolved {
return None;
Some((
exercise_info.name.as_str(),
s.spawn(|| exercise_info.run_exercise(None, cmd_runner)),
))
})
.collect::<Vec<_>>();
for (exercise_name, handle) in handles {
let Ok(result) = handle.join() else {
bail!("Panic while trying to run the exericse {exercise_name}");
};
match result {
Ok(true) => bail!(
"The exercise {exercise_name} is already solved.\n{SKIP_CHECK_UNSOLVED_HINT}",
),
Ok(false) => (),
Err(e) => return Err(e),
}
Some((
exercise_info.name.as_str(),
thread::spawn(|| exercise_info.run_exercise(None, cmd_runner)),
))
})
.collect::<Vec<_>>();
let n_handles = handles.len();
write!(stdout, "Progress: 0/{n_handles}")?;
stdout.flush()?;
let mut handle_num = 1;
for (exercise_name, handle) in handles {
let Ok(result) = handle.join() else {
bail!("Panic while trying to run the exericse {exercise_name}");
};
match result {
Ok(true) => {
bail!("The exercise {exercise_name} is already solved.\n{SKIP_CHECK_UNSOLVED_HINT}",)
}
Ok(false) => (),
Err(e) => return Err(e),
}
write!(stdout, "\rProgress: {handle_num}/{n_handles}")?;
stdout.flush()?;
handle_num += 1;
}
stdout.write_all(b"\n")?;
Ok(())
Ok(())
})
}
fn check_exercises(info_file: &'static InfoFile, cmd_runner: &'static CmdRunner) -> Result<()> {
fn check_exercises(info_file: &InfoFile, cmd_runner: &CmdRunner) -> Result<()> {
match info_file.format_version.cmp(&CURRENT_FORMAT_VERSION) {
Ordering::Less => bail!("`format_version` < {CURRENT_FORMAT_VERSION} (supported version)\nPlease migrate to the latest format version"),
Ordering::Greater => bail!("`format_version` > {CURRENT_FORMAT_VERSION} (supported version)\nTry updating the Rustlings program"),
Ordering::Equal => (),
}
let handle = thread::spawn(move || check_exercises_unsolved(info_file, cmd_runner));
let info_file_paths = check_info_file_exercises(info_file)?;
check_unexpected_files("exercises", &info_file_paths)?;
let handle = thread::spawn(move || check_unexpected_files("exercises", &info_file_paths));
check_exercises_unsolved(info_file, cmd_runner)?;
handle.join().unwrap()
}
enum SolutionCheck {
Success { sol_path: String },
MissingRequired,
MissingOptional,
RunFailure { output: Vec<u8> },
Err(Error),
@ -238,96 +222,88 @@ enum SolutionCheck {
fn check_solutions(
require_solutions: bool,
info_file: &'static InfoFile,
cmd_runner: &'static CmdRunner,
info_file: &InfoFile,
cmd_runner: &CmdRunner,
) -> Result<()> {
let mut stdout = io::stdout().lock();
stdout.write_all(b"Running all solutions...\n")?;
println!("Running all solutions. This may take a while…\n");
thread::scope(|s| {
let handles = info_file
.exercises
.iter()
.map(|exercise_info| {
s.spawn(|| {
let sol_path = exercise_info.sol_path();
if !Path::new(&sol_path).exists() {
if require_solutions {
return SolutionCheck::MissingRequired;
}
let handles = info_file
.exercises
.iter()
.map(|exercise_info| {
thread::spawn(move || {
let sol_path = exercise_info.sol_path();
if !Path::new(&sol_path).exists() {
if require_solutions {
return SolutionCheck::Err(anyhow!(
"The solution of the exercise {} is missing",
exercise_info.name,
));
return SolutionCheck::MissingOptional;
}
return SolutionCheck::MissingOptional;
}
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
match exercise_info.run_solution(Some(&mut output), cmd_runner) {
Ok(true) => SolutionCheck::Success { sol_path },
Ok(false) => SolutionCheck::RunFailure { output },
Err(e) => SolutionCheck::Err(e),
}
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
match exercise_info.run_solution(Some(&mut output), cmd_runner) {
Ok(true) => SolutionCheck::Success { sol_path },
Ok(false) => SolutionCheck::RunFailure { output },
Err(e) => SolutionCheck::Err(e),
}
})
})
})
.collect::<Vec<_>>();
.collect::<Vec<_>>();
let mut sol_paths = hash_set_with_capacity(info_file.exercises.len());
let mut fmt_cmd = Command::new("rustfmt");
fmt_cmd
.arg("--check")
.arg("--edition")
.arg("2021")
.arg("--color")
.arg("always")
.stdin(Stdio::null());
let mut sol_paths = hash_set_with_capacity(info_file.exercises.len());
let mut fmt_cmd = Command::new("rustfmt");
fmt_cmd
.arg("--check")
.arg("--edition")
.arg("2021")
.arg("--color")
.arg("always")
.stdin(Stdio::null());
let n_handles = handles.len();
write!(stdout, "Progress: 0/{n_handles}")?;
stdout.flush()?;
let mut handle_num = 1;
for (exercise_info, handle) in info_file.exercises.iter().zip(handles) {
let Ok(check_result) = handle.join() else {
bail!(
"Panic while trying to run the solution of the exericse {}",
exercise_info.name,
);
};
match check_result {
SolutionCheck::Success { sol_path } => {
fmt_cmd.arg(&sol_path);
sol_paths.insert(PathBuf::from(sol_path));
}
SolutionCheck::MissingOptional => (),
SolutionCheck::RunFailure { output } => {
stdout.write_all(b"\n\n")?;
stdout.write_all(&output)?;
for (exercise_info, handle) in info_file.exercises.iter().zip(handles) {
let Ok(check_result) = handle.join() else {
bail!(
"Running the solution of the exercise {} failed with the error above",
"Panic while trying to run the solution of the exericse {}",
exercise_info.name,
);
};
match check_result {
SolutionCheck::Success { sol_path } => {
fmt_cmd.arg(&sol_path);
sol_paths.insert(PathBuf::from(sol_path));
}
SolutionCheck::MissingRequired => {
bail!(
"The solution of the exercise {} is missing",
exercise_info.name,
);
}
SolutionCheck::MissingOptional => (),
SolutionCheck::RunFailure { output } => {
io::stderr().lock().write_all(&output)?;
bail!(
"Running the solution of the exercise {} failed with the error above",
exercise_info.name,
);
}
SolutionCheck::Err(e) => return Err(e),
}
SolutionCheck::Err(e) => return Err(e),
}
write!(stdout, "\rProgress: {handle_num}/{n_handles}")?;
stdout.flush()?;
handle_num += 1;
}
stdout.write_all(b"\n")?;
let handle = s.spawn(move || check_unexpected_files("solutions", &sol_paths));
let handle = thread::spawn(move || check_unexpected_files("solutions", &sol_paths));
if !fmt_cmd
.status()
.context("Failed to run `rustfmt` on all solution files")?
.success()
{
bail!("Some solutions aren't formatted. Run `rustfmt` on them");
}
if !fmt_cmd
.status()
.context("Failed to run `rustfmt` on all solution files")?
.success()
{
bail!("Some solutions aren't formatted. Run `rustfmt` on them");
}
handle.join().unwrap()
handle.join().unwrap()
})
}
pub fn check(require_solutions: bool) -> Result<()> {
@ -340,12 +316,9 @@ pub fn check(require_solutions: bool) -> Result<()> {
check_cargo_toml(&info_file.exercises, "Cargo.toml", b"")?;
}
// Leaking is fine since they are used until the end of the program.
let cmd_runner = Box::leak(Box::new(CmdRunner::build()?));
let info_file = Box::leak(Box::new(info_file));
check_exercises(info_file, cmd_runner)?;
check_solutions(require_solutions, info_file, cmd_runner)?;
let cmd_runner = CmdRunner::build()?;
check_exercises(&info_file, &cmd_runner)?;
check_solutions(require_solutions, &info_file, &cmd_runner)?;
println!("Everything looks fine!");

View file

@ -98,7 +98,7 @@ pub trait RunnableExercise {
let output_is_some = output.is_some();
let mut test_cmd = cmd_runner.cargo("test", bin_name, output.as_deref_mut());
if output_is_some {
test_cmd.args(["--", "--color", "always", "--format", "pretty"]);
test_cmd.args(["--", "--color", "always", "--show-output"]);
}
let test_success = test_cmd.run("cargo test …")?;
if !test_success {

View file

@ -135,4 +135,4 @@ impl InfoFile {
}
const NO_EXERCISES_ERR: &str = "There are no exercises yet!
Add at least one exercise before testing.";
If you are developing third-party exercises, add at least one exercise before testing.";

View file

@ -75,7 +75,7 @@ fn handle_list(app_state: &mut AppState, stdout: &mut StdoutLock) -> Result<()>
}
KeyCode::Char('c') => {
ui_state.selected_to_current_exercise()?;
break;
ui_state = ui_state.with_updated_rows();
}
_ => (),
}

View file

@ -33,21 +33,18 @@ pub fn run(app_state: &mut AppState) -> Result<()> {
)?;
if let Some(solution_path) = app_state.current_solution_path()? {
writeln!(
stdout,
"\n{} for comparison: {}\n",
"Solution".bold(),
style(TerminalFileLink(&solution_path)).underlined().cyan(),
)?;
println!(
"\nA solution file can be found at {}\n",
style(TerminalFileLink(&solution_path)).underlined().green(),
);
}
match app_state.done_current_exercise(&mut stdout)? {
ExercisesProgress::AllDone => (),
ExercisesProgress::CurrentPending | ExercisesProgress::NewPending => writeln!(
stdout,
ExercisesProgress::CurrentPending | ExercisesProgress::NewPending => println!(
"Next exercise: {}",
app_state.current_exercise().terminal_link(),
)?,
),
}
Ok(())

View file

@ -56,12 +56,10 @@ impl<'a> WatchState<'a> {
"\nChecking the exercise `{}`. Please wait…",
self.app_state.current_exercise().name,
)?;
let success = self
.app_state
.current_exercise()
.run_exercise(Some(&mut self.output), self.app_state.cmd_runner())?;
self.output.push(b'\n');
if success {
self.done_status =
if let Some(solution_path) = self.app_state.current_solution_path()? {
@ -123,9 +121,11 @@ impl<'a> WatchState<'a> {
pub fn render(&mut self) -> Result<()> {
// Prevent having the first line shifted if clearing wasn't successful.
self.writer.write_all(b"\n")?;
clear_terminal(&mut self.writer)?;
self.writer.write_all(&self.output)?;
self.writer.write_all(b"\n")?;
if self.show_hint {
writeln!(
@ -137,20 +137,21 @@ impl<'a> WatchState<'a> {
}
if self.done_status != DoneStatus::Pending {
writeln!(self.writer, "{}", "Exercise done ✓".bold().green())?;
if let DoneStatus::DoneWithSolution(solution_path) = &self.done_status {
writeln!(
self.writer,
"{} for comparison: {}",
"Solution".bold(),
style(TerminalFileLink(solution_path)).underlined().cyan(),
)?;
}
writeln!(
self.writer,
"When done experimenting, enter `n` to move on to the next exercise 🦀\n",
"{}\n",
"Exercise done ✓
When you are done experimenting, enter `n` to move on to the next exercise 🦀"
.bold()
.green(),
)?;
}
if let DoneStatus::DoneWithSolution(solution_path) = &self.done_status {
writeln!(
self.writer,
"A solution file can be found at {}\n",
style(TerminalFileLink(solution_path)).underlined().green(),
)?;
}