Skip to content

Commit e1e4530

Browse files
author
fmoko
authored
Merge pull request #422 from AbdouSeck/show-tests-prints
2 parents f47d3f4 + 9e4fb10 commit e1e4530

File tree

8 files changed

+164
-42
lines changed

8 files changed

+164
-42
lines changed

info.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -804,7 +804,7 @@ name = "try_from_into"
804804
path = "exercises/conversions/try_from_into.rs"
805805
mode = "test"
806806
hint = """
807-
Follow the steps provided right before the `From` implementation.
807+
Follow the steps provided right before the `TryFrom` implementation.
808808
You can also use the example at https://doc.rust-lang.org/std/convert/trait.TryFrom.html"""
809809

810810
[[exercises]]
@@ -821,4 +821,4 @@ mode = "test"
821821
hint = """
822822
The implementation of FromStr should return an Ok with a Person object,
823823
or an Err with a string if the string is not valid.
824-
This is a some like an `try_from_into` exercise."""
824+
This is almost like the `try_from_into` exercise."""

install.sh

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,30 @@ Path=${1:-rustlings/}
102102
echo "Cloning Rustlings at $Path..."
103103
git clone -q https://github.com/rust-lang/rustlings $Path
104104

105+
cd $Path
106+
105107
Version=$(curl -s https://api.github.com/repos/rust-lang/rustlings/releases/latest | ${PY} -c "import json,sys;obj=json.load(sys.stdin);print(obj['tag_name']);")
106108
CargoBin="${CARGO_HOME:-$HOME/.cargo}/bin"
107109

110+
if [[ -z ${Version} ]]
111+
then
112+
echo "The latest tag version could not be fetched remotely."
113+
echo "Using the local git repository..."
114+
Version=$(ls -tr .git/refs/tags/ | tail -1)
115+
if [[ -z ${Version} ]]
116+
then
117+
echo "No valid tag version found"
118+
echo "Rustlings will be installed using the master branch"
119+
Version="master"
120+
else
121+
Version="tags/${Version}"
122+
fi
123+
else
124+
Version="tags/${Version}"
125+
fi
126+
108127
echo "Checking out version $Version..."
109-
cd $Path
110-
git checkout -q tags/$Version
128+
git checkout -q ${Version}
111129

112130
echo "Installing the 'rustlings' executable..."
113131
cargo install --force --path .

src/exercise.rs

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,21 @@ const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT\s+DONE";
1111
const CONTEXT: usize = 2;
1212
const CLIPPY_CARGO_TOML_PATH: &str = "./exercises/clippy/Cargo.toml";
1313

14+
// Get a temporary file name that is hopefully unique to this process
15+
#[inline]
1416
fn temp_file() -> String {
1517
format!("./temp_{}", process::id())
1618
}
1719

20+
// The mode of the exercise.
1821
#[derive(Deserialize, Copy, Clone)]
1922
#[serde(rename_all = "lowercase")]
2023
pub enum Mode {
24+
// Indicates that the exercise should be compiled as a binary
2125
Compile,
26+
// Indicates that the exercise should be compiled as a test harness
2227
Test,
28+
// Indicates that the exercise should be linted with clippy
2329
Clippy,
2430
}
2531

@@ -28,41 +34,60 @@ pub struct ExerciseList {
2834
pub exercises: Vec<Exercise>,
2935
}
3036

37+
// A representation of a rustlings exercise.
38+
// This is deserialized from the accompanying info.toml file
3139
#[derive(Deserialize)]
3240
pub struct Exercise {
41+
// Name of the exercise
3342
pub name: String,
43+
// The path to the file containing the exercise's source code
3444
pub path: PathBuf,
45+
// The mode of the exercise (Test, Compile, or Clippy)
3546
pub mode: Mode,
47+
// The hint text associated with the exercise
3648
pub hint: String,
3749
}
3850

51+
// An enum to track of the state of an Exercise.
52+
// An Exercise can be either Done or Pending
3953
#[derive(PartialEq, Debug)]
4054
pub enum State {
55+
// The state of the exercise once it's been completed
4156
Done,
57+
// The state of the exercise while it's not completed yet
4258
Pending(Vec<ContextLine>),
4359
}
4460

61+
// The context information of a pending exercise
4562
#[derive(PartialEq, Debug)]
4663
pub struct ContextLine {
64+
// The source code that is still pending completion
4765
pub line: String,
66+
// The line number of the source code still pending completion
4867
pub number: usize,
68+
// Whether or not this is important
4969
pub important: bool,
5070
}
5171

72+
// The result of compiling an exercise
5273
pub struct CompiledExercise<'a> {
5374
exercise: &'a Exercise,
5475
_handle: FileHandle,
5576
}
5677

5778
impl<'a> CompiledExercise<'a> {
79+
// Run the compiled exercise
5880
pub fn run(&self) -> Result<ExerciseOutput, ExerciseOutput> {
5981
self.exercise.run()
6082
}
6183
}
6284

85+
// A representation of an already executed binary
6386
#[derive(Debug)]
6487
pub struct ExerciseOutput {
88+
// The textual contents of the standard output of the binary
6589
pub stdout: String,
90+
// The textual contents of the standard error of the binary
6691
pub stderr: String,
6792
}
6893

@@ -140,7 +165,11 @@ path = "{}.rs""#,
140165
}
141166

142167
fn run(&self) -> Result<ExerciseOutput, ExerciseOutput> {
143-
let cmd = Command::new(&temp_file())
168+
let arg = match self.mode {
169+
Mode::Test => "--show-output",
170+
_ => ""
171+
};
172+
let cmd = Command::new(&temp_file()).arg(arg)
144173
.output()
145174
.expect("Failed to run 'run' command");
146175

@@ -205,6 +234,7 @@ impl Display for Exercise {
205234
}
206235
}
207236

237+
#[inline]
208238
fn clean() {
209239
let _ignored = remove_file(&temp_file());
210240
}
@@ -280,4 +310,16 @@ mod test {
280310

281311
assert_eq!(exercise.state(), State::Done);
282312
}
313+
314+
#[test]
315+
fn test_exercise_with_output() {
316+
let exercise = Exercise {
317+
name: "finished_exercise".into(),
318+
path: PathBuf::from("tests/fixture/success/testSuccess.rs"),
319+
mode: Mode::Test,
320+
hint: String::new(),
321+
};
322+
let out = exercise.compile().unwrap().run().unwrap();
323+
assert!(out.stdout.contains("THIS TEST TOO SHALL PASS"));
324+
}
283325
}

src/main.rs

Lines changed: 36 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,21 @@ fn main() {
2727
.version(crate_version!())
2828
.author("Olivia Hugger, Carol Nichols")
2929
.about("Rustlings is a collection of small exercises to get you used to writing and reading Rust code")
30-
.subcommand(SubCommand::with_name("verify").alias("v").about("Verifies all exercises according to the recommended order"))
31-
.subcommand(SubCommand::with_name("watch").alias("w").about("Reruns `verify` when files were edited"))
30+
.arg(
31+
Arg::with_name("nocapture")
32+
.long("nocapture")
33+
.help("Show outputs from the test exercises")
34+
)
35+
.subcommand(
36+
SubCommand::with_name("verify")
37+
.alias("v")
38+
.about("Verifies all exercises according to the recommended order")
39+
)
40+
.subcommand(
41+
SubCommand::with_name("watch")
42+
.alias("w")
43+
.about("Reruns `verify` when files were edited")
44+
)
3245
.subcommand(
3346
SubCommand::with_name("run")
3447
.alias("r")
@@ -43,7 +56,7 @@ fn main() {
4356
)
4457
.get_matches();
4558

46-
if None == matches.subcommand_name() {
59+
if matches.subcommand_name().is_none() {
4760
println!();
4861
println!(r#" welcome to... "#);
4962
println!(r#" _ _ _ "#);
@@ -73,6 +86,7 @@ fn main() {
7386

7487
let toml_str = &fs::read_to_string("info.toml").unwrap();
7588
let exercises = toml::from_str::<ExerciseList>(toml_str).unwrap().exercises;
89+
let verbose = matches.is_present("nocapture");
7690

7791
if let Some(ref matches) = matches.subcommand_matches("run") {
7892
let name = matches.value_of("name").unwrap();
@@ -84,7 +98,7 @@ fn main() {
8498
std::process::exit(1)
8599
});
86100

87-
run(&exercise).unwrap_or_else(|_| std::process::exit(1));
101+
run(&exercise, verbose).unwrap_or_else(|_| std::process::exit(1));
88102
}
89103

90104
if let Some(ref matches) = matches.subcommand_matches("hint") {
@@ -102,25 +116,23 @@ fn main() {
102116
}
103117

104118
if matches.subcommand_matches("verify").is_some() {
105-
verify(&exercises).unwrap_or_else(|_| std::process::exit(1));
119+
verify(&exercises, verbose).unwrap_or_else(|_| std::process::exit(1));
106120
}
107121

108-
if matches.subcommand_matches("watch").is_some() {
109-
if watch(&exercises).is_ok() {
110-
println!(
111-
"{emoji} All exercises completed! {emoji}",
112-
emoji = Emoji("🎉", "★")
113-
);
114-
println!("");
115-
println!("We hope you enjoyed learning about the various aspects of Rust!");
116-
println!(
117-
"If you noticed any issues, please don't hesitate to report them to our repo."
118-
);
119-
println!("You can also contribute your own exercises to help the greater community!");
120-
println!("");
121-
println!("Before reporting an issue or contributing, please read our guidelines:");
122-
println!("https://github.com/rust-lang/rustlings/blob/master/CONTRIBUTING.md");
123-
}
122+
if matches.subcommand_matches("watch").is_some() && watch(&exercises, verbose).is_ok() {
123+
println!(
124+
"{emoji} All exercises completed! {emoji}",
125+
emoji = Emoji("🎉", "★")
126+
);
127+
println!();
128+
println!("We hope you enjoyed learning about the various aspects of Rust!");
129+
println!(
130+
"If you noticed any issues, please don't hesitate to report them to our repo."
131+
);
132+
println!("You can also contribute your own exercises to help the greater community!");
133+
println!();
134+
println!("Before reporting an issue or contributing, please read our guidelines:");
135+
println!("https://github.com/rust-lang/rustlings/blob/master/CONTRIBUTING.md");
124136
}
125137

126138
if matches.subcommand_name().is_none() {
@@ -149,7 +161,7 @@ fn spawn_watch_shell(failed_exercise_hint: &Arc<Mutex<Option<String>>>) {
149161
});
150162
}
151163

152-
fn watch(exercises: &[Exercise]) -> notify::Result<()> {
164+
fn watch(exercises: &[Exercise], verbose: bool) -> notify::Result<()> {
153165
/* Clears the terminal with an ANSI escape code.
154166
Works in UNIX and newer Windows terminals. */
155167
fn clear_screen() {
@@ -164,7 +176,7 @@ fn watch(exercises: &[Exercise]) -> notify::Result<()> {
164176
clear_screen();
165177

166178
let to_owned_hint = |t: &Exercise| t.hint.to_owned();
167-
let failed_exercise_hint = match verify(exercises.iter()) {
179+
let failed_exercise_hint = match verify(exercises.iter(), verbose) {
168180
Ok(_) => return Ok(()),
169181
Err(exercise) => Arc::new(Mutex::new(Some(to_owned_hint(exercise)))),
170182
};
@@ -179,7 +191,7 @@ fn watch(exercises: &[Exercise]) -> notify::Result<()> {
179191
.iter()
180192
.skip_while(|e| !filepath.ends_with(&e.path));
181193
clear_screen();
182-
match verify(pending_exercises) {
194+
match verify(pending_exercises, verbose) {
183195
Ok(_) => return Ok(()),
184196
Err(exercise) => {
185197
let mut failed_exercise_hint = failed_exercise_hint.lock().unwrap();

src/run.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,22 @@ use crate::exercise::{Exercise, Mode};
22
use crate::verify::test;
33
use indicatif::ProgressBar;
44

5-
pub fn run(exercise: &Exercise) -> Result<(), ()> {
5+
// Invoke the rust compiler on the path of the given exercise,
6+
// and run the ensuing binary.
7+
// The verbose argument helps determine whether or not to show
8+
// the output from the test harnesses (if the mode of the exercise is test)
9+
pub fn run(exercise: &Exercise, verbose: bool) -> Result<(), ()> {
610
match exercise.mode {
7-
Mode::Test => test(exercise)?,
11+
Mode::Test => test(exercise, verbose)?,
812
Mode::Compile => compile_and_run(exercise)?,
913
Mode::Clippy => compile_and_run(exercise)?,
1014
}
1115
Ok(())
1216
}
1317

18+
// Invoke the rust compiler on the path of the given exercise
19+
// and run the ensuing binary.
20+
// This is strictly for non-test binaries, so output is displayed
1421
fn compile_and_run(exercise: &Exercise) -> Result<(), ()> {
1522
let progress_bar = ProgressBar::new_spinner();
1623
progress_bar.set_message(format!("Compiling {}...", exercise).as_str());

0 commit comments

Comments
 (0)