Compare commits

..

No commits in common. "5e7afce019325226c7515fe9cb462dda2685f7a3" and "8e178ac60dd947dc4ae30126b9281106599ddbce" have entirely different histories.

5 changed files with 40 additions and 65 deletions

View file

@ -1,8 +1,6 @@
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}``"))?;
@ -37,18 +35,13 @@ 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);
@ -75,19 +68,3 @@ 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,6 +1,7 @@
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,29 +12,32 @@ 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 {
let name = exercise_info.name.as_str(); if exercise_info.name.is_empty() {
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(name) { if let Some(c) = forbidden_char(&exercise_info.name) {
bail!("Char `{c}` in the exercise name `{name}` is not allowed"); bail!(
"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!("The exercise `{name}` has an empty dir name in `info.toml`"); bail!(
"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");
@ -42,11 +45,14 @@ 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 `{name}` has an empty hint. Please provide a hint or at least tell the user why a hint isn't needed for this exercise"); 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);
} }
if !names.insert(name) { if !names.insert(exercise_info.name.as_str()) {
bail!("The exercise name `{name}` is duplicated. Exercise names must all be unique"); bail!(
"The exercise name `{}` is duplicated. Exercise names must all be unique",
exercise_info.name,
);
} }
let path = exercise_info.path(); let path = exercise_info.path();
@ -62,10 +68,6 @@ 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));
@ -74,12 +76,11 @@ 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")?;
@ -131,12 +132,11 @@ 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_unexpected_files(&info_file_paths)?; check_exercise_dir_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,7 +163,6 @@ 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,7 +8,6 @@ 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}"))?;
@ -16,7 +15,6 @@ 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]>,
@ -29,13 +27,13 @@ where
} }
pub fn new(path: &Path, no_git: bool) -> Result<()> { pub fn new(path: &Path, no_git: bool) -> Result<()> {
let dir_path_str = path.to_string_lossy(); let dir_name = path.to_string_lossy();
create_dir(path).with_context(|| format!("Failed to create the directory {dir_path_str}"))?; create_dir(path).with_context(|| format!("Failed to create the directory {dir_name}"))?;
println!("Created the directory {dir_path_str}"); println!("Created the directory {dir_name}");
set_current_dir(path) set_current_dir(path)
.with_context(|| format!("Failed to set {dir_path_str} as the current directory"))?; .with_context(|| format!("Failed to set {dir_name} as the current directory"))?;
if !no_git if !no_git
&& !Command::new("git") && !Command::new("git")
@ -44,28 +42,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 possible error message above"); bail!("`git init` didn't run successfully. See the error message above");
} }
write_rel_file(".gitignore", &dir_path_str, GITIGNORE)?; write_rel_file(".gitignore", &dir_name, GITIGNORE)?;
create_rel_dir("exercises", &dir_path_str)?; create_rel_dir("exercises", &dir_name)?;
create_rel_dir("solutions", &dir_path_str)?; create_rel_dir("solutions", &dir_name)?;
write_rel_file( write_rel_file(
"info.toml", "info.toml",
&dir_path_str, &dir_name,
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_path_str, CARGO_TOML)?; write_rel_file("Cargo.toml", &dir_name, CARGO_TOML)?;
write_rel_file("README.md", &dir_path_str, README)?; write_rel_file("README.md", &dir_name, README)?;
create_rel_dir(".vscode", &dir_path_str)?; create_rel_dir(".vscode", &dir_name)?;
write_rel_file( write_rel_file(
".vscode/extensions.json", ".vscode/extensions.json",
&dir_path_str, &dir_name,
crate::init::VS_CODE_EXTENSIONS_JSON, crate::init::VS_CODE_EXTENSIONS_JSON,
)?; )?;
@ -139,7 +137,8 @@ const README: &str = "# Rustlings 🦀
Welcome to these third-party Rustlings exercises 😃 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) ✅ 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 🚀 Then, open your terminal in this directory and run `rustlings` to get started with the exercises 🚀
"; ";

View file

@ -1,13 +1,13 @@
use anyhow::{Context, Result};
use std::fs; use std::fs;
use anyhow::{Context, Result};
use crate::{ use crate::{
cargo_toml::updated_cargo_toml, cargo_toml::updated_cargo_toml,
info_file::{ExerciseInfo, InfoFile}, info_file::{ExerciseInfo, InfoFile},
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,7 +26,6 @@ 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,