mirror of
https://github.com/notohh/rustlings.git
synced 2024-11-22 05:52:23 -05:00
Make the output optional
This commit is contained in:
parent
3a99542f73
commit
74fab994e2
7 changed files with 84 additions and 53 deletions
|
@ -63,3 +63,7 @@ panic = "abort"
|
||||||
|
|
||||||
[package.metadata.release]
|
[package.metadata.release]
|
||||||
pre-release-hook = ["./release-hook.sh"]
|
pre-release-hook = ["./release-hook.sh"]
|
||||||
|
|
||||||
|
# TODO: Remove after the following fix is released: https://github.com/rust-lang/rust-clippy/pull/13102
|
||||||
|
[lints.clippy]
|
||||||
|
needless_option_as_deref = "allow"
|
||||||
|
|
|
@ -11,7 +11,7 @@ use std::{
|
||||||
use crate::{
|
use crate::{
|
||||||
clear_terminal,
|
clear_terminal,
|
||||||
embedded::EMBEDDED_FILES,
|
embedded::EMBEDDED_FILES,
|
||||||
exercise::{Exercise, RunnableExercise, OUTPUT_CAPACITY},
|
exercise::{Exercise, RunnableExercise},
|
||||||
info_file::ExerciseInfo,
|
info_file::ExerciseInfo,
|
||||||
DEBUG_PROFILE,
|
DEBUG_PROFILE,
|
||||||
};
|
};
|
||||||
|
@ -386,8 +386,7 @@ impl AppState {
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
.map(|exercise| {
|
.map(|exercise| {
|
||||||
s.spawn(|| {
|
s.spawn(|| {
|
||||||
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
let success = exercise.run_exercise(None, &self.target_dir)?;
|
||||||
let success = exercise.run_exercise(&mut output, &self.target_dir)?;
|
|
||||||
exercise.done = success;
|
exercise.done = success;
|
||||||
Ok::<_, Error>(success)
|
Ok::<_, Error>(success)
|
||||||
})
|
})
|
||||||
|
|
54
src/cmd.rs
54
src/cmd.rs
|
@ -1,30 +1,42 @@
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use std::{io::Read, path::Path, process::Command};
|
use std::{
|
||||||
|
io::Read,
|
||||||
|
path::Path,
|
||||||
|
process::{Command, Stdio},
|
||||||
|
};
|
||||||
|
|
||||||
/// Run a command with a description for a possible error and append the merged stdout and stderr.
|
/// Run a command with a description for a possible error and append the merged stdout and stderr.
|
||||||
/// The boolean in the returned `Result` is true if the command's exit status is success.
|
/// The boolean in the returned `Result` is true if the command's exit status is success.
|
||||||
pub fn run_cmd(mut cmd: Command, description: &str, output: &mut Vec<u8>) -> Result<bool> {
|
pub fn run_cmd(mut cmd: Command, description: &str, output: Option<&mut Vec<u8>>) -> Result<bool> {
|
||||||
let (mut reader, writer) = os_pipe::pipe()
|
let spawn = |mut cmd: Command| {
|
||||||
.with_context(|| format!("Failed to create a pipe to run the command `{description}``"))?;
|
// NOTE: The closure drops `cmd` which prevents a pipe deadlock.
|
||||||
|
cmd.spawn()
|
||||||
|
.with_context(|| format!("Failed to run the command `{description}`"))
|
||||||
|
};
|
||||||
|
|
||||||
let writer_clone = writer.try_clone().with_context(|| {
|
let mut handle = if let Some(output) = output {
|
||||||
format!("Failed to clone the pipe writer for the command `{description}`")
|
let (mut reader, writer) = os_pipe::pipe().with_context(|| {
|
||||||
})?;
|
format!("Failed to create a pipe to run the command `{description}``")
|
||||||
|
})?;
|
||||||
|
|
||||||
let mut handle = cmd
|
let writer_clone = writer.try_clone().with_context(|| {
|
||||||
.stdout(writer_clone)
|
format!("Failed to clone the pipe writer for the command `{description}`")
|
||||||
.stderr(writer)
|
})?;
|
||||||
.spawn()
|
|
||||||
.with_context(|| format!("Failed to run the command `{description}`"))?;
|
|
||||||
|
|
||||||
// Prevent pipe deadlock.
|
cmd.stdout(writer_clone).stderr(writer);
|
||||||
drop(cmd);
|
let handle = spawn(cmd)?;
|
||||||
|
|
||||||
reader
|
reader
|
||||||
.read_to_end(output)
|
.read_to_end(output)
|
||||||
.with_context(|| format!("Failed to read the output of the command `{description}`"))?;
|
.with_context(|| format!("Failed to read the output of the command `{description}`"))?;
|
||||||
|
|
||||||
output.push(b'\n');
|
output.push(b'\n');
|
||||||
|
|
||||||
|
handle
|
||||||
|
} else {
|
||||||
|
cmd.stdout(Stdio::null()).stderr(Stdio::null());
|
||||||
|
spawn(cmd)?
|
||||||
|
};
|
||||||
|
|
||||||
handle
|
handle
|
||||||
.wait()
|
.wait()
|
||||||
|
@ -42,14 +54,14 @@ pub struct CargoCmd<'a> {
|
||||||
/// Added as `--target-dir` if `Self::dev` is true.
|
/// Added as `--target-dir` if `Self::dev` is true.
|
||||||
pub target_dir: &'a Path,
|
pub target_dir: &'a Path,
|
||||||
/// The output buffer to append the merged stdout and stderr.
|
/// The output buffer to append the merged stdout and stderr.
|
||||||
pub output: &'a mut Vec<u8>,
|
pub output: Option<&'a mut Vec<u8>>,
|
||||||
/// true while developing Rustlings.
|
/// true while developing Rustlings.
|
||||||
pub dev: bool,
|
pub dev: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> CargoCmd<'a> {
|
impl<'a> CargoCmd<'a> {
|
||||||
/// Run `cargo SUBCOMMAND --bin EXERCISE_NAME … ARGS`.
|
/// Run `cargo SUBCOMMAND --bin EXERCISE_NAME … ARGS`.
|
||||||
pub fn run(&mut self) -> Result<bool> {
|
pub fn run(self) -> Result<bool> {
|
||||||
let mut cmd = Command::new("cargo");
|
let mut cmd = Command::new("cargo");
|
||||||
cmd.arg(self.subcommand);
|
cmd.arg(self.subcommand);
|
||||||
|
|
||||||
|
@ -86,7 +98,7 @@ mod tests {
|
||||||
cmd.arg("Hello");
|
cmd.arg("Hello");
|
||||||
|
|
||||||
let mut output = Vec::with_capacity(8);
|
let mut output = Vec::with_capacity(8);
|
||||||
run_cmd(cmd, "echo …", &mut output).unwrap();
|
run_cmd(cmd, "echo …", Some(&mut output)).unwrap();
|
||||||
|
|
||||||
assert_eq!(output, b"Hello\n\n");
|
assert_eq!(output, b"Hello\n\n");
|
||||||
}
|
}
|
||||||
|
|
|
@ -184,8 +184,7 @@ fn check_exercises_unsolved(info_file: &InfoFile, target_dir: &Path) -> Result<(
|
||||||
error_occurred.store(true, atomic::Ordering::Relaxed);
|
error_occurred.store(true, atomic::Ordering::Relaxed);
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
match exercise_info.run_exercise(None, target_dir) {
|
||||||
match exercise_info.run_exercise(&mut output, target_dir) {
|
|
||||||
Ok(true) => error(b"Already solved!"),
|
Ok(true) => error(b"Already solved!"),
|
||||||
Ok(false) => (),
|
Ok(false) => (),
|
||||||
Err(e) => error(e.to_string().as_bytes()),
|
Err(e) => error(e.to_string().as_bytes()),
|
||||||
|
@ -244,7 +243,7 @@ fn check_solutions(require_solutions: bool, info_file: &InfoFile, target_dir: &P
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
|
||||||
match exercise_info.run_solution(&mut output, target_dir) {
|
match exercise_info.run_solution(Some(&mut output), target_dir) {
|
||||||
Ok(true) => {
|
Ok(true) => {
|
||||||
paths.lock().unwrap().insert(PathBuf::from(path));
|
paths.lock().unwrap().insert(PathBuf::from(path));
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,8 +19,10 @@ pub const OUTPUT_CAPACITY: usize = 1 << 14;
|
||||||
|
|
||||||
// Run an exercise binary and append its output to the `output` buffer.
|
// Run an exercise binary and append its output to the `output` buffer.
|
||||||
// Compilation must be done before calling this method.
|
// Compilation must be done before calling this method.
|
||||||
fn run_bin(bin_name: &str, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
|
fn run_bin(bin_name: &str, mut output: Option<&mut Vec<u8>>, target_dir: &Path) -> Result<bool> {
|
||||||
writeln!(output, "{}", "Output".underlined())?;
|
if let Some(output) = output.as_deref_mut() {
|
||||||
|
writeln!(output, "{}", "Output".underlined())?;
|
||||||
|
}
|
||||||
|
|
||||||
// 7 = "/debug/".len()
|
// 7 = "/debug/".len()
|
||||||
let mut bin_path = PathBuf::with_capacity(target_dir.as_os_str().len() + 7 + bin_name.len());
|
let mut bin_path = PathBuf::with_capacity(target_dir.as_os_str().len() + 7 + bin_name.len());
|
||||||
|
@ -28,19 +30,25 @@ fn run_bin(bin_name: &str, output: &mut Vec<u8>, target_dir: &Path) -> Result<bo
|
||||||
bin_path.push("debug");
|
bin_path.push("debug");
|
||||||
bin_path.push(bin_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.as_deref_mut(),
|
||||||
|
)?;
|
||||||
|
|
||||||
if !success {
|
if let Some(output) = output {
|
||||||
// This output is important to show the user that something went wrong.
|
if !success {
|
||||||
// Otherwise, calling something like `exit(1)` in an exercise without further output
|
// This output is important to show the user that something went wrong.
|
||||||
// leaves the user confused about why the exercise isn't done yet.
|
// Otherwise, calling something like `exit(1)` in an exercise without further output
|
||||||
writeln!(
|
// leaves the user confused about why the exercise isn't done yet.
|
||||||
output,
|
writeln!(
|
||||||
"{}",
|
output,
|
||||||
"The exercise didn't run successfully (nonzero exit code)"
|
"{}",
|
||||||
.bold()
|
"The exercise didn't run successfully (nonzero exit code)"
|
||||||
.red(),
|
.bold()
|
||||||
)?;
|
.red(),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(success)
|
Ok(success)
|
||||||
|
@ -77,8 +85,15 @@ pub trait RunnableExercise {
|
||||||
|
|
||||||
// Compile, check and run the exercise or its solution (depending on `bin_name´).
|
// Compile, check and run the exercise or its solution (depending on `bin_name´).
|
||||||
// The output is written to the `output` buffer after clearing it.
|
// 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> {
|
fn run(
|
||||||
output.clear();
|
&self,
|
||||||
|
bin_name: &str,
|
||||||
|
mut output: Option<&mut Vec<u8>>,
|
||||||
|
target_dir: &Path,
|
||||||
|
) -> Result<bool> {
|
||||||
|
if let Some(output) = output.as_deref_mut() {
|
||||||
|
output.clear();
|
||||||
|
}
|
||||||
|
|
||||||
// Developing the official Rustlings.
|
// Developing the official Rustlings.
|
||||||
let dev = DEBUG_PROFILE && in_official_repo();
|
let dev = DEBUG_PROFILE && in_official_repo();
|
||||||
|
@ -90,7 +105,7 @@ pub trait RunnableExercise {
|
||||||
description: "cargo build …",
|
description: "cargo build …",
|
||||||
hide_warnings: false,
|
hide_warnings: false,
|
||||||
target_dir,
|
target_dir,
|
||||||
output,
|
output: output.as_deref_mut(),
|
||||||
dev,
|
dev,
|
||||||
}
|
}
|
||||||
.run()?;
|
.run()?;
|
||||||
|
@ -99,7 +114,9 @@ pub trait RunnableExercise {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Discard the output of `cargo build` because it will be shown again by Clippy.
|
// Discard the output of `cargo build` because it will be shown again by Clippy.
|
||||||
output.clear();
|
if let Some(output) = output.as_deref_mut() {
|
||||||
|
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() {
|
||||||
|
@ -114,7 +131,7 @@ pub trait RunnableExercise {
|
||||||
description: "cargo clippy …",
|
description: "cargo clippy …",
|
||||||
hide_warnings: false,
|
hide_warnings: false,
|
||||||
target_dir,
|
target_dir,
|
||||||
output,
|
output: output.as_deref_mut(),
|
||||||
dev,
|
dev,
|
||||||
}
|
}
|
||||||
.run()?;
|
.run()?;
|
||||||
|
@ -123,7 +140,7 @@ pub trait RunnableExercise {
|
||||||
}
|
}
|
||||||
|
|
||||||
if !self.test() {
|
if !self.test() {
|
||||||
return run_bin(bin_name, output, target_dir);
|
return run_bin(bin_name, output.as_deref_mut(), target_dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
let test_success = CargoCmd {
|
let test_success = CargoCmd {
|
||||||
|
@ -134,12 +151,12 @@ pub trait RunnableExercise {
|
||||||
// Hide warnings because they are shown by Clippy.
|
// Hide warnings because they are shown by Clippy.
|
||||||
hide_warnings: true,
|
hide_warnings: true,
|
||||||
target_dir,
|
target_dir,
|
||||||
output,
|
output: output.as_deref_mut(),
|
||||||
dev,
|
dev,
|
||||||
}
|
}
|
||||||
.run()?;
|
.run()?;
|
||||||
|
|
||||||
let run_success = run_bin(bin_name, output, target_dir)?;
|
let run_success = run_bin(bin_name, output.as_deref_mut(), target_dir)?;
|
||||||
|
|
||||||
Ok(test_success && run_success)
|
Ok(test_success && run_success)
|
||||||
}
|
}
|
||||||
|
@ -147,13 +164,13 @@ pub trait RunnableExercise {
|
||||||
/// Compile, check and run the exercise.
|
/// Compile, check and run the exercise.
|
||||||
/// The output is written to the `output` buffer after clearing it.
|
/// The output is written to the `output` buffer after clearing it.
|
||||||
#[inline]
|
#[inline]
|
||||||
fn run_exercise(&self, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
|
fn run_exercise(&self, output: Option<&mut Vec<u8>>, target_dir: &Path) -> Result<bool> {
|
||||||
self.run(self.name(), output, target_dir)
|
self.run(self.name(), output, target_dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Compile, check and run the exercise's solution.
|
/// Compile, check and run the exercise's solution.
|
||||||
/// The output is written to the `output` buffer after clearing it.
|
/// The output is written to the `output` buffer after clearing it.
|
||||||
fn run_solution(&self, output: &mut Vec<u8>, target_dir: &Path) -> Result<bool> {
|
fn run_solution(&self, output: Option<&mut Vec<u8>>, target_dir: &Path) -> Result<bool> {
|
||||||
let name = self.name();
|
let name = self.name();
|
||||||
let mut bin_name = String::with_capacity(name.len());
|
let mut bin_name = String::with_capacity(name.len());
|
||||||
bin_name.push_str(name);
|
bin_name.push_str(name);
|
||||||
|
|
|
@ -11,7 +11,7 @@ use crate::{
|
||||||
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_exercise(&mut output, app_state.target_dir())?;
|
let success = exercise.run_exercise(Some(&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)?;
|
||||||
|
|
|
@ -54,7 +54,7 @@ impl<'a> WatchState<'a> {
|
||||||
let success = self
|
let success = self
|
||||||
.app_state
|
.app_state
|
||||||
.current_exercise()
|
.current_exercise()
|
||||||
.run_exercise(&mut self.output, self.app_state.target_dir())?;
|
.run_exercise(Some(&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()? {
|
||||||
|
|
Loading…
Reference in a new issue