rustlings/src/exercise.rs

75 lines
2 KiB
Rust
Raw Normal View History

2024-04-18 06:41:17 -04:00
use anyhow::{Context, Result};
2024-04-13 20:41:19 -04:00
use crossterm::style::{style, StyledContent, Stylize};
2024-04-07 18:36:26 -04:00
use std::{
2024-04-13 19:15:43 -04:00
fmt::{self, Display, Formatter},
2024-04-17 17:37:31 -04:00
path::Path,
2024-04-18 06:41:17 -04:00
process::{Command, Output},
2024-04-07 18:36:26 -04:00
};
2024-04-23 20:52:30 -04:00
use crate::{info_file::Mode, terminal_link::TerminalFileLink, DEBUG_PROFILE};
2024-04-13 20:41:19 -04:00
pub struct Exercise {
pub dir: Option<&'static str>,
2024-04-13 19:15:43 -04:00
// Exercise's unique name
pub name: &'static str,
// Exercise's path
2024-04-13 20:41:19 -04:00
pub path: &'static str,
2024-03-31 10:55:33 -04:00
// The mode of the exercise
pub mode: Mode,
// The hint text associated with the exercise
pub hint: String,
2024-04-13 19:15:43 -04:00
pub done: bool,
}
impl Exercise {
2024-03-31 10:55:33 -04:00
fn cargo_cmd(&self, command: &str, args: &[&str]) -> Result<Output> {
2024-03-31 20:11:52 -04:00
let mut cmd = Command::new("cargo");
cmd.arg(command);
// A hack to make `cargo run` work when developing Rustlings.
2024-04-21 13:26:19 -04:00
if DEBUG_PROFILE && Path::new("tests").exists() {
2024-03-31 20:11:52 -04:00
cmd.arg("--manifest-path").arg("dev/Cargo.toml");
}
cmd.arg("--color")
2024-03-31 10:55:33 -04:00
.arg("always")
.arg("-q")
.arg("--bin")
2024-04-13 19:15:43 -04:00
.arg(self.name)
2024-03-31 10:55:33 -04:00
.args(args)
.output()
2024-03-31 10:55:33 -04:00
.context("Failed to run Cargo")
}
2024-03-31 10:55:33 -04:00
pub fn run(&self) -> Result<Output> {
match self.mode {
2024-04-13 19:15:43 -04:00
Mode::Run => self.cargo_cmd("run", &[]),
2024-04-16 15:46:07 -04:00
Mode::Test => self.cargo_cmd(
"test",
&[
"--",
"--color",
"always",
"--nocapture",
"--format",
"pretty",
],
),
2024-03-31 10:55:33 -04:00
Mode::Clippy => self.cargo_cmd(
"clippy",
&["--", "-D", "warnings", "-D", "clippy::float_cmp"],
),
}
}
2024-04-13 20:41:19 -04:00
pub fn terminal_link(&self) -> StyledContent<TerminalFileLink<'_>> {
2024-04-23 20:52:30 -04:00
style(TerminalFileLink(self.path)).underlined().blue()
2024-04-13 20:41:19 -04:00
}
}
impl Display for Exercise {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2024-04-13 20:41:19 -04:00
self.path.fmt(f)
}
}