rustlings/src/exercise.rs

70 lines
1.9 KiB
Rust
Raw Normal View History

2024-03-31 17:55:33 +03:00
use anyhow::{Context, Result};
2024-04-08 01:36:26 +03:00
use std::{
2024-04-14 02:15:43 +03:00
fmt::{self, Display, Formatter},
path::Path,
2024-04-08 01:36:26 +03:00
process::{Command, Output},
};
2024-04-14 02:15:43 +03:00
use crate::{
embedded::{WriteStrategy, EMBEDDED_FILES},
info_file::Mode,
};
2024-03-31 17:55:33 +03:00
pub struct Exercise {
2024-04-14 02:15:43 +03:00
// Exercise's unique name
pub name: &'static str,
// Exercise's path
pub path: &'static Path,
2024-03-31 17:55:33 +03:00
// The mode of the exercise
pub mode: Mode,
// The hint text associated with the exercise
pub hint: String,
2024-04-14 02:15:43 +03:00
pub done: bool,
}
impl Exercise {
2024-03-31 17:55:33 +03:00
fn cargo_cmd(&self, command: &str, args: &[&str]) -> Result<Output> {
2024-04-01 03:11:52 +03:00
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")
2024-03-31 17:55:33 +03:00
.arg("always")
.arg("-q")
.arg("--bin")
2024-04-14 02:15:43 +03:00
.arg(self.name)
2024-03-31 17:55:33 +03:00
.args(args)
.output()
2024-03-31 17:55:33 +03:00
.context("Failed to run Cargo")
}
2024-03-31 17:55:33 +03:00
pub fn run(&self) -> Result<Output> {
match self.mode {
2024-04-14 02:15:43 +03:00
Mode::Run => self.cargo_cmd("run", &[]),
Mode::Test => self.cargo_cmd("test", &["--", "--nocapture", "--format", "pretty"]),
2024-03-31 17:55:33 +03:00
Mode::Clippy => self.cargo_cmd(
"clippy",
&["--", "-D", "warnings", "-D", "clippy::float_cmp"],
),
}
}
2024-04-07 23:43:59 +03:00
pub fn reset(&self) -> Result<()> {
EMBEDDED_FILES
2024-04-14 02:15:43 +03:00
.write_exercise_to_disk(self.path, WriteStrategy::Overwrite)
2024-04-07 23:43:59 +03:00
.with_context(|| format!("Failed to reset the exercise {self}"))
}
}
impl Display for Exercise {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2024-04-12 20:07:17 +03:00
Display::fmt(&self.path.display(), f)
}
}