use anyhow::{Context, Error, Result, bail};
use serde::Deserialize;
use std::{fs, io::ErrorKind};
use crate::{embedded::EMBEDDED_FILES, exercise::RunnableExercise};
#[derive(Deserialize)]
pub struct ExerciseInfo {
pub name: String,
pub dir: Option<String>,
#[serde(default = "default_true")]
pub test: bool,
#[serde(default)]
pub strict_clippy: bool,
pub hint: String,
#[serde(default)]
pub skip_check_unsolved: bool,
}
#[inline(always)]
const fn default_true() -> bool {
true
}
impl ExerciseInfo {
pub fn path(&self) -> String {
let mut path = if let Some(dir) = &self.dir {
let mut path = String::with_capacity(14 + dir.len() + self.name.len());
path.push_str("exercises/");
path.push_str(dir);
path.push('/');
path
} else {
let mut path = String::with_capacity(13 + self.name.len());
path.push_str("exercises/");
path
};
path.push_str(&self.name);
path.push_str(".rs");
path
}
}
impl RunnableExercise for ExerciseInfo {
#[inline]
fn name(&self) -> &str {
&self.name
}
#[inline]
fn dir(&self) -> Option<&str> {
self.dir.as_deref()
}
#[inline]
fn strict_clippy(&self) -> bool {
self.strict_clippy
}
#[inline]
fn test(&self) -> bool {
self.test
}
}
#[derive(Deserialize)]
pub struct InfoFile {
pub format_version: u8,
pub welcome_message: Option<String>,
pub final_message: Option<String>,
pub exercises: Vec<ExerciseInfo>,
}
impl InfoFile {
pub fn parse() -> Result<Self> {
let slf = match fs::read_to_string("info.toml") {
Ok(file_content) => toml::de::from_str::<Self>(&file_content)
.context("Failed to parse the `info.toml` file")?,
Err(e) => {
if e.kind() == ErrorKind::NotFound {
return toml::de::from_str(EMBEDDED_FILES.info_file)
.context("Failed to parse the embedded `info.toml` file");
}
return Err(Error::from(e).context("Failed to read the `info.toml` file"));
}
};
if slf.exercises.is_empty() {
bail!("{NO_EXERCISES_ERR}");
}
Ok(slf)
}
}
const NO_EXERCISES_ERR: &str = "There are no exercises yet!
Add at least one exercise before testing.";