From 14f3585816ae12091956efcc45c1e4aefc2f91ce Mon Sep 17 00:00:00 2001 From: mo8it Date: Mon, 1 Apr 2024 02:11:52 +0200 Subject: Make `cargo run` work --- src/bin/gen-dev-cargo-toml.rs | 56 +++++++++++++++++++++++++++++++++++++++++++ src/exercise.rs | 14 ++++++++--- 2 files changed, 67 insertions(+), 3 deletions(-) create mode 100644 src/bin/gen-dev-cargo-toml.rs (limited to 'src') diff --git a/src/bin/gen-dev-cargo-toml.rs b/src/bin/gen-dev-cargo-toml.rs new file mode 100644 index 0000000..20167a1 --- /dev/null +++ b/src/bin/gen-dev-cargo-toml.rs @@ -0,0 +1,56 @@ +use anyhow::{bail, Context, Result}; +use serde::Deserialize; +use std::{ + fs::{self, create_dir}, + io::ErrorKind, +}; + +#[derive(Deserialize)] +struct Exercise { + name: String, + path: String, +} + +#[derive(Deserialize)] +struct InfoToml { + exercises: Vec, +} + +fn main() -> Result<()> { + let exercises = toml_edit::de::from_str::( + &fs::read_to_string("info.toml").context("Failed to read `info.toml`")?, + ) + .context("Failed to deserialize `info.toml`")? + .exercises; + + let mut buf = Vec::with_capacity(1 << 14); + + buf.extend_from_slice(b"bin = [\n"); + + for exercise in exercises { + buf.extend_from_slice(b" { name = \""); + buf.extend_from_slice(exercise.name.as_bytes()); + buf.extend_from_slice(b"\", path = \"../"); + buf.extend_from_slice(exercise.path.as_bytes()); + buf.extend_from_slice(b"\" },\n"); + } + + buf.extend_from_slice( + br#"] + +[package] +name = "rustlings" +version = "0.0.0" +edition = "2021" +publish = false +"#, + ); + + if let Err(e) = create_dir("dev") { + if e.kind() != ErrorKind::AlreadyExists { + bail!("Failed to create the `dev` directory: {e}"); + } + } + + fs::write("dev/Cargo.toml", buf).context("Failed to write `dev/Cargo.toml`") +} diff --git a/src/exercise.rs b/src/exercise.rs index e7045d6..450acf4 100644 --- a/src/exercise.rs +++ b/src/exercise.rs @@ -91,9 +91,17 @@ pub struct ContextLine { impl Exercise { fn cargo_cmd(&self, command: &str, args: &[&str]) -> Result { - Command::new("cargo") - .arg(command) - .arg("--color") + let mut cmd = Command::new("cargo"); + cmd.arg(command); + + // A hack to make `cargo run` work when developing Rustlings. + // Use `dev/Cargo.toml` when in the directory of the repository. + #[cfg(debug_assertions)] + if std::path::Path::new("tests").exists() { + cmd.arg("--manifest-path").arg("dev/Cargo.toml"); + } + + cmd.arg("--color") .arg("always") .arg("-q") .arg("--bin") -- cgit v1.2.3