Skip to content

Commit b9d2756

Browse files
committed
Merge branch 'main' into toml
2 parents e452060 + 07dec76 commit b9d2756

File tree

6 files changed

+95
-52
lines changed

6 files changed

+95
-52
lines changed

Cargo.lock

Lines changed: 54 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@ edition = "2021"
1212
clap = { version = "4.5.2", features = ["derive"] }
1313
console = "0.15.8"
1414
glob = "0.3.0"
15-
home = "0.5.9"
1615
indicatif = "0.17.8"
1716
notify-debouncer-mini = "0.4.1"
1817
regex = "1.10.3"
1918
serde_json = "1.0.114"
2019
serde = { version = "1.0.197", features = ["derive"] }
2120
toml_edit = { version = "0.22.9", default-features = false, features = ["parse", "serde"] }
21+
which = "6.0.1"
2222

2323
[[bin]]
2424
name = "rustlings"

src/exercise.rs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::fmt::{self, Display, Formatter};
55
use std::fs::{self, remove_file, File};
66
use std::io::Read;
77
use std::path::PathBuf;
8-
use std::process::{self, Command};
8+
use std::process::{self, Command, Stdio};
99

1010
const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"];
1111
const RUSTC_EDITION_ARGS: &[&str] = &["--edition", "2021"];
@@ -58,7 +58,7 @@ pub struct Exercise {
5858

5959
// An enum to track of the state of an Exercise.
6060
// An Exercise can be either Done or Pending
61-
#[derive(PartialEq, Debug)]
61+
#[derive(PartialEq, Eq, Debug)]
6262
pub enum State {
6363
// The state of the exercise once it's been completed
6464
Done,
@@ -67,7 +67,7 @@ pub enum State {
6767
}
6868

6969
// The context information of a pending exercise
70-
#[derive(PartialEq, Debug)]
70+
#[derive(PartialEq, Eq, Debug)]
7171
pub struct ContextLine {
7272
// The source code that is still pending completion
7373
pub line: String,
@@ -148,7 +148,10 @@ path = "{}.rs""#,
148148
.args(RUSTC_COLOR_ARGS)
149149
.args(RUSTC_EDITION_ARGS)
150150
.args(RUSTC_NO_DEBUG_ARGS)
151-
.output()
151+
.stdin(Stdio::null())
152+
.stdout(Stdio::null())
153+
.stderr(Stdio::null())
154+
.status()
152155
.expect("Failed to compile!");
153156
// Due to an issue with Clippy, a cargo clean is required to catch all lints.
154157
// See https://github.com/rust-lang/rust-clippy/issues/2604
@@ -157,7 +160,10 @@ path = "{}.rs""#,
157160
Command::new("cargo")
158161
.args(["clean", "--manifest-path", CLIPPY_CARGO_TOML_PATH])
159162
.args(RUSTC_COLOR_ARGS)
160-
.output()
163+
.stdin(Stdio::null())
164+
.stdout(Stdio::null())
165+
.stderr(Stdio::null())
166+
.status()
161167
.expect("Failed to run 'cargo clean'");
162168
Command::new("cargo")
163169
.args(["clippy", "--manifest-path", CLIPPY_CARGO_TOML_PATH])

src/main.rs

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use std::ffi::OsStr;
1010
use std::fs;
1111
use std::io::{self, prelude::*};
1212
use std::path::Path;
13-
use std::process::{Command, Stdio};
13+
use std::process::Command;
1414
use std::sync::atomic::{AtomicBool, Ordering};
1515
use std::sync::mpsc::{channel, RecvTimeoutError};
1616
use std::sync::{Arc, Mutex};
@@ -91,7 +91,7 @@ fn main() {
9191
println!("\n{WELCOME}\n");
9292
}
9393

94-
if !rustc_exists() {
94+
if which::which("rustc").is_err() {
9595
println!("We cannot find `rustc`.");
9696
println!("Try running `rustc --version` to diagnose your problem.");
9797
println!("For instructions on how to install Rust, check the README.");
@@ -218,16 +218,13 @@ fn main() {
218218
println!("Failed to write rust-project.json to disk for rust-analyzer");
219219
} else {
220220
println!("Successfully generated rust-project.json");
221-
println!("rust-analyzer will now parse exercises, restart your language server or editor")
221+
println!("rust-analyzer will now parse exercises, restart your language server or editor");
222222
}
223223
}
224224

225225
Subcommands::Watch { success_hints } => match watch(&exercises, verbose, success_hints) {
226226
Err(e) => {
227-
println!(
228-
"Error: Could not watch your progress. Error message was {:?}.",
229-
e
230-
);
227+
println!("Error: Could not watch your progress. Error message was {e:?}.");
231228
println!("Most likely you've run out of disk space or your 'inotify limit' has been reached.");
232229
std::process::exit(1);
233230
}
@@ -281,7 +278,7 @@ fn spawn_watch_shell(
281278
if parts.is_empty() {
282279
println!("no command provided");
283280
} else if let Err(e) = Command::new(parts[0]).args(&parts[1..]).status() {
284-
println!("failed to execute command `{}`: {}", cmd, e);
281+
println!("failed to execute command `{cmd}`: {e}");
285282
}
286283
} else {
287284
println!("unknown command: {input}");
@@ -293,7 +290,7 @@ fn spawn_watch_shell(
293290
}
294291

295292
fn find_exercise<'a>(name: &str, exercises: &'a [Exercise]) -> &'a Exercise {
296-
if name.eq("next") {
293+
if name == "next" {
297294
exercises
298295
.iter()
299296
.find(|e| !e.looks_done())
@@ -339,15 +336,14 @@ fn watch(
339336

340337
clear_screen();
341338

342-
let to_owned_hint = |t: &Exercise| t.hint.to_owned();
343339
let failed_exercise_hint = match verify(
344340
exercises.iter(),
345341
(0, exercises.len()),
346342
verbose,
347343
success_hints,
348344
) {
349345
Ok(_) => return Ok(WatchStatus::Finished),
350-
Err(exercise) => Arc::new(Mutex::new(Some(to_owned_hint(exercise)))),
346+
Err(exercise) => Arc::new(Mutex::new(Some(exercise.hint.clone()))),
351347
};
352348
spawn_watch_shell(&failed_exercise_hint, Arc::clone(&should_quit));
353349
loop {
@@ -384,7 +380,7 @@ fn watch(
384380
Err(exercise) => {
385381
let mut failed_exercise_hint =
386382
failed_exercise_hint.lock().unwrap();
387-
*failed_exercise_hint = Some(to_owned_hint(exercise));
383+
*failed_exercise_hint = Some(exercise.hint.clone());
388384
}
389385
}
390386
}
@@ -404,19 +400,7 @@ fn watch(
404400
}
405401
}
406402

407-
fn rustc_exists() -> bool {
408-
Command::new("rustc")
409-
.args(["--version"])
410-
.stdout(Stdio::null())
411-
.stderr(Stdio::null())
412-
.stdin(Stdio::null())
413-
.spawn()
414-
.and_then(|mut child| child.wait())
415-
.map(|status| status.success())
416-
.unwrap_or(false)
417-
}
418-
419-
const DEFAULT_OUT: &str = r#"Thanks for installing Rustlings!
403+
const DEFAULT_OUT: &str = "Thanks for installing Rustlings!
420404
421405
Is this your first time? Don't worry, Rustlings was made for beginners! We are
422406
going to teach you a lot of things about Rust, but before we can get
@@ -442,7 +426,7 @@ started, here's a couple of notes about how Rustlings operates:
442426
autocompletion, run the command `rustlings lsp`.
443427
444428
Got all that? Great! To get started, run `rustlings watch` in order to get the first
445-
exercise. Make sure to have your editor open!"#;
429+
exercise. Make sure to have your editor open!";
446430

447431
const FENISH_LINE: &str = "+----------------------------------------------------+
448432
| You made it to the Fe-nish line! |

src/run.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ pub fn run(exercise: &Exercise, verbose: bool) -> Result<(), ()> {
2121
// Resets the exercise by stashing the changes.
2222
pub fn reset(exercise: &Exercise) -> Result<(), ()> {
2323
let command = Command::new("git")
24-
.args(["stash", "--"])
24+
.arg("stash")
25+
.arg("--")
2526
.arg(&exercise.path)
2627
.spawn();
2728

src/verify.rs

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ pub fn verify<'a>(
2424
.progress_chars("#>-"),
2525
);
2626
bar.set_position(num_done as u64);
27-
bar.set_message(format!("({:.1} %)", percentage));
27+
bar.set_message(format!("({percentage:.1} %)"));
2828

2929
for exercise in exercises {
3030
let compile_result = match exercise.mode {
@@ -37,7 +37,7 @@ pub fn verify<'a>(
3737
}
3838
percentage += 100.0 / total as f32;
3939
bar.inc(1);
40-
bar.set_message(format!("({:.1} %)", percentage));
40+
bar.set_message(format!("({percentage:.1} %)"));
4141
if bar.position() == total as u64 {
4242
println!(
4343
"Progress: You completed {} / {} exercises ({:.1} %).",
@@ -51,6 +51,7 @@ pub fn verify<'a>(
5151
Ok(())
5252
}
5353

54+
#[derive(PartialEq, Eq)]
5455
enum RunMode {
5556
Interactive,
5657
NonInteractive,
@@ -124,7 +125,7 @@ fn compile_and_test(
124125
if verbose {
125126
println!("{}", output.stdout);
126127
}
127-
if let RunMode::Interactive = run_mode {
128+
if run_mode == RunMode::Interactive {
128129
Ok(prompt_for_completion(exercise, None, success_hints))
129130
} else {
130131
Ok(true)
@@ -191,27 +192,25 @@ fn prompt_for_completion(
191192
Mode::Test => "The code is compiling, and the tests pass!",
192193
Mode::Clippy => clippy_success_msg,
193194
};
194-
println!();
195+
195196
if no_emoji {
196-
println!("~*~ {success_msg} ~*~")
197+
println!("\n~*~ {success_msg} ~*~\n");
197198
} else {
198-
println!("🎉 🎉 {success_msg} 🎉 🎉")
199+
println!("\n🎉 🎉 {success_msg} 🎉 🎉\n");
199200
}
200-
println!();
201201

202202
if let Some(output) = prompt_output {
203-
println!("Output:");
204-
println!("{}", separator());
205-
println!("{output}");
206-
println!("{}", separator());
207-
println!();
203+
println!(
204+
"Output:\n{separator}\n{output}\n{separator}\n",
205+
separator = separator(),
206+
);
208207
}
209208
if success_hints {
210-
println!("Hints:");
211-
println!("{}", separator());
212-
println!("{}", exercise.hint);
213-
println!("{}", separator());
214-
println!();
209+
println!(
210+
"Hints:\n{separator}\n{}\n{separator}\n",
211+
exercise.hint,
212+
separator = separator(),
213+
);
215214
}
216215

217216
println!("You can keep working on this exercise,");
@@ -231,7 +230,7 @@ fn prompt_for_completion(
231230
"{:>2} {} {}",
232231
style(context_line.number).blue().bold(),
233232
style("|").blue(),
234-
formatted_line
233+
formatted_line,
235234
);
236235
}
237236

0 commit comments

Comments
 (0)