diff options
| author | mo8it <mo8it@proton.me> | 2024-07-05 13:39:50 +0200 |
|---|---|---|
| committer | mo8it <mo8it@proton.me> | 2024-07-05 13:39:50 +0200 |
| commit | 7123c7ae3a9605fbe962e4ef0a0f1424cd16fef8 (patch) | |
| tree | c67f7e62bb9a179ae4fdbab492501cb6847e64c7 /src/dev | |
| parent | 77b687d501771c24bd83294d97b8e6f9ffa92d6b (diff) | |
| parent | 4d9c346a173bb722b929f3ea3c00f84954483e24 (diff) | |
Merge remote-tracking branch 'upstream/main' into fix-enum-variant-inconsistency
Diffstat (limited to 'src/dev')
| -rw-r--r-- | src/dev/check.rs | 296 | ||||
| -rw-r--r-- | src/dev/new.rs | 145 | ||||
| -rw-r--r-- | src/dev/update.rs | 50 |
3 files changed, 491 insertions, 0 deletions
diff --git a/src/dev/check.rs b/src/dev/check.rs new file mode 100644 index 0000000..5c35462 --- /dev/null +++ b/src/dev/check.rs @@ -0,0 +1,296 @@ +use anyhow::{anyhow, bail, Context, Result}; +use std::{ + cmp::Ordering, + fs::{self, read_dir, OpenOptions}, + io::{self, Read, Write}, + path::{Path, PathBuf}, + sync::{ + atomic::{self, AtomicBool}, + Mutex, + }, + thread, +}; + +use crate::{ + app_state::parse_target_dir, + cargo_toml::{append_bins, bins_start_end_ind, BINS_BUFFER_CAPACITY}, + exercise::{RunnableExercise, OUTPUT_CAPACITY}, + info_file::{ExerciseInfo, InfoFile}, + CURRENT_FORMAT_VERSION, DEBUG_PROFILE, +}; + +// Find a char that isn't allowed in the exercise's `name` or `dir`. +fn forbidden_char(input: &str) -> Option<char> { + input.chars().find(|c| !c.is_alphanumeric() && *c != '_') +} + +// Check that the Cargo.toml file is up-to-date. +fn check_cargo_toml( + exercise_infos: &[ExerciseInfo], + current_cargo_toml: &str, + exercise_path_prefix: &[u8], +) -> Result<()> { + let (bins_start_ind, bins_end_ind) = bins_start_end_ind(current_cargo_toml)?; + + let old_bins = ¤t_cargo_toml.as_bytes()[bins_start_ind..bins_end_ind]; + let mut new_bins = Vec::with_capacity(BINS_BUFFER_CAPACITY); + append_bins(&mut new_bins, exercise_infos, exercise_path_prefix); + + if old_bins != new_bins { + if DEBUG_PROFILE { + bail!("The file `dev/Cargo.toml` is outdated. Please run `cargo run -- dev update` to update it"); + } + + bail!("The file `Cargo.toml` is outdated. Please run `rustlings dev update` to update it"); + } + + Ok(()) +} + +// Check the info of all exercises and return their paths in a set. +fn check_info_file_exercises(info_file: &InfoFile) -> Result<hashbrown::HashSet<PathBuf>> { + let mut names = hashbrown::HashSet::with_capacity(info_file.exercises.len()); + let mut paths = hashbrown::HashSet::with_capacity(info_file.exercises.len()); + + let mut file_buf = String::with_capacity(1 << 14); + for exercise_info in &info_file.exercises { + let name = exercise_info.name.as_str(); + if name.is_empty() { + bail!("Found an empty exercise name in `info.toml`"); + } + if let Some(c) = forbidden_char(name) { + bail!("Char `{c}` in the exercise name `{name}` is not allowed"); + } + + if let Some(dir) = &exercise_info.dir { + if dir.is_empty() { + bail!("The exercise `{name}` has an empty dir name in `info.toml`"); + } + if let Some(c) = forbidden_char(dir) { + bail!("Char `{c}` in the exercise dir `{dir}` is not allowed"); + } + } + + if exercise_info.hint.trim().is_empty() { + bail!("The exercise `{name}` has an empty hint. Please provide a hint or at least tell the user why a hint isn't needed for this exercise"); + } + + if !names.insert(name) { + bail!("The exercise name `{name}` is duplicated. Exercise names must all be unique"); + } + + let path = exercise_info.path(); + + OpenOptions::new() + .read(true) + .open(&path) + .with_context(|| format!("Failed to open the file {path}"))? + .read_to_string(&mut file_buf) + .with_context(|| format!("Failed to read the file {path}"))?; + + if !file_buf.contains("fn main()") { + bail!("The `main` function is missing in the file `{path}`.\nCreate at least an empty `main` function to avoid language server errors"); + } + + if !file_buf.contains("// TODO") { + bail!("Didn't find any `// TODO` comment in the file `{path}`.\nYou need to have at least one such comment to guide the user."); + } + + if !exercise_info.test && file_buf.contains("#[test]") { + bail!("The file `{path}` contains tests annotated with `#[test]` but the exercise `{name}` has `test = false` in the `info.toml` file"); + } + + file_buf.clear(); + + paths.insert(PathBuf::from(path)); + } + + Ok(paths) +} + +// Check `dir` for unexpected files. +// Only Rust files in `allowed_rust_files` and `README.md` files are allowed. +// Only one level of directory nesting is allowed. +fn check_unexpected_files( + dir: &str, + allowed_rust_files: &hashbrown::HashSet<PathBuf>, +) -> Result<()> { + let unexpected_file = |path: &Path| { + anyhow!("Found the file `{}`. Only `README.md` and Rust files related to an exercise in `info.toml` are allowed in the `{dir}` directory", path.display()) + }; + + for entry in read_dir(dir).with_context(|| format!("Failed to open the `{dir}` directory"))? { + let entry = entry.with_context(|| format!("Failed to read the `{dir}` directory"))?; + + if entry.file_type().unwrap().is_file() { + let path = entry.path(); + let file_name = path.file_name().unwrap(); + if file_name == "README.md" { + continue; + } + + if !allowed_rust_files.contains(&path) { + return Err(unexpected_file(&path)); + } + + continue; + } + + let dir_path = entry.path(); + for entry in read_dir(&dir_path) + .with_context(|| format!("Failed to open the directory {}", dir_path.display()))? + { + let entry = entry + .with_context(|| format!("Failed to read the directory {}", dir_path.display()))?; + let path = entry.path(); + + if !entry.file_type().unwrap().is_file() { + bail!("Found `{}` but expected only files. Only one level of exercise nesting is allowed", path.display()); + } + + let file_name = path.file_name().unwrap(); + if file_name == "README.md" { + continue; + } + + if !allowed_rust_files.contains(&path) { + return Err(unexpected_file(&path)); + } + } + } + + Ok(()) +} + +fn check_exercises_unsolved(info_file: &InfoFile, target_dir: &Path) -> Result<()> { + let error_occurred = AtomicBool::new(false); + + println!( + "Running all exercises to check that they aren't already solved. This may take a while…\n", + ); + thread::scope(|s| { + for exercise_info in &info_file.exercises { + if exercise_info.skip_check_unsolved { + continue; + } + + s.spawn(|| { + let error = |e| { + let mut stderr = io::stderr().lock(); + stderr.write_all(e).unwrap(); + stderr.write_all(b"\nProblem with the exercise ").unwrap(); + stderr.write_all(exercise_info.name.as_bytes()).unwrap(); + stderr.write_all(SEPARATOR).unwrap(); + error_occurred.store(true, atomic::Ordering::Relaxed); + }; + + let mut output = Vec::with_capacity(OUTPUT_CAPACITY); + match exercise_info.run_exercise(&mut output, target_dir) { + Ok(true) => error(b"Already solved!"), + Ok(false) => (), + Err(e) => error(e.to_string().as_bytes()), + } + }); + } + }); + + if error_occurred.load(atomic::Ordering::Relaxed) { + bail!(CHECK_EXERCISES_UNSOLVED_ERR); + } + + Ok(()) +} + +fn check_exercises(info_file: &InfoFile, target_dir: &Path) -> Result<()> { + match info_file.format_version.cmp(&CURRENT_FORMAT_VERSION) { + Ordering::Less => bail!("`format_version` < {CURRENT_FORMAT_VERSION} (supported version)\nPlease migrate to the latest format version"), + Ordering::Greater => bail!("`format_version` > {CURRENT_FORMAT_VERSION} (supported version)\nTry updating the Rustlings program"), + Ordering::Equal => (), + } + + let info_file_paths = check_info_file_exercises(info_file)?; + check_unexpected_files("exercises", &info_file_paths)?; + + check_exercises_unsolved(info_file, target_dir) +} + +fn check_solutions(require_solutions: bool, info_file: &InfoFile, target_dir: &Path) -> Result<()> { + let paths = Mutex::new(hashbrown::HashSet::with_capacity(info_file.exercises.len())); + let error_occurred = AtomicBool::new(false); + + println!("Running all solutions. This may take a while…\n"); + thread::scope(|s| { + for exercise_info in &info_file.exercises { + s.spawn(|| { + let error = |e| { + let mut stderr = io::stderr().lock(); + stderr.write_all(e).unwrap(); + stderr + .write_all(b"\nFailed to run the solution of the exercise ") + .unwrap(); + stderr.write_all(exercise_info.name.as_bytes()).unwrap(); + stderr.write_all(SEPARATOR).unwrap(); + error_occurred.store(true, atomic::Ordering::Relaxed); + }; + + let path = exercise_info.sol_path(); + if !Path::new(&path).exists() { + if require_solutions { + error(b"Solution missing"); + } + + // No solution to check. + return; + } + + let mut output = Vec::with_capacity(OUTPUT_CAPACITY); + match exercise_info.run_solution(&mut output, target_dir) { + Ok(true) => { + paths.lock().unwrap().insert(PathBuf::from(path)); + } + Ok(false) => error(&output), + Err(e) => error(e.to_string().as_bytes()), + } + }); + } + }); + + if error_occurred.load(atomic::Ordering::Relaxed) { + bail!("At least one solution failed. See the output above."); + } + + check_unexpected_files("solutions", &paths.into_inner().unwrap())?; + + Ok(()) +} + +pub fn check(require_solutions: bool) -> Result<()> { + let info_file = InfoFile::parse()?; + + // A hack to make `cargo run -- dev check` work when developing Rustlings. + if DEBUG_PROFILE { + check_cargo_toml( + &info_file.exercises, + include_str!("../../dev-Cargo.toml"), + b"../", + )?; + } else { + let current_cargo_toml = + fs::read_to_string("Cargo.toml").context("Failed to read the file `Cargo.toml`")?; + check_cargo_toml(&info_file.exercises, ¤t_cargo_toml, b"")?; + } + + let target_dir = parse_target_dir()?; + check_exercises(&info_file, &target_dir)?; + check_solutions(require_solutions, &info_file, &target_dir)?; + + println!("\nEverything looks fine!"); + + Ok(()) +} + +const SEPARATOR: &[u8] = + b"\n========================================================================================\n"; + +const CHECK_EXERCISES_UNSOLVED_ERR: &str = "At least one exercise is already solved or failed to run. See the output above. +If this is an intro exercise that is intended to be already solved, add `skip_check_unsolved = true` to the exercise's metadata in the `info.toml` file."; diff --git a/src/dev/new.rs b/src/dev/new.rs new file mode 100644 index 0000000..fefc4fc --- /dev/null +++ b/src/dev/new.rs @@ -0,0 +1,145 @@ +use anyhow::{bail, Context, Result}; +use std::{ + env::set_current_dir, + fs::{self, create_dir}, + path::Path, + process::Command, +}; + +use crate::CURRENT_FORMAT_VERSION; + +// Create a directory relative to the current directory and print its path. +fn create_rel_dir(dir_name: &str, current_dir: &str) -> Result<()> { + create_dir(dir_name) + .with_context(|| format!("Failed to create the directory {current_dir}/{dir_name}"))?; + println!("Created the directory {current_dir}/{dir_name}"); + Ok(()) +} + +// Write a file relative to the current directory and print its path. +fn write_rel_file<C>(file_name: &str, current_dir: &str, content: C) -> Result<()> +where + C: AsRef<[u8]>, +{ + fs::write(file_name, content) + .with_context(|| format!("Failed to create the file {current_dir}/{file_name}"))?; + // Space to align with `create_rel_dir`. + println!("Created the file {current_dir}/{file_name}"); + Ok(()) +} + +pub fn new(path: &Path, no_git: bool) -> Result<()> { + let dir_path_str = path.to_string_lossy(); + + create_dir(path).with_context(|| format!("Failed to create the directory {dir_path_str}"))?; + println!("Created the directory {dir_path_str}"); + + set_current_dir(path) + .with_context(|| format!("Failed to set {dir_path_str} as the current directory"))?; + + if !no_git + && !Command::new("git") + .arg("init") + .status() + .context("Failed to run `git init`")? + .success() + { + bail!("`git init` didn't run successfully. See the possible error message above"); + } + + write_rel_file(".gitignore", &dir_path_str, GITIGNORE)?; + + create_rel_dir("exercises", &dir_path_str)?; + create_rel_dir("solutions", &dir_path_str)?; + + write_rel_file( + "info.toml", + &dir_path_str, + format!("{INFO_FILE_BEFORE_FORMAT_VERSION}{CURRENT_FORMAT_VERSION}{INFO_FILE_AFTER_FORMAT_VERSION}"), + )?; + + write_rel_file("Cargo.toml", &dir_path_str, CARGO_TOML)?; + + write_rel_file("README.md", &dir_path_str, README)?; + + create_rel_dir(".vscode", &dir_path_str)?; + write_rel_file( + ".vscode/extensions.json", + &dir_path_str, + crate::init::VS_CODE_EXTENSIONS_JSON, + )?; + + println!("\nInitialization done ✓"); + + Ok(()) +} + +pub const GITIGNORE: &[u8] = b".rustlings-state.txt +Cargo.lock +target +.vscode +!.vscode/extensions.json +"; + +const INFO_FILE_BEFORE_FORMAT_VERSION: &str = + "# The format version is an indicator of the compatibility of third-party exercises with the +# Rustlings program. +# The format version is not the same as the version of the Rustlings program. +# In case Rustlings makes an unavoidable breaking change to the expected format of third-party +# exercises, you would need to raise this version and adapt to the new format. +# Otherwise, the newest version of the Rustlings program won't be able to run these exercises. +format_version = "; + +const INFO_FILE_AFTER_FORMAT_VERSION: &str = r#" + +# Optional multi-line message to be shown to users when just starting with the exercises. +welcome_message = """Welcome to these third-party Rustlings exercises.""" + +# Optional multi-line message to be shown to users after finishing all exercises. +final_message = """We hope that you found the exercises helpful :D""" + +# Repeat this section for every exercise. +[[exercises]] +# Exercise name which is the exercise file name without the `.rs` extension. +name = "???" + +# Optional directory name to be provided if you want to organize exercises in directories. +# If `dir` is specified, the exercise path is `exercises/DIR/NAME.rs` +# Otherwise, the path is `exercises/NAME.rs` +# dir = "???" + +# Rustlings expects the exercise to contain tests and run them. +# You can optionally disable testing by setting `test` to `false` (the default is `true`). +# In that case, the exercise will be considered done when it just successfully compiles. +# test = true + +# Rustlings will always run Clippy on exercises. +# You can optionally set `strict_clippy` to `true` (the default is `false`) to only consider +# the exercise as done when there are no warnings left. +# strict_clippy = false + +# A multi-line hint to be shown to users on request. +hint = """???""" +"#; + +const CARGO_TOML: &[u8] = + br#"# Don't edit the `bin` list manually! It is updated by `rustlings dev update` +bin = [] + +[package] +name = "exercises" +edition = "2021" +# Don't publish the exercises on crates.io! +publish = false + +[dependencies] +"#; + +const README: &str = "# Rustlings 🦀 + +Welcome to these third-party Rustlings exercises 😃 + +First, [install Rustlings using the official instructions in the README of the Rustlings project](https://github.com/rust-lang/rustlings) ✅ + +Then, open your terminal in this directory and run `rustlings` to get started with the exercises 🚀 +"; diff --git a/src/dev/update.rs b/src/dev/update.rs new file mode 100644 index 0000000..66efe3d --- /dev/null +++ b/src/dev/update.rs @@ -0,0 +1,50 @@ +use anyhow::{Context, Result}; +use std::fs; + +use crate::{ + cargo_toml::updated_cargo_toml, + info_file::{ExerciseInfo, InfoFile}, + DEBUG_PROFILE, +}; + +// Update the `Cargo.toml` file. +fn update_cargo_toml( + exercise_infos: &[ExerciseInfo], + current_cargo_toml: &str, + exercise_path_prefix: &[u8], + cargo_toml_path: &str, +) -> Result<()> { + let updated_cargo_toml = + updated_cargo_toml(exercise_infos, current_cargo_toml, exercise_path_prefix)?; + + fs::write(cargo_toml_path, updated_cargo_toml) + .context("Failed to write the `Cargo.toml` file")?; + + Ok(()) +} + +pub fn update() -> Result<()> { + let info_file = InfoFile::parse()?; + + // A hack to make `cargo run -- dev update` work when developing Rustlings. + if DEBUG_PROFILE { + update_cargo_toml( + &info_file.exercises, + include_str!("../../dev-Cargo.toml"), + b"../", + "dev/Cargo.toml", + ) + .context("Failed to update the file `dev/Cargo.toml`")?; + + println!("Updated `dev/Cargo.toml`"); + } else { + let current_cargo_toml = + fs::read_to_string("Cargo.toml").context("Failed to read the file `Cargo.toml`")?; + update_cargo_toml(&info_file.exercises, ¤t_cargo_toml, b"", "Cargo.toml") + .context("Failed to update the file `Cargo.toml`")?; + + println!("Updated `Cargo.toml`"); + } + + Ok(()) +} |
