summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorDan <danbond@protonmail.com>2024-03-29 18:29:38 +0000
committerGitHub <noreply@github.com>2024-03-29 18:29:38 +0000
commit30273a6ee5a8666c236c47340d54dabbab604f9b (patch)
tree2a2d57987fbe6e11ac1cbe08aa5edf32051c7d18 /src
parenteb952a480d2dabcafa8b55e1a89872c9b5e4194b (diff)
parent9691c3cb55484ce9676c85ad4673b38e06100303 (diff)
Merge branch 'main' into main
Diffstat (limited to 'src')
-rw-r--r--src/exercise.rs182
-rw-r--r--src/main.rs208
-rw-r--r--src/project.rs139
-rw-r--r--src/run.rs3
-rw-r--r--src/ui.rs2
-rw-r--r--src/verify.rs37
6 files changed, 321 insertions, 250 deletions
diff --git a/src/exercise.rs b/src/exercise.rs
index 664b362..19f528a 100644
--- a/src/exercise.rs
+++ b/src/exercise.rs
@@ -1,19 +1,33 @@
-use regex::Regex;
use serde::Deserialize;
-use std::env;
use std::fmt::{self, Display, Formatter};
use std::fs::{self, remove_file, File};
-use std::io::Read;
+use std::io::{self, BufRead, BufReader};
use std::path::PathBuf;
-use std::process::{self, Command};
+use std::process::{self, exit, Command, Stdio};
+use std::{array, env, mem};
+use winnow::ascii::{space0, Caseless};
+use winnow::combinator::opt;
+use winnow::Parser;
const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"];
const RUSTC_EDITION_ARGS: &[&str] = &["--edition", "2021"];
const RUSTC_NO_DEBUG_ARGS: &[&str] = &["-C", "strip=debuginfo"];
-const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT\s+DONE";
const CONTEXT: usize = 2;
const CLIPPY_CARGO_TOML_PATH: &str = "./exercises/22_clippy/Cargo.toml";
+// Checks if the line contains the "I AM NOT DONE" comment.
+fn contains_not_done_comment(input: &str) -> bool {
+ (
+ space0::<_, ()>,
+ "//",
+ opt('/'),
+ space0,
+ Caseless("I AM NOT DONE"),
+ )
+ .parse_next(&mut &*input)
+ .is_ok()
+}
+
// Get a temporary file name that is hopefully unique
#[inline]
fn temp_file() -> String {
@@ -58,7 +72,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 +81,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 +162,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 +174,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])
@@ -205,51 +225,101 @@ path = "{}.rs""#,
}
pub fn state(&self) -> State {
- let mut source_file = File::open(&self.path).unwrap_or_else(|e| {
- panic!(
- "We were unable to open the exercise file {}! {e}",
- self.path.display()
- )
+ let source_file = File::open(&self.path).unwrap_or_else(|e| {
+ println!(
+ "Failed to open the exercise file {}: {e}",
+ self.path.display(),
+ );
+ exit(1);
});
-
- let source = {
- let mut s = String::new();
- source_file.read_to_string(&mut s).unwrap_or_else(|e| {
- panic!(
- "We were unable to read the exercise file {}! {e}",
- self.path.display()
- )
- });
- s
+ let mut source_reader = BufReader::new(source_file);
+
+ // Read the next line into `buf` without the newline at the end.
+ let mut read_line = |buf: &mut String| -> io::Result<_> {
+ let n = source_reader.read_line(buf)?;
+ if buf.ends_with('\n') {
+ buf.pop();
+ if buf.ends_with('\r') {
+ buf.pop();
+ }
+ }
+ Ok(n)
};
- let re = Regex::new(I_AM_DONE_REGEX).unwrap();
+ let mut current_line_number: usize = 1;
+ // Keep the last `CONTEXT` lines while iterating over the file lines.
+ let mut prev_lines: [_; CONTEXT] = array::from_fn(|_| String::with_capacity(256));
+ let mut line = String::with_capacity(256);
- if !re.is_match(&source) {
- return State::Done;
- }
+ loop {
+ let n = read_line(&mut line).unwrap_or_else(|e| {
+ println!(
+ "Failed to read the exercise file {}: {e}",
+ self.path.display(),
+ );
+ exit(1);
+ });
- let matched_line_index = source
- .lines()
- .enumerate()
- .find_map(|(i, line)| if re.is_match(line) { Some(i) } else { None })
- .expect("This should not happen at all");
-
- let min_line = ((matched_line_index as i32) - (CONTEXT as i32)).max(0) as usize;
- let max_line = matched_line_index + CONTEXT;
-
- let context = source
- .lines()
- .enumerate()
- .filter(|&(i, _)| i >= min_line && i <= max_line)
- .map(|(i, line)| ContextLine {
- line: line.to_string(),
- number: i + 1,
- important: i == matched_line_index,
- })
- .collect();
+ // Reached the end of the file and didn't find the comment.
+ if n == 0 {
+ return State::Done;
+ }
- State::Pending(context)
+ if contains_not_done_comment(&line) {
+ let mut context = Vec::with_capacity(2 * CONTEXT + 1);
+ // Previous lines.
+ for (ind, prev_line) in prev_lines
+ .into_iter()
+ .take(current_line_number - 1)
+ .enumerate()
+ .rev()
+ {
+ context.push(ContextLine {
+ line: prev_line,
+ number: current_line_number - 1 - ind,
+ important: false,
+ });
+ }
+
+ // Current line.
+ context.push(ContextLine {
+ line,
+ number: current_line_number,
+ important: true,
+ });
+
+ // Next lines.
+ for ind in 0..CONTEXT {
+ let mut next_line = String::with_capacity(256);
+ let Ok(n) = read_line(&mut next_line) else {
+ // If an error occurs, just ignore the next lines.
+ break;
+ };
+
+ // Reached the end of the file.
+ if n == 0 {
+ break;
+ }
+
+ context.push(ContextLine {
+ line: next_line,
+ number: current_line_number + 1 + ind,
+ important: false,
+ });
+ }
+
+ return State::Pending(context);
+ }
+
+ current_line_number += 1;
+ // Add the current line as a previous line and shift the older lines by one.
+ for prev_line in &mut prev_lines {
+ mem::swap(&mut line, prev_line);
+ }
+ // The current line now contains the oldest previous line.
+ // Recycle it for reading the next line.
+ line.clear();
+ }
}
// Check that the exercise looks to be solved using self.state()
@@ -375,4 +445,20 @@ mod test {
let out = exercise.compile().unwrap().run().unwrap();
assert!(out.stdout.contains("THIS TEST TOO SHALL PASS"));
}
+
+ #[test]
+ fn test_not_done() {
+ assert!(contains_not_done_comment("// I AM NOT DONE"));
+ assert!(contains_not_done_comment("/// I AM NOT DONE"));
+ assert!(contains_not_done_comment("// I AM NOT DONE"));
+ assert!(contains_not_done_comment("/// I AM NOT DONE"));
+ assert!(contains_not_done_comment("// I AM NOT DONE "));
+ assert!(contains_not_done_comment("// I AM NOT DONE!"));
+ assert!(contains_not_done_comment("// I am not done"));
+ assert!(contains_not_done_comment("// i am NOT done"));
+
+ assert!(!contains_not_done_comment("I AM NOT DONE"));
+ assert!(!contains_not_done_comment("// NOT DONE"));
+ assert!(!contains_not_done_comment("DONE"));
+ }
}
diff --git a/src/main.rs b/src/main.rs
index a06f0c5..8f73dbb 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,16 +1,18 @@
use crate::exercise::{Exercise, ExerciseList};
-use crate::project::RustAnalyzerProject;
+use crate::project::write_project_json;
use crate::run::{reset, run};
use crate::verify::verify;
+use anyhow::Result;
use clap::{Parser, Subcommand};
use console::Emoji;
use notify_debouncer_mini::notify::{self, RecursiveMode};
use notify_debouncer_mini::{new_debouncer, DebouncedEventKind};
+use shlex::Shlex;
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};
@@ -84,31 +86,32 @@ enum Subcommands {
Lsp,
}
-fn main() {
+fn main() -> Result<()> {
let args = Args::parse();
if args.command.is_none() {
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(|| {
@@ -128,31 +131,43 @@ fn main() {
println!("{:<17}\t{:<46}\t{:<7}", "Name", "Path", "Status");
}
let mut exercises_done: u16 = 0;
- let filters = filter.clone().unwrap_or_default().to_lowercase();
- exercises.iter().for_each(|e| {
- let fname = format!("{}", e.path.display());
+ let lowercase_filter = filter
+ .as_ref()
+ .map(|s| s.to_lowercase())
+ .unwrap_or_default();
+ let filters = lowercase_filter
+ .split(',')
+ .filter_map(|f| {
+ let f = f.trim();
+ if f.is_empty() {
+ None
+ } else {
+ Some(f)
+ }
+ })
+ .collect::<Vec<_>>();
+
+ for exercise in &exercises {
+ let fname = exercise.path.to_string_lossy();
let filter_cond = filters
- .split(',')
- .filter(|f| !f.trim().is_empty())
- .any(|f| e.name.contains(f) || fname.contains(f));
- let status = if e.looks_done() {
+ .iter()
+ .any(|f| exercise.name.contains(f) || fname.contains(f));
+ let looks_done = exercise.looks_done();
+ let status = if looks_done {
exercises_done += 1;
"Done"
} else {
"Pending"
};
- let solve_cond = {
- (e.looks_done() && solved)
- || (!e.looks_done() && unsolved)
- || (!solved && !unsolved)
- };
+ let solve_cond =
+ (looks_done && solved) || (!looks_done && unsolved) || (!solved && !unsolved);
if solve_cond && (filter_cond || filter.is_none()) {
let line = if paths {
format!("{fname}\n")
} else if names {
- format!("{}\n", e.name)
+ format!("{}\n", exercise.name)
} else {
- format!("{:<17}\t{fname:<46}\t{status:<7}\n", e.name)
+ format!("{:<17}\t{fname:<46}\t{status:<7}\n", exercise.name)
};
// Somehow using println! leads to the binary panicking
// when its output is piped.
@@ -168,7 +183,8 @@ fn main() {
});
}
}
- });
+ }
+
let percentage_progress = exercises_done as f32 / exercises.len() as f32 * 100.0;
println!(
"Progress: You completed {} / {} exercises ({:.1} %).",
@@ -203,30 +219,17 @@ fn main() {
}
Subcommands::Lsp => {
- let mut project = RustAnalyzerProject::new();
- project
- .get_sysroot_src()
- .expect("Couldn't find toolchain path, do you have `rustc` installed?");
- project
- .exercises_to_json()
- .expect("Couldn't parse rustlings exercises files");
-
- if project.crates.is_empty() {
- println!("Failed find any exercises, make sure you're in the `rustlings` folder");
- } else if project.write_to_disk().is_err() {
- println!("Failed to write rust-project.json to disk for rust-analyzer");
+ if let Err(e) = write_project_json(exercises) {
+ println!("Failed to write rust-project.json to disk for rust-analyzer: {e}");
} 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);
}
@@ -243,56 +246,60 @@ fn main() {
}
},
}
+
+ Ok(())
}
fn spawn_watch_shell(
- failed_exercise_hint: &Arc<Mutex<Option<String>>>,
+ failed_exercise_hint: Arc<Mutex<Option<String>>>,
should_quit: Arc<AtomicBool>,
) {
- let failed_exercise_hint = Arc::clone(failed_exercise_hint);
println!("Welcome to watch mode! You can type 'help' to get an overview of the commands you can use here.");
- thread::spawn(move || loop {
- let mut input = String::new();
- match io::stdin().read_line(&mut input) {
- Ok(_) => {
- let input = input.trim();
- if input == "hint" {
- if let Some(hint) = &*failed_exercise_hint.lock().unwrap() {
- println!("{hint}");
- }
- } else if input == "clear" {
- println!("\x1B[2J\x1B[1;1H");
- } else if input.eq("quit") {
- should_quit.store(true, Ordering::SeqCst);
- println!("Bye!");
- } else if input.eq("help") {
- println!("Commands available to you in watch mode:");
- println!(" hint - prints the current exercise's hint");
- println!(" clear - clears the screen");
- println!(" quit - quits watch mode");
- println!(" !<cmd> - executes a command, like `!rustc --explain E0381`");
- println!(" help - displays this help message");
- println!();
- println!("Watch mode automatically re-evaluates the current exercise");
- println!("when you edit a file's contents.")
- } else if let Some(cmd) = input.strip_prefix('!') {
- let parts: Vec<&str> = cmd.split_whitespace().collect();
- if parts.is_empty() {
- println!("no command provided");
- } else if let Err(e) = Command::new(parts[0]).args(&parts[1..]).status() {
- println!("failed to execute command `{}`: {}", cmd, e);
- }
- } else {
- println!("unknown command: {input}");
+
+ thread::spawn(move || {
+ let mut input = String::with_capacity(32);
+ let mut stdin = io::stdin().lock();
+
+ loop {
+ // Recycle input buffer.
+ input.clear();
+
+ if let Err(e) = stdin.read_line(&mut input) {
+ println!("error reading command: {e}");
+ }
+
+ let input = input.trim();
+ if input == "hint" {
+ if let Some(hint) = &*failed_exercise_hint.lock().unwrap() {
+ println!("{hint}");
}
+ } else if input == "clear" {
+ println!("\x1B[2J\x1B[1;1H");
+ } else if input == "quit" {
+ should_quit.store(true, Ordering::SeqCst);
+ println!("Bye!");
+ } else if input == "help" {
+ println!("{WATCH_MODE_HELP_MESSAGE}");
+ } else if let Some(cmd) = input.strip_prefix('!') {
+ let mut parts = Shlex::new(cmd);
+
+ let Some(program) = parts.next() else {
+ println!("no command provided");
+ continue;
+ };
+
+ if let Err(e) = Command::new(program).args(parts).status() {
+ println!("failed to execute command `{cmd}`: {e}");
+ }
+ } else {
+ println!("unknown command: {input}\n{WATCH_MODE_HELP_MESSAGE}");
}
- Err(error) => println!("error reading command: {error}"),
}
});
}
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())
@@ -338,7 +345,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()),
@@ -346,9 +352,9 @@ 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(&failed_exercise_hint, Arc::clone(&should_quit));
+ spawn_watch_shell(Arc::clone(&failed_exercise_hint), Arc::clone(&should_quit));
loop {
match rx.recv_timeout(Duration::from_secs(1)) {
Ok(event) => match event {
@@ -383,7 +389,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());
}
}
}
@@ -403,19 +409,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
@@ -441,7 +435,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! |
@@ -477,3 +471,13 @@ const WELCOME: &str = r" welcome to...
| | | |_| \__ \ |_| | | | | | (_| \__ \
|_| \__,_|___/\__|_|_|_| |_|\__, |___/
|___/";
+
+const WATCH_MODE_HELP_MESSAGE: &str = "Commands available to you in watch mode:
+ hint - prints the current exercise's hint
+ clear - clears the screen
+ quit - quits watch mode
+ !<cmd> - executes a command, like `!rustc --explain E0381`
+ help - displays this help message
+
+Watch mode automatically re-evaluates the current exercise
+when you edit a file's contents.";
diff --git a/src/project.rs b/src/project.rs
index 00fc304..0f56de9 100644
--- a/src/project.rs
+++ b/src/project.rs
@@ -1,102 +1,83 @@
-use glob::glob;
-use serde::{Deserialize, Serialize};
+use anyhow::{Context, Result};
+use serde::Serialize;
use std::env;
-use std::error::Error;
-use std::path::{Path, PathBuf};
-use std::process::Command;
+use std::path::PathBuf;
+use std::process::{Command, Stdio};
+
+use crate::exercise::Exercise;
/// Contains the structure of resulting rust-project.json file
/// and functions to build the data required to create the file
-#[derive(Serialize, Deserialize)]
-pub struct RustAnalyzerProject {
- sysroot_src: String,
- pub crates: Vec<Crate>,
+#[derive(Serialize)]
+struct RustAnalyzerProject {
+ sysroot_src: PathBuf,
+ crates: Vec<Crate>,
}
-#[derive(Serialize, Deserialize)]
-pub struct Crate {
- root_module: String,
- edition: String,
- deps: Vec<String>,
- cfg: Vec<String>,
+#[derive(Serialize)]
+struct Crate {
+ root_module: PathBuf,
+ edition: &'static str,
+ // Not used, but required in the JSON file.
+ deps: Vec<()>,
+ // Only `test` is used for all crates.
+ // Therefore, an array is used instead of a `Vec`.
+ cfg: [&'static str; 1],
}
impl RustAnalyzerProject {
- pub fn new() -> RustAnalyzerProject {
- RustAnalyzerProject {
- sysroot_src: String::new(),
- crates: Vec::new(),
- }
- }
-
- /// Write rust-project.json to disk
- pub fn write_to_disk(&self) -> Result<(), std::io::Error> {
- std::fs::write(
- "./rust-project.json",
- serde_json::to_vec(&self).expect("Failed to serialize to JSON"),
- )?;
- Ok(())
- }
+ fn build(exercises: Vec<Exercise>) -> Result<Self> {
+ let crates = exercises
+ .into_iter()
+ .map(|exercise| Crate {
+ root_module: exercise.path,
+ edition: "2021",
+ deps: Vec::new(),
+ // This allows rust_analyzer to work inside `#[test]` blocks
+ cfg: ["test"],
+ })
+ .collect();
- /// If path contains .rs extension, add a crate to `rust-project.json`
- fn path_to_json(&mut self, path: PathBuf) -> Result<(), Box<dyn Error>> {
- if let Some(ext) = path.extension() {
- if ext == "rs" {
- self.crates.push(Crate {
- root_module: path.display().to_string(),
- edition: "2021".to_string(),
- deps: Vec::new(),
- // This allows rust_analyzer to work inside #[test] blocks
- cfg: vec!["test".to_string()],
- })
- }
- }
-
- Ok(())
- }
-
- /// Parse the exercises folder for .rs files, any matches will create
- /// a new `crate` in rust-project.json which allows rust-analyzer to
- /// treat it like a normal binary
- pub fn exercises_to_json(&mut self) -> Result<(), Box<dyn Error>> {
- for path in glob("./exercises/**/*")? {
- self.path_to_json(path?)?;
- }
- Ok(())
- }
-
- /// Use `rustc` to determine the default toolchain
- pub fn get_sysroot_src(&mut self) -> Result<(), Box<dyn Error>> {
- // check if RUST_SRC_PATH is set
- if let Ok(path) = env::var("RUST_SRC_PATH") {
- self.sysroot_src = path;
- return Ok(());
+ if let Some(path) = env::var_os("RUST_SRC_PATH") {
+ return Ok(Self {
+ sysroot_src: PathBuf::from(path),
+ crates,
+ });
}
let toolchain = Command::new("rustc")
.arg("--print")
.arg("sysroot")
- .output()?
+ .stderr(Stdio::inherit())
+ .output()
+ .context("Failed to get the sysroot from `rustc`. Do you have `rustc` installed?")?
.stdout;
- let toolchain = String::from_utf8(toolchain)?;
+ let toolchain =
+ String::from_utf8(toolchain).context("The toolchain path is invalid UTF8")?;
let toolchain = toolchain.trim_end();
-
println!("Determined toolchain: {toolchain}\n");
- let Ok(path) = Path::new(toolchain)
- .join("lib")
- .join("rustlib")
- .join("src")
- .join("rust")
- .join("library")
- .into_os_string()
- .into_string()
- else {
- return Err("The sysroot path is invalid UTF8".into());
- };
- self.sysroot_src = path;
+ let mut sysroot_src = PathBuf::with_capacity(256);
+ sysroot_src.extend([toolchain, "lib", "rustlib", "src", "rust", "library"]);
- Ok(())
+ Ok(Self {
+ sysroot_src,
+ crates,
+ })
}
}
+
+/// Write `rust-project.json` to disk.
+pub fn write_project_json(exercises: Vec<Exercise>) -> Result<()> {
+ let content = RustAnalyzerProject::build(exercises)?;
+
+ // Using the capacity 2^14 since the file length in bytes is higher than 2^13.
+ // The final length is not known exactly because it depends on the user's sysroot path,
+ // the current number of exercises etc.
+ let mut buf = Vec::with_capacity(1 << 14);
+ serde_json::to_writer(&mut buf, &content)?;
+ std::fs::write("rust-project.json", buf)?;
+
+ Ok(())
+}
diff --git a/src/run.rs b/src/run.rs
index e0ada4c..6dd0388 100644
--- a/src/run.rs
+++ b/src/run.rs
@@ -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();
diff --git a/src/ui.rs b/src/ui.rs
index 74835e1..d8177b9 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -1,5 +1,5 @@
macro_rules! print_emoji {
- ($emoji:expr, $sign:expr, $color: ident ,$fmt:literal, $ex:expr) => {{
+ ($emoji:expr, $sign:expr, $color: ident, $fmt:literal, $ex:expr) => {{
use console::{style, Emoji};
use std::env;
let formatstr = format!($fmt, $ex);
diff --git a/src/verify.rs b/src/verify.rs
index cafecab..dac2562 100644
--- a/src/verify.rs
+++ b/src/verify.rs
@@ -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,");
@@ -224,14 +223,14 @@ fn prompt_for_completion(
let formatted_line = if context_line.important {
format!("{}", style(context_line.line).bold())
} else {
- context_line.line.to_string()
+ context_line.line
};
println!(
"{:>2} {} {}",
style(context_line.number).blue().bold(),
style("|").blue(),
- formatted_line
+ formatted_line,
);
}