Compare commits

..

4 commits

Author SHA1 Message Date
mo8it 5e7afce019 Document dev 2024-05-01 19:47:35 +02:00
mo8it 74180ba1cc Check for tests while test=false 2024-05-01 19:16:59 +02:00
mo8it d425dbe203 Test run_cmd 2024-05-01 18:08:18 +02:00
mo8it 32415e1e6c Document cmd 2024-05-01 17:55:49 +02:00
5 changed files with 65 additions and 40 deletions

View file

@ -1,6 +1,8 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use std::{io::Read, path::Path, process::Command}; use std::{io::Read, path::Path, process::Command};
// Run a command with a description for a possible error and append the merged stdout and stderr.
// The boolean in the returned `Result` is true if the command's exit status is success.
pub fn run_cmd(mut cmd: Command, description: &str, output: &mut Vec<u8>) -> Result<bool> { pub fn run_cmd(mut cmd: Command, description: &str, output: &mut Vec<u8>) -> Result<bool> {
let (mut reader, writer) = os_pipe::pipe() let (mut reader, writer) = os_pipe::pipe()
.with_context(|| format!("Failed to create a pipe to run the command `{description}``"))?; .with_context(|| format!("Failed to create a pipe to run the command `{description}``"))?;
@ -35,13 +37,18 @@ pub struct CargoCmd<'a> {
pub args: &'a [&'a str], pub args: &'a [&'a str],
pub exercise_name: &'a str, pub exercise_name: &'a str,
pub description: &'a str, pub description: &'a str,
// RUSTFLAGS="-A warnings"
pub hide_warnings: bool, pub hide_warnings: bool,
// Added as `--target-dir` if `Self::dev` is true.
pub target_dir: &'a Path, pub target_dir: &'a Path,
// The output buffer to append the merged stdout and stderr.
pub output: &'a mut Vec<u8>, pub output: &'a mut Vec<u8>,
// true while developing Rustlings.
pub dev: bool, pub dev: bool,
} }
impl<'a> CargoCmd<'a> { impl<'a> CargoCmd<'a> {
// Run `cargo SUBCOMMAND --bin EXERCISE_NAME … ARGS`.
pub fn run(&mut self) -> Result<bool> { pub fn run(&mut self) -> Result<bool> {
let mut cmd = Command::new("cargo"); let mut cmd = Command::new("cargo");
cmd.arg(self.subcommand); cmd.arg(self.subcommand);
@ -68,3 +75,19 @@ impl<'a> CargoCmd<'a> {
run_cmd(cmd, self.description, self.output) run_cmd(cmd, self.description, self.output)
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_run_cmd() {
let mut cmd = Command::new("echo");
cmd.arg("Hello");
let mut output = Vec::with_capacity(8);
run_cmd(cmd, "echo …", &mut output).unwrap();
assert_eq!(output, b"Hello\n\n");
}
}

View file

@ -1,7 +1,6 @@
use std::path::PathBuf;
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use clap::Subcommand; use clap::Subcommand;
use std::path::PathBuf;
use crate::DEBUG_PROFILE; use crate::DEBUG_PROFILE;

View file

@ -12,32 +12,29 @@ use crate::{
CURRENT_FORMAT_VERSION, DEBUG_PROFILE, 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> { fn forbidden_char(input: &str) -> Option<char> {
input.chars().find(|c| *c != '_' && !c.is_alphanumeric()) input.chars().find(|c| *c != '_' && !c.is_alphanumeric())
} }
// 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>> { 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 names = hashbrown::HashSet::with_capacity(info_file.exercises.len());
let mut paths = 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); let mut file_buf = String::with_capacity(1 << 14);
for exercise_info in &info_file.exercises { for exercise_info in &info_file.exercises {
if exercise_info.name.is_empty() { let name = exercise_info.name.as_str();
if name.is_empty() {
bail!("Found an empty exercise name in `info.toml`"); bail!("Found an empty exercise name in `info.toml`");
} }
if let Some(c) = forbidden_char(&exercise_info.name) { if let Some(c) = forbidden_char(name) {
bail!( bail!("Char `{c}` in the exercise name `{name}` is not allowed");
"Char `{c}` in the exercise name `{}` is not allowed",
exercise_info.name,
);
} }
if let Some(dir) = &exercise_info.dir { if let Some(dir) = &exercise_info.dir {
if dir.is_empty() { if dir.is_empty() {
bail!( bail!("The exercise `{name}` has an empty dir name in `info.toml`");
"The exercise `{}` has an empty dir name in `info.toml`",
exercise_info.name,
);
} }
if let Some(c) = forbidden_char(dir) { if let Some(c) = forbidden_char(dir) {
bail!("Char `{c}` in the exercise dir `{dir}` is not allowed"); bail!("Char `{c}` in the exercise dir `{dir}` is not allowed");
@ -45,14 +42,11 @@ fn check_info_file_exercises(info_file: &InfoFile) -> Result<hashbrown::HashSet<
} }
if exercise_info.hint.trim().is_empty() { if exercise_info.hint.trim().is_empty() {
bail!("The exercise `{}` has an empty hint. Please provide a hint or at least tell the user why a hint isn't needed for this exercise", exercise_info.name); 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(exercise_info.name.as_str()) { if !names.insert(name) {
bail!( bail!("The exercise name `{name}` is duplicated. Exercise names must all be unique");
"The exercise name `{}` is duplicated. Exercise names must all be unique",
exercise_info.name,
);
} }
let path = exercise_info.path(); let path = exercise_info.path();
@ -68,6 +62,10 @@ fn check_info_file_exercises(info_file: &InfoFile) -> Result<hashbrown::HashSet<
bail!("The `main` function is missing in the file `{path}`.\nCreate at least an empty `main` function to avoid language server errors"); bail!("The `main` function is missing in the file `{path}`.\nCreate at least an empty `main` function to avoid language server errors");
} }
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(); file_buf.clear();
paths.insert(PathBuf::from(path)); paths.insert(PathBuf::from(path));
@ -76,11 +74,12 @@ fn check_info_file_exercises(info_file: &InfoFile) -> Result<hashbrown::HashSet<
Ok(paths) Ok(paths)
} }
// Check the `exercises` directory for unexpected files.
fn check_unexpected_files(info_file_paths: &hashbrown::HashSet<PathBuf>) -> Result<()> {
fn unexpected_file(path: &Path) -> Error { fn unexpected_file(path: &Path) -> Error {
anyhow!("Found the file `{}`. Only `README.md` and Rust files related to an exercise in `info.toml` are allowed in the `exercises` directory", path.display()) anyhow!("Found the file `{}`. Only `README.md` and Rust files related to an exercise in `info.toml` are allowed in the `exercises` directory", path.display())
} }
fn check_exercise_dir_files(info_file_paths: &hashbrown::HashSet<PathBuf>) -> Result<()> {
for entry in read_dir("exercises").context("Failed to open the `exercises` directory")? { for entry in read_dir("exercises").context("Failed to open the `exercises` directory")? {
let entry = entry.context("Failed to read the `exercises` directory")?; let entry = entry.context("Failed to read the `exercises` directory")?;
@ -132,11 +131,12 @@ fn check_exercises(info_file: &InfoFile) -> Result<()> {
} }
let info_file_paths = check_info_file_exercises(info_file)?; let info_file_paths = check_info_file_exercises(info_file)?;
check_exercise_dir_files(&info_file_paths)?; check_unexpected_files(&info_file_paths)?;
Ok(()) Ok(())
} }
// Check that the Cargo.toml file is up-to-date.
fn check_cargo_toml( fn check_cargo_toml(
exercise_infos: &[ExerciseInfo], exercise_infos: &[ExerciseInfo],
current_cargo_toml: &str, current_cargo_toml: &str,
@ -163,6 +163,7 @@ pub fn check() -> Result<()> {
let info_file = InfoFile::parse()?; let info_file = InfoFile::parse()?;
check_exercises(&info_file)?; check_exercises(&info_file)?;
// A hack to make `cargo run -- dev check` work when developing Rustlings.
if DEBUG_PROFILE { if DEBUG_PROFILE {
check_cargo_toml( check_cargo_toml(
&info_file.exercises, &info_file.exercises,

View file

@ -8,6 +8,7 @@ use std::{
use crate::CURRENT_FORMAT_VERSION; 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<()> { fn create_rel_dir(dir_name: &str, current_dir: &str) -> Result<()> {
create_dir(dir_name) create_dir(dir_name)
.with_context(|| format!("Failed to create the directory {current_dir}/{dir_name}"))?; .with_context(|| format!("Failed to create the directory {current_dir}/{dir_name}"))?;
@ -15,6 +16,7 @@ fn create_rel_dir(dir_name: &str, current_dir: &str) -> Result<()> {
Ok(()) 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<()> fn write_rel_file<C>(file_name: &str, current_dir: &str, content: C) -> Result<()>
where where
C: AsRef<[u8]>, C: AsRef<[u8]>,
@ -27,13 +29,13 @@ where
} }
pub fn new(path: &Path, no_git: bool) -> Result<()> { pub fn new(path: &Path, no_git: bool) -> Result<()> {
let dir_name = path.to_string_lossy(); let dir_path_str = path.to_string_lossy();
create_dir(path).with_context(|| format!("Failed to create the directory {dir_name}"))?; create_dir(path).with_context(|| format!("Failed to create the directory {dir_path_str}"))?;
println!("Created the directory {dir_name}"); println!("Created the directory {dir_path_str}");
set_current_dir(path) set_current_dir(path)
.with_context(|| format!("Failed to set {dir_name} as the current directory"))?; .with_context(|| format!("Failed to set {dir_path_str} as the current directory"))?;
if !no_git if !no_git
&& !Command::new("git") && !Command::new("git")
@ -42,28 +44,28 @@ pub fn new(path: &Path, no_git: bool) -> Result<()> {
.context("Failed to run `git init`")? .context("Failed to run `git init`")?
.success() .success()
{ {
bail!("`git init` didn't run successfully. See the error message above"); bail!("`git init` didn't run successfully. See the possible error message above");
} }
write_rel_file(".gitignore", &dir_name, GITIGNORE)?; write_rel_file(".gitignore", &dir_path_str, GITIGNORE)?;
create_rel_dir("exercises", &dir_name)?; create_rel_dir("exercises", &dir_path_str)?;
create_rel_dir("solutions", &dir_name)?; create_rel_dir("solutions", &dir_path_str)?;
write_rel_file( write_rel_file(
"info.toml", "info.toml",
&dir_name, &dir_path_str,
format!("{INFO_FILE_BEFORE_FORMAT_VERSION}{CURRENT_FORMAT_VERSION}{INFO_FILE_AFTER_FORMAT_VERSION}"), format!("{INFO_FILE_BEFORE_FORMAT_VERSION}{CURRENT_FORMAT_VERSION}{INFO_FILE_AFTER_FORMAT_VERSION}"),
)?; )?;
write_rel_file("Cargo.toml", &dir_name, CARGO_TOML)?; write_rel_file("Cargo.toml", &dir_path_str, CARGO_TOML)?;
write_rel_file("README.md", &dir_name, README)?; write_rel_file("README.md", &dir_path_str, README)?;
create_rel_dir(".vscode", &dir_name)?; create_rel_dir(".vscode", &dir_path_str)?;
write_rel_file( write_rel_file(
".vscode/extensions.json", ".vscode/extensions.json",
&dir_name, &dir_path_str,
crate::init::VS_CODE_EXTENSIONS_JSON, crate::init::VS_CODE_EXTENSIONS_JSON,
)?; )?;
@ -137,8 +139,7 @@ const README: &str = "# Rustlings 🦀
Welcome to these third-party Rustlings exercises 😃 Welcome to these third-party Rustlings exercises 😃
First, First, [install Rustlings using the official instructions in the README of the Rustlings project](https://github.com/rust-lang/rustlings) ✅
[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 🚀 Then, open your terminal in this directory and run `rustlings` to get started with the exercises 🚀
"; ";

View file

@ -1,6 +1,5 @@
use std::fs;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use std::fs;
use crate::{ use crate::{
cargo_toml::updated_cargo_toml, cargo_toml::updated_cargo_toml,
@ -8,6 +7,7 @@ use crate::{
DEBUG_PROFILE, DEBUG_PROFILE,
}; };
// Update the `Cargo.toml` file.
fn update_cargo_toml( fn update_cargo_toml(
exercise_infos: &[ExerciseInfo], exercise_infos: &[ExerciseInfo],
current_cargo_toml: &str, current_cargo_toml: &str,
@ -26,6 +26,7 @@ fn update_cargo_toml(
pub fn update() -> Result<()> { pub fn update() -> Result<()> {
let info_file = InfoFile::parse()?; let info_file = InfoFile::parse()?;
// A hack to make `cargo run -- dev update` work when developing Rustlings.
if DEBUG_PROFILE { if DEBUG_PROFILE {
update_cargo_toml( update_cargo_toml(
&info_file.exercises, &info_file.exercises,