feat: Quest loading

- Added config::Config::load_quests()
- Added quest::error::QuestError error type
- Updated documentation
This commit is contained in:
Alexey 2025-11-28 15:37:48 +03:00
commit a5eac1b64f
5 changed files with 130 additions and 10 deletions

View file

@ -1,8 +1,10 @@
//! Module for handling configuration
//! Configuration file that handles (de-)serializing other components
use std::path::PathBuf;
use std::{fs::{self, DirEntry},path::PathBuf};
use serde::Deserialize;
use crate::quest::{Quest,error::QuestError};
/// Struct for containing paths to other (de-)serializable things
#[derive(Deserialize)]
pub struct Config {
@ -30,10 +32,35 @@ impl Default for Config {
}
}
fn handle_quest_entry(quest_entry: DirEntry) -> Result<Quest, QuestError>{
let filetype = quest_entry.file_type();
if let Err(error) = filetype {
return Err(QuestError::IoError(error));
}
let path = quest_entry.path();
let filetype = filetype.unwrap();
if !filetype.is_file() {
return Err(QuestError::IsNotAFile(path));
}
Quest::load(path)
}
impl Config {
/// Deserialize config from TOML
/// Logs all errors and returns default config if that happens
///
/// # Examples
/// ```rust
/// use squad_quest::config::Config;
///
/// let path = "cfg/config.toml".into();
/// let config = Config::load(path);
/// ```
pub fn load(path: PathBuf) -> Self {
match std::fs::read_to_string(path) {
match fs::read_to_string(path) {
Ok(string) => {
match toml::from_str::<Config>(&string) {
Ok(conf) => {
@ -52,4 +79,51 @@ impl Config {
}
}
}
/// Load [Vec]<[Quest]> from quests folder.
/// Also logs errors and counts successfully loaded quests.
///
/// # Examples
/// ```rust
/// use squad_quest::{config::Config, quest::Quest};
///
///
/// let path = "cfg/config.toml".into();
/// let config = Config::load(path);
/// let quests = config.load_quests();
///
/// for quest in quests {
/// println!("Quest #{} {}", quest.id, quest.name);
/// }
/// ```
pub fn load_quests(&self) -> Vec<Quest> {
let mut out_vec = Vec::new();
match fs::read_dir(&self.quests_path) {
Ok(iter) => {
for entry in iter {
match entry {
Ok(quest_entry) => {
match handle_quest_entry(quest_entry) {
Ok(quest) => out_vec.push(quest),
Err(error) => {
eprintln!("Error on loading single quest: {error}");
}
}
},
Err(error) => {
eprintln!("Error on loading single quest: {error}");
}
}
}
},
Err(error) => {
eprintln!("Error on loading quests: {error}");
}
}
println!("Loaded {} quests successfully", out_vec.len());
out_vec
}
}