1
0
mirror of https://github.com/rust-lang/rustlings.git synced 2025-12-01 22:51:45 +02:00

Merge branch 'main' into watch

This commit is contained in:
mo8it
2024-03-27 14:41:26 +01:00
6 changed files with 110 additions and 78 deletions

View File

@@ -5,7 +5,7 @@ use std::fmt::{self, Display, Formatter};
use std::fs::{self, remove_file, File};
use std::io::Read;
use std::path::PathBuf;
use std::process::{self, Command};
use std::process::{self, Command, Stdio};
const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"];
const RUSTC_EDITION_ARGS: &[&str] = &["--edition", "2021"];
@@ -58,7 +58,7 @@ pub struct Exercise {
// An enum to track of the state of an Exercise.
// An Exercise can be either Done or Pending
#[derive(PartialEq, Debug)]
#[derive(PartialEq, Eq, Debug)]
pub enum State {
// The state of the exercise once it's been completed
Done,
@@ -67,7 +67,7 @@ pub enum State {
}
// The context information of a pending exercise
#[derive(PartialEq, Debug)]
#[derive(PartialEq, Eq, Debug)]
pub struct ContextLine {
// The source code that is still pending completion
pub line: String,
@@ -148,7 +148,10 @@ path = "{}.rs""#,
.args(RUSTC_COLOR_ARGS)
.args(RUSTC_EDITION_ARGS)
.args(RUSTC_NO_DEBUG_ARGS)
.output()
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.expect("Failed to compile!");
// Due to an issue with Clippy, a cargo clean is required to catch all lints.
// See https://github.com/rust-lang/rust-clippy/issues/2604
@@ -157,7 +160,10 @@ path = "{}.rs""#,
Command::new("cargo")
.args(["clean", "--manifest-path", CLIPPY_CARGO_TOML_PATH])
.args(RUSTC_COLOR_ARGS)
.output()
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.expect("Failed to run 'cargo clean'");
Command::new("cargo")
.args(["clippy", "--manifest-path", CLIPPY_CARGO_TOML_PATH])

View File

@@ -11,7 +11,7 @@ use std::ffi::OsStr;
use std::fs;
use std::io::{self, prelude::*};
use std::path::Path;
use std::process::{Command, Stdio};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, RecvTimeoutError};
use std::sync::{Arc, Mutex};
@@ -92,24 +92,25 @@ fn main() {
println!("\n{WELCOME}\n");
}
if !Path::new("info.toml").exists() {
println!(
"{} must be run from the rustlings directory",
std::env::current_exe().unwrap().to_str().unwrap()
);
println!("Try `cd rustlings/`!");
std::process::exit(1);
}
if !rustc_exists() {
if which::which("rustc").is_err() {
println!("We cannot find `rustc`.");
println!("Try running `rustc --version` to diagnose your problem.");
println!("For instructions on how to install Rust, check the README.");
std::process::exit(1);
}
let toml_str = &fs::read_to_string("info.toml").unwrap();
let exercises = toml::from_str::<ExerciseList>(toml_str).unwrap().exercises;
let info_file = fs::read_to_string("info.toml").unwrap_or_else(|e| {
match e.kind() {
io::ErrorKind::NotFound => println!(
"The program must be run from the rustlings directory\nTry `cd rustlings/`!",
),
_ => println!("Failed to read the info.toml file: {e}"),
}
std::process::exit(1);
});
let exercises = toml_edit::de::from_str::<ExerciseList>(&info_file)
.unwrap()
.exercises;
let verbose = args.nocapture;
let command = args.command.unwrap_or_else(|| {
@@ -218,16 +219,13 @@ fn main() {
println!("Failed to write rust-project.json to disk for rust-analyzer");
} else {
println!("Successfully generated rust-project.json");
println!("rust-analyzer will now parse exercises, restart your language server or editor")
println!("rust-analyzer will now parse exercises, restart your language server or editor");
}
}
Subcommands::Watch { success_hints } => match watch(&exercises, verbose, success_hints) {
Err(e) => {
println!(
"Error: Could not watch your progress. Error message was {:?}.",
e
);
println!("Error: Could not watch your progress. Error message was {e:?}.");
println!("Most likely you've run out of disk space or your 'inotify limit' has been reached.");
std::process::exit(1);
}
@@ -295,7 +293,7 @@ fn spawn_watch_shell(
}
fn find_exercise<'a>(name: &str, exercises: &'a [Exercise]) -> &'a Exercise {
if name.eq("next") {
if name == "next" {
exercises
.iter()
.find(|e| !e.looks_done())
@@ -341,7 +339,6 @@ fn watch(
clear_screen();
let to_owned_hint = |t: &Exercise| t.hint.to_owned();
let failed_exercise_hint = match verify(
exercises.iter(),
(0, exercises.len()),
@@ -349,7 +346,7 @@ fn watch(
success_hints,
) {
Ok(_) => return Ok(WatchStatus::Finished),
Err(exercise) => Arc::new(Mutex::new(Some(to_owned_hint(exercise)))),
Err(exercise) => Arc::new(Mutex::new(Some(exercise.hint.clone()))),
};
spawn_watch_shell(Arc::clone(&failed_exercise_hint), Arc::clone(&should_quit));
loop {
@@ -386,7 +383,7 @@ fn watch(
Err(exercise) => {
let mut failed_exercise_hint =
failed_exercise_hint.lock().unwrap();
*failed_exercise_hint = Some(to_owned_hint(exercise));
*failed_exercise_hint = Some(exercise.hint.clone());
}
}
}
@@ -406,19 +403,7 @@ fn watch(
}
}
fn rustc_exists() -> bool {
Command::new("rustc")
.args(["--version"])
.stdout(Stdio::null())
.stderr(Stdio::null())
.stdin(Stdio::null())
.spawn()
.and_then(|mut child| child.wait())
.map(|status| status.success())
.unwrap_or(false)
}
const DEFAULT_OUT: &str = r#"Thanks for installing Rustlings!
const DEFAULT_OUT: &str = "Thanks for installing Rustlings!
Is this your first time? Don't worry, Rustlings was made for beginners! We are
going to teach you a lot of things about Rust, but before we can get
@@ -444,7 +429,7 @@ started, here's a couple of notes about how Rustlings operates:
autocompletion, run the command `rustlings lsp`.
Got all that? Great! To get started, run `rustlings watch` in order to get the first
exercise. Make sure to have your editor open!"#;
exercise. Make sure to have your editor open!";
const FENISH_LINE: &str = "+----------------------------------------------------+
| You made it to the Fe-nish line! |

View File

@@ -21,7 +21,8 @@ pub fn run(exercise: &Exercise, verbose: bool) -> Result<(), ()> {
// Resets the exercise by stashing the changes.
pub fn reset(exercise: &Exercise) -> Result<(), ()> {
let command = Command::new("git")
.args(["stash", "--"])
.arg("stash")
.arg("--")
.arg(&exercise.path)
.spawn();

View File

@@ -24,7 +24,7 @@ pub fn verify<'a>(
.progress_chars("#>-"),
);
bar.set_position(num_done as u64);
bar.set_message(format!("({:.1} %)", percentage));
bar.set_message(format!("({percentage:.1} %)"));
for exercise in exercises {
let compile_result = match exercise.mode {
@@ -37,7 +37,7 @@ pub fn verify<'a>(
}
percentage += 100.0 / total as f32;
bar.inc(1);
bar.set_message(format!("({:.1} %)", percentage));
bar.set_message(format!("({percentage:.1} %)"));
if bar.position() == total as u64 {
println!(
"Progress: You completed {} / {} exercises ({:.1} %).",
@@ -51,6 +51,7 @@ pub fn verify<'a>(
Ok(())
}
#[derive(PartialEq, Eq)]
enum RunMode {
Interactive,
NonInteractive,
@@ -124,7 +125,7 @@ fn compile_and_test(
if verbose {
println!("{}", output.stdout);
}
if let RunMode::Interactive = run_mode {
if run_mode == RunMode::Interactive {
Ok(prompt_for_completion(exercise, None, success_hints))
} else {
Ok(true)
@@ -191,27 +192,25 @@ fn prompt_for_completion(
Mode::Test => "The code is compiling, and the tests pass!",
Mode::Clippy => clippy_success_msg,
};
println!();
if no_emoji {
println!("~*~ {success_msg} ~*~")
println!("\n~*~ {success_msg} ~*~\n");
} else {
println!("🎉 🎉 {success_msg} 🎉 🎉")
println!("\n🎉 🎉 {success_msg} 🎉 🎉\n");
}
println!();
if let Some(output) = prompt_output {
println!("Output:");
println!("{}", separator());
println!("{output}");
println!("{}", separator());
println!();
println!(
"Output:\n{separator}\n{output}\n{separator}\n",
separator = separator(),
);
}
if success_hints {
println!("Hints:");
println!("{}", separator());
println!("{}", exercise.hint);
println!("{}", separator());
println!();
println!(
"Hints:\n{separator}\n{}\n{separator}\n",
exercise.hint,
separator = separator(),
);
}
println!("You can keep working on this exercise,");
@@ -231,7 +230,7 @@ fn prompt_for_completion(
"{:>2} {} {}",
style(context_line.number).blue().bold(),
style("|").blue(),
formatted_line
formatted_line,
);
}