Compare commits
No commits in common. "master" and "0.3.0" have entirely different histories.
14 changed files with 499 additions and 754 deletions
4
Cargo.lock
generated
4
Cargo.lock
generated
|
|
@ -332,7 +332,7 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
|||
|
||||
[[package]]
|
||||
name = "squad-quest"
|
||||
version = "0.5.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"toml",
|
||||
|
|
@ -340,7 +340,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "squad-quest-cli"
|
||||
version = "0.5.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"clap",
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
members = ["cli"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.5.1"
|
||||
version = "0.3.0"
|
||||
edition = "2024"
|
||||
repository = "https://2ndbeam.ru/git/2ndbeam/squad-quest"
|
||||
license = "MIT"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,10 @@
|
|||
quests_path = "quests"
|
||||
accounts_path = "accounts"
|
||||
map = "map.toml"
|
||||
verbose = true
|
||||
# Default config
|
||||
|
||||
# Path to quests folder relative to config
|
||||
quests_path = "./quests"
|
||||
|
||||
# Path to accounts folder relative to config
|
||||
accounts_path = "./accounts"
|
||||
|
||||
# Path to map .toml file relative to config
|
||||
map = "./map.toml"
|
||||
|
|
|
|||
|
|
@ -9,5 +9,5 @@ license.workspace = true
|
|||
chrono = "0.4.42"
|
||||
clap = { version = "4.5.53", features = ["derive"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
squad-quest = { version = "0.5.0", path = ".." }
|
||||
squad-quest = { version = "0.3.0", path = ".." }
|
||||
toml = "0.9.8"
|
||||
|
|
|
|||
|
|
@ -1,66 +0,0 @@
|
|||
use clap::{Args,Subcommand,ValueEnum};
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum AccountCommands {
|
||||
/// List accounts
|
||||
List,
|
||||
/// Create empty account
|
||||
Create(AccountCreateArgs),
|
||||
/// Update balance value
|
||||
Balance(AccountBalanceArgs),
|
||||
/// Approve account answer for quest
|
||||
Complete(AccountCompleteArgs),
|
||||
/// Delete account
|
||||
Delete(AccountDeleteArgs),
|
||||
/// Unlock room for account if it has enough balance
|
||||
Unlock(AccountUnlockArgs),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct AccountCreateArgs {
|
||||
/// Account will be created with this id
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum AccountBalanceActions {
|
||||
Set,
|
||||
Add,
|
||||
Remove,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct AccountBalanceArgs {
|
||||
/// Account id
|
||||
pub id: String,
|
||||
/// What to do with the balance
|
||||
#[arg(value_enum)]
|
||||
pub action: AccountBalanceActions,
|
||||
/// Amount of doing
|
||||
pub value: u32,
|
||||
/// If action is remove, set balance to 0 if the result is negative instead of returning error
|
||||
#[arg(short,long)]
|
||||
pub negative_ok: bool,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct AccountCompleteArgs {
|
||||
/// Id of the account
|
||||
pub account: String,
|
||||
/// Id of the quest
|
||||
pub quest: u16,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct AccountDeleteArgs {
|
||||
/// Id of the account to delete
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct AccountUnlockArgs {
|
||||
/// Id of the account
|
||||
pub account: String,
|
||||
/// Id of the room to unlock
|
||||
pub room: u16,
|
||||
}
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
use clap::{Args,Subcommand};
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum MapCommands {
|
||||
/// List all rooms with connections
|
||||
List,
|
||||
/// Add new room to map
|
||||
Add(MapAddArgs),
|
||||
/// Connect two rooms
|
||||
Connect(MapConnectArgs),
|
||||
/// Disconnect two rooms if they're connected
|
||||
Disconnect(MapConnectArgs),
|
||||
/// Remove all connections with the room
|
||||
Delete(MapDeleteArgs),
|
||||
/// Update room data
|
||||
Update(MapUpdateArgs),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct MapAddArgs {
|
||||
/// Name of the room
|
||||
pub name: String,
|
||||
/// Price of the room
|
||||
pub value: u32,
|
||||
/// Optional description for the room
|
||||
#[arg(long,short)]
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct MapConnectArgs {
|
||||
/// First room ID
|
||||
pub first: u16,
|
||||
/// Second room ID
|
||||
pub second: u16,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct MapDeleteArgs {
|
||||
/// ID of the room to delete
|
||||
pub id: u16,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct MapUpdateArgs {
|
||||
/// ID of the room to update
|
||||
pub id: u16,
|
||||
/// Room name
|
||||
#[arg(short,long)]
|
||||
pub name: Option<String>,
|
||||
/// Room description
|
||||
#[arg(short,long)]
|
||||
pub description: Option<String>,
|
||||
/// Room price
|
||||
#[arg(short,long)]
|
||||
pub value: Option<u32>,
|
||||
}
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use clap::{Args,Parser,Subcommand};
|
||||
|
||||
pub mod account;
|
||||
pub mod map;
|
||||
pub mod quest;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version, about, long_about = None)]
|
||||
#[command(propagate_version = true)]
|
||||
pub struct Cli {
|
||||
/// Path to config
|
||||
#[arg(short, long)]
|
||||
pub config: PathBuf,
|
||||
/// Object to make operation on
|
||||
#[command(subcommand)]
|
||||
pub command: Objects,
|
||||
/// Suppress most output
|
||||
#[arg(short, long)]
|
||||
pub quiet: bool,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum Objects {
|
||||
/// Initialize new SquadQuest in current working directory
|
||||
Init(InitArgs),
|
||||
/// Operations on the quests
|
||||
#[command(subcommand)]
|
||||
Quest(quest::QuestCommands),
|
||||
/// Operations on the accounts
|
||||
#[command(subcommand)]
|
||||
Account(account::AccountCommands),
|
||||
/// Operations on the map rooms
|
||||
#[command(subcommand)]
|
||||
Map(map::MapCommands),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct InitArgs {
|
||||
#[arg(long,short)]
|
||||
pub path: Option<PathBuf>,
|
||||
}
|
||||
|
|
@ -1,131 +0,0 @@
|
|||
use squad_quest::quest::QuestDifficulty as LibQuestDifficulty;
|
||||
use toml::value::Date;
|
||||
use serde::Deserialize;
|
||||
use clap::{Args,Subcommand,ValueEnum};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DateWrapper {
|
||||
date: Date,
|
||||
}
|
||||
|
||||
fn parse_date(arg: &str) -> Result<Date,toml::de::Error> {
|
||||
let toml_str = format!("date = {arg}");
|
||||
let wrapper: DateWrapper = toml::from_str(&toml_str)?;
|
||||
Ok(wrapper.date)
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
|
||||
pub enum QuestDifficulty {
|
||||
/// Easy quest
|
||||
Easy,
|
||||
/// Normal quest
|
||||
Normal,
|
||||
/// Hard quest
|
||||
Hard,
|
||||
/// Special case of hard quests.
|
||||
Secret,
|
||||
}
|
||||
|
||||
impl From<QuestDifficulty> for LibQuestDifficulty {
|
||||
fn from(value: QuestDifficulty) -> Self {
|
||||
match value {
|
||||
QuestDifficulty::Easy => LibQuestDifficulty::Easy,
|
||||
QuestDifficulty::Normal => LibQuestDifficulty::Normal,
|
||||
QuestDifficulty::Hard => LibQuestDifficulty::Hard,
|
||||
QuestDifficulty::Secret => LibQuestDifficulty::Secret,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum QuestCommands {
|
||||
/// List available quests
|
||||
List(QuestListArgs),
|
||||
/// Create new quest and automatically assign it id
|
||||
Create(QuestCreateArgs),
|
||||
/// Update existing quest
|
||||
Update(QuestUpdateArgs),
|
||||
/// Delete quest
|
||||
Delete(QuestDeleteArgs),
|
||||
/// Make certain quests public
|
||||
Daily,
|
||||
/// Publish quest with specified id
|
||||
Publish(QuestPublishArgs),
|
||||
}
|
||||
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct QuestListArgs {
|
||||
/// Only list id and name of the quest
|
||||
#[arg(short, long)]
|
||||
pub short: bool,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct QuestCreateArgs {
|
||||
/// Difficulty of the quest
|
||||
#[arg(value_enum)]
|
||||
pub difficulty: QuestDifficulty,
|
||||
/// Reward for the quest
|
||||
pub reward: u32,
|
||||
/// Name of the quest
|
||||
pub name: String,
|
||||
/// Visible description of the quest
|
||||
pub description: String,
|
||||
/// Answer for the quest for admins
|
||||
pub answer: String,
|
||||
/// Create quest and make it public immediately
|
||||
#[arg(short,long)]
|
||||
pub public: bool,
|
||||
/// Make quest available on date (format = YYYY-MM-DD, ex. 2025-12-24)
|
||||
#[arg(short,long,value_parser = parse_date)]
|
||||
pub available: Option<Date>,
|
||||
/// Quest expiration date (format = YYYY-MM-DD, ex. 2025-12-24)
|
||||
#[arg(short,long,value_parser = parse_date)]
|
||||
pub deadline: Option<Date>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct QuestUpdateArgs {
|
||||
/// Id of the quest to update
|
||||
pub id: u16,
|
||||
/// Difficulty of the quest
|
||||
#[arg(value_enum,long)]
|
||||
pub difficulty: Option<QuestDifficulty>,
|
||||
/// Reward for the quest
|
||||
#[arg(long)]
|
||||
pub reward: Option<u32>,
|
||||
/// Name of the quest
|
||||
#[arg(long)]
|
||||
pub name: Option<String>,
|
||||
/// Visible description of the quest
|
||||
#[arg(long)]
|
||||
pub description: Option<String>,
|
||||
/// Answer for the quest for admins
|
||||
#[arg(long)]
|
||||
pub answer: Option<String>,
|
||||
/// Create quest and make it public immediately
|
||||
#[arg(long)]
|
||||
pub public: Option<bool>,
|
||||
/// Make quest available on date (format = YYYY-MM-DD, ex. 2025-12-24)
|
||||
#[arg(long,value_parser = parse_date)]
|
||||
pub available: Option<Date>,
|
||||
/// Quest expiration date (format = YYYY-MM-DD, ex. 2025-12-24)
|
||||
#[arg(long,value_parser = parse_date)]
|
||||
pub deadline: Option<Date>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct QuestDeleteArgs {
|
||||
/// Id of the quest to delete
|
||||
pub id: u16,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct QuestPublishArgs {
|
||||
/// Id of the quest to publish
|
||||
pub id: u16,
|
||||
/// Make it non-public instead
|
||||
#[arg(long,short)]
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
|
@ -1 +0,0 @@
|
|||
pub mod cli;
|
||||
663
cli/src/main.rs
663
cli/src/main.rs
|
|
@ -1,11 +1,272 @@
|
|||
use std::{fs::DirBuilder, path::{Path, PathBuf}};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use clap::Parser;
|
||||
use squad_quest_cli::cli::{Cli,Objects,account::*,map::*,quest::*};
|
||||
use squad_quest::{SquadObject, account::Account, config::Config, error::Error, map::{Map, Room}, quest::Quest};
|
||||
use clap::{Parser,Subcommand,Args,ValueEnum};
|
||||
use serde::Deserialize;
|
||||
use squad_quest::{SquadObject, account::Account, config::Config, error::Error, map::{Map, Room}, quest::{Quest,QuestDifficulty as LibQuestDifficulty}};
|
||||
use toml::value::Date;
|
||||
use chrono::{Datelike, NaiveDate, Utc};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DateWrapper {
|
||||
date: Date,
|
||||
}
|
||||
|
||||
fn parse_date(arg: &str) -> Result<Date,toml::de::Error> {
|
||||
let toml_str = format!("date = {arg}");
|
||||
let wrapper: DateWrapper = toml::from_str(&toml_str)?;
|
||||
Ok(wrapper.date)
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version, about, long_about = None)]
|
||||
#[command(propagate_version = true)]
|
||||
struct Cli {
|
||||
/// Path to config
|
||||
#[arg(short, long)]
|
||||
config: PathBuf,
|
||||
/// Object to make operation on
|
||||
#[command(subcommand)]
|
||||
command: Objects,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Objects {
|
||||
/// Operations on the quests
|
||||
#[command(subcommand)]
|
||||
Quest(QuestCommands),
|
||||
/// Operations on the accounts
|
||||
#[command(subcommand)]
|
||||
Account(AccountCommands),
|
||||
/// Operations on the map rooms
|
||||
#[command(subcommand)]
|
||||
Map(MapCommands),
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
|
||||
enum QuestDifficulty {
|
||||
/// Easy quest
|
||||
Easy,
|
||||
/// Normal quest
|
||||
Normal,
|
||||
/// Hard quest
|
||||
Hard,
|
||||
/// Special case of hard quests.
|
||||
Secret,
|
||||
}
|
||||
|
||||
impl From<QuestDifficulty> for LibQuestDifficulty {
|
||||
fn from(value: QuestDifficulty) -> Self {
|
||||
match value {
|
||||
QuestDifficulty::Easy => LibQuestDifficulty::Easy,
|
||||
QuestDifficulty::Normal => LibQuestDifficulty::Normal,
|
||||
QuestDifficulty::Hard => LibQuestDifficulty::Hard,
|
||||
QuestDifficulty::Secret => LibQuestDifficulty::Secret,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum QuestCommands {
|
||||
/// List available quests
|
||||
List(QuestListArgs),
|
||||
/// Create new quest and automatically assign it id
|
||||
Create(QuestCreateArgs),
|
||||
/// Update existing quest
|
||||
Update(QuestUpdateArgs),
|
||||
/// Delete quest
|
||||
Delete(QuestDeleteArgs),
|
||||
/// Make certain quests public
|
||||
Daily,
|
||||
/// Publish quest with specified id
|
||||
Publish(QuestPublishArgs),
|
||||
}
|
||||
|
||||
|
||||
#[derive(Args)]
|
||||
struct QuestListArgs {
|
||||
/// Only list id and name of the quest
|
||||
#[arg(short, long)]
|
||||
short: bool,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct QuestCreateArgs { /// Difficulty of the quest #[arg(value_enum)]
|
||||
difficulty: QuestDifficulty,
|
||||
/// Reward for the quest
|
||||
reward: u32,
|
||||
/// Name of the quest
|
||||
name: String,
|
||||
/// Visible description of the quest
|
||||
description: String,
|
||||
/// Answer for the quest for admins
|
||||
answer: String,
|
||||
/// Create quest and make it public immediately
|
||||
#[arg(short,long)]
|
||||
public: bool,
|
||||
/// Make quest available on date (format = YYYY-MM-DD, ex. 2025-12-24)
|
||||
#[arg(short,long,value_parser = parse_date)]
|
||||
available: Option<Date>,
|
||||
/// Quest expiration date (format = YYYY-MM-DD, ex. 2025-12-24)
|
||||
#[arg(short,long,value_parser = parse_date)]
|
||||
deadline: Option<Date>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct QuestUpdateArgs {
|
||||
/// Id of the quest to update
|
||||
id: u16,
|
||||
/// Difficulty of the quest
|
||||
#[arg(value_enum,long)]
|
||||
difficulty: Option<QuestDifficulty>,
|
||||
/// Reward for the quest
|
||||
#[arg(long)]
|
||||
reward: Option<u32>,
|
||||
/// Name of the quest
|
||||
#[arg(long)]
|
||||
name: Option<String>,
|
||||
/// Visible description of the quest
|
||||
#[arg(long)]
|
||||
description: Option<String>,
|
||||
/// Answer for the quest for admins
|
||||
#[arg(long)]
|
||||
answer: Option<String>,
|
||||
/// Create quest and make it public immediately
|
||||
#[arg(long)]
|
||||
public: Option<bool>,
|
||||
/// Make quest available on date (format = YYYY-MM-DD, ex. 2025-12-24)
|
||||
#[arg(long,value_parser = parse_date)]
|
||||
available: Option<Date>,
|
||||
/// Quest expiration date (format = YYYY-MM-DD, ex. 2025-12-24)
|
||||
#[arg(long,value_parser = parse_date)]
|
||||
deadline: Option<Date>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct QuestDeleteArgs {
|
||||
/// Id of the quest to delete
|
||||
id: u16,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct QuestPublishArgs {
|
||||
/// Id of the quest to publish
|
||||
id: u16,
|
||||
/// Make it non-public instead
|
||||
#[arg(long,short)]
|
||||
reverse: bool,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum AccountCommands {
|
||||
/// List accounts
|
||||
List,
|
||||
/// Create empty account
|
||||
Create(AccountCreateArgs),
|
||||
/// Update balance value
|
||||
Balance(AccountBalanceArgs),
|
||||
/// Approve account answer for quest
|
||||
Complete(AccountCompleteArgs),
|
||||
/// Delete account
|
||||
Delete(AccountDeleteArgs),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct AccountCreateArgs {
|
||||
/// Account will be created with this id
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
enum AccountBalanceActions {
|
||||
Set,
|
||||
Add,
|
||||
Remove,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct AccountBalanceArgs {
|
||||
/// Account id
|
||||
id: String,
|
||||
/// What to do with the balance
|
||||
#[arg(value_enum)]
|
||||
action: AccountBalanceActions,
|
||||
/// Amount of doing
|
||||
value: u32,
|
||||
/// If action is remove, set balance to 0 if the result is negative instead of returning error
|
||||
#[arg(short,long)]
|
||||
negative_ok: bool,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct AccountCompleteArgs {
|
||||
/// Id of the account
|
||||
account: String,
|
||||
/// Id of the quest
|
||||
quest: u16,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct AccountDeleteArgs {
|
||||
/// Id of the account to delete
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum MapCommands {
|
||||
/// List all rooms with connections
|
||||
List,
|
||||
/// Add new room to map
|
||||
Add(MapAddArgs),
|
||||
/// Connect two rooms
|
||||
Connect(MapConnectArgs),
|
||||
/// Disconnect two rooms if they're connected
|
||||
Disconnect(MapConnectArgs),
|
||||
/// Remove all connections with the room
|
||||
Delete(MapDeleteArgs),
|
||||
/// Update room data
|
||||
Update(MapUpdateArgs),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct MapAddArgs {
|
||||
/// Name of the room
|
||||
name: String,
|
||||
/// Price of the room
|
||||
value: u32,
|
||||
/// Optional description for the room
|
||||
#[arg(long,short)]
|
||||
description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct MapConnectArgs {
|
||||
/// First room ID
|
||||
first: u16,
|
||||
/// Second room ID
|
||||
second: u16,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct MapDeleteArgs {
|
||||
/// ID of the room to delete
|
||||
id: u16,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
struct MapUpdateArgs {
|
||||
/// ID of the room to update
|
||||
id: u16,
|
||||
/// Room name
|
||||
#[arg(short,long)]
|
||||
name: Option<String>,
|
||||
/// Room description
|
||||
#[arg(short,long)]
|
||||
description: Option<String>,
|
||||
/// Room price
|
||||
#[arg(short,long)]
|
||||
value: Option<u32>,
|
||||
}
|
||||
|
||||
fn print_quest_short(quest: &Quest) {
|
||||
println!("Quest #{}: {}", quest.id, quest.name);
|
||||
}
|
||||
|
|
@ -17,94 +278,16 @@ fn print_quest_long(quest: &Quest) {
|
|||
println!("Answer:\n{}", quest.answer);
|
||||
}
|
||||
|
||||
fn do_and_log(result: Result<(),Error>, log: bool, ok_text: String) {
|
||||
match result {
|
||||
Ok(_) if log => println!("{ok_text}"),
|
||||
Err(error) if log => eprintln!("Error: {error}"),
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
|
||||
fn load_config_silent(quiet: bool, path: PathBuf) -> Config {
|
||||
match quiet {
|
||||
false => Config::load(path.clone()),
|
||||
true => {
|
||||
match Config::try_load(path.clone()) {
|
||||
Ok(mut config) => {
|
||||
config.verbose = false;
|
||||
config
|
||||
},
|
||||
Err(_) => {
|
||||
let path = path.clone().parent().unwrap_or(&Path::new(".")).to_owned();
|
||||
Config {
|
||||
verbose: false,
|
||||
path,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
fn main() -> Result<(), Error> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
let config = load_config_silent(cli.quiet, cli.config.clone());
|
||||
let map_save = |map: Map, map_path: PathBuf| { map.save(map_path.parent().unwrap_or(Path::new("")).to_owned()) };
|
||||
let config = Config::load(cli.config.clone());
|
||||
|
||||
match &cli.command {
|
||||
Objects::Init(args) => {
|
||||
let path = match args.path.clone() {
|
||||
Some(path) => path,
|
||||
None => PathBuf::new(),
|
||||
};
|
||||
|
||||
match DirBuilder::new().recursive(true).create(path.clone()) {
|
||||
Ok(_) if !cli.quiet => println!("Created directory {:?}", path),
|
||||
Err(error) => {
|
||||
if !cli.quiet { eprintln!("Error: {error}"); }
|
||||
return;
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
|
||||
let config = Config {
|
||||
path: path.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
do_and_log(config.save(path.clone()), !cli.quiet, format!("Created file {:?}/config.toml", path));
|
||||
let mut config_path = path.clone();
|
||||
config_path.push("config.toml");
|
||||
let mut config = load_config_silent(true, config_path);
|
||||
config.verbose = Config::default().verbose;
|
||||
|
||||
let map = Map::default();
|
||||
let map_path = config.full_map_path();
|
||||
|
||||
do_and_log(map_save(map, map_path.clone()), !cli.quiet, format!("Created file {:?}/map.toml", map_path));
|
||||
|
||||
let quests_path = config.full_quests_path();
|
||||
let accounts_path = config.full_accounts_path();
|
||||
|
||||
for path in [quests_path, accounts_path] {
|
||||
match DirBuilder::new().recursive(true).create(path.clone()) {
|
||||
Ok(_) if !cli.quiet => println!("Created directory {:?}", path),
|
||||
Err(error) => {
|
||||
if !cli.quiet { eprintln!("Error: {error}"); }
|
||||
return;
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
},
|
||||
Objects::Quest(commands) => {
|
||||
let mut quests = config.load_quests();
|
||||
let mut path = config.full_quests_path();
|
||||
|
||||
match commands {
|
||||
QuestCommands::List(args) => {
|
||||
let quests = config.load_quests();
|
||||
for quest in quests {
|
||||
if args.short {
|
||||
print_quest_short(&quest);
|
||||
|
|
@ -114,26 +297,24 @@ fn main() {
|
|||
}
|
||||
},
|
||||
QuestCommands::Create(args) => {
|
||||
let mut quests = config.load_quests();
|
||||
quests.sort_by(|a,b| a.id.cmp(&b.id));
|
||||
let next_id = match quests.last() {
|
||||
Some(quest) => quest.id + 1u16,
|
||||
None => 0u16
|
||||
};
|
||||
|
||||
let mut check_path = path.clone();
|
||||
check_path.push(format!("{next_id}.toml"));
|
||||
match std::fs::exists(&check_path) {
|
||||
let path = config.full_quests_path();
|
||||
let mut quest_path = path.clone();
|
||||
quest_path.push(format!("{next_id}.toml"));
|
||||
match std::fs::exists(&quest_path) {
|
||||
Ok(exists) => {
|
||||
if exists {
|
||||
if !cli.quiet { eprintln!("Error: {:?} is not empty.", path); }
|
||||
return;
|
||||
panic!("Error: {:?} is not empty.", quest_path);
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
if !cli.quiet {
|
||||
eprintln!("Error: {error}");
|
||||
}
|
||||
return;
|
||||
panic!("Error while retrieving {:?}: {}.", quest_path, error);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -148,13 +329,16 @@ fn main() {
|
|||
available_on: args.available.clone(),
|
||||
deadline: args.deadline.clone()
|
||||
};
|
||||
|
||||
do_and_log(quest.save(path), !cli.quiet, format!("Created quest #{}.", quest.id));
|
||||
if let Err(error) = quest.save(path) {
|
||||
eprintln!("Error while saving quest: {error}.");
|
||||
} else {
|
||||
println!("Successfully saved quest #{}.", quest.id);
|
||||
}
|
||||
},
|
||||
QuestCommands::Update(args) => {
|
||||
let quests = config.load_quests();
|
||||
let Some(quest) = quests.iter().find(|q| q.id == args.id) else {
|
||||
if !cli.quiet { eprintln!("Error: Quest #{} not found.", args.id); }
|
||||
return;
|
||||
panic!("Error: Quest #{} not found.", args.id);
|
||||
};
|
||||
let quest = Quest {
|
||||
id: args.id,
|
||||
|
|
@ -170,31 +354,22 @@ fn main() {
|
|||
available_on: args.available.clone().or(quest.available_on.clone()),
|
||||
deadline: args.deadline.clone().or(quest.deadline.clone())
|
||||
};
|
||||
|
||||
do_and_log(quest.save(path), !cli.quiet, format!("Updated quest #{}.", quest.id));
|
||||
let path = config.full_quests_path();
|
||||
match quest.save(path) {
|
||||
Ok(_) => println!("Updated quest #{}", quest.id),
|
||||
Err(error) => eprintln!("Error while updating quest: {error}")
|
||||
}
|
||||
},
|
||||
QuestCommands::Delete(args) => {
|
||||
let mut path = config.full_quests_path();
|
||||
path.push(format!("{}.toml", args.id));
|
||||
match Quest::delete(path) {
|
||||
Ok(_) => {
|
||||
if !cli.quiet { println!("Deleted quest #{}.", args.id); }
|
||||
|
||||
let mut accounts = config.load_accounts();
|
||||
let accounts_path = config.full_accounts_path();
|
||||
for account in accounts.iter_mut() {
|
||||
if let Some(index) = account.quests_completed.iter().position(|qid| *qid == args.id) {
|
||||
account.quests_completed.remove(index);
|
||||
do_and_log(account.save(accounts_path.clone()), !cli.quiet, format!("Removed quest #{} from account \"{}\" completed quests", args.id, account.id));
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(error) if !cli.quiet => {
|
||||
eprintln!("Error: {error}");
|
||||
},
|
||||
_ => {},
|
||||
Ok(_) => println!("Successfully deleted quest #{}", args.id),
|
||||
Err(error) => eprintln!("Error deleting quest #{}: {}", args.id, error),
|
||||
}
|
||||
},
|
||||
QuestCommands::Daily => {
|
||||
let mut quests = config.load_quests();
|
||||
let today: NaiveDate = Utc::now().date_naive();
|
||||
let toml_today = Date {
|
||||
year: today.year() as u16,
|
||||
|
|
@ -202,38 +377,47 @@ fn main() {
|
|||
day: today.day() as u8
|
||||
};
|
||||
|
||||
let path = config.full_quests_path();
|
||||
|
||||
for quest in quests.iter_mut().filter(|q| !q.public && q.available_on.is_some_and(|date| date.le(&toml_today))) {
|
||||
println!("Quest #{} will be published.", quest.id);
|
||||
quest.public = true;
|
||||
do_and_log(quest.save(path.clone()), !cli.quiet, format!("Published quest #{}.", quest.id));
|
||||
if let Err(error) = quest.save(path.clone()) {
|
||||
eprintln!("Error while saving quest: {error}.");
|
||||
}
|
||||
}
|
||||
},
|
||||
QuestCommands::Publish(args) => {
|
||||
let mut quests = config.load_quests();
|
||||
let quest = quests.iter_mut().find(|q| q.id == args.id);
|
||||
|
||||
let path = config.full_quests_path();
|
||||
|
||||
match quest {
|
||||
Some(quest) => {
|
||||
let not_str = if args.reverse {" not "} else {" "};
|
||||
|
||||
if quest.public != args.reverse {
|
||||
if !cli.quiet { eprintln!("Error: quest #{} is already{}public.", quest.id, not_str); }
|
||||
return;
|
||||
panic!("Quest #{} is already{}public", quest.id, not_str);
|
||||
}
|
||||
|
||||
quest.public = !args.reverse;
|
||||
do_and_log(quest.save(path), !cli.quiet, format!("Published quest #{}.", quest.id));
|
||||
if let Err(error) = quest.save(path) {
|
||||
eprintln!("Error while saving quest: {error}.");
|
||||
};
|
||||
},
|
||||
None if !cli.quiet => eprintln!("Error: quest #{} not found.", args.id),
|
||||
_ => {},
|
||||
None => {
|
||||
eprintln!("Error: couldn't find quest with id {}.", args.id);
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
Objects::Account(commands) => {
|
||||
let mut accounts = config.load_accounts();
|
||||
let mut path = config.full_accounts_path();
|
||||
|
||||
match commands {
|
||||
AccountCommands::List => {
|
||||
let accounts = config.load_accounts();
|
||||
|
||||
for account in accounts {
|
||||
println!("\"{}\": Balance {}", account.id, account.balance);
|
||||
}
|
||||
|
|
@ -244,17 +428,31 @@ fn main() {
|
|||
..Default::default()
|
||||
};
|
||||
|
||||
let accounts = config.load_accounts();
|
||||
|
||||
if let Some(_) = accounts.iter().find(|a| a.id == account.id) {
|
||||
if !cli.quiet { eprintln!("Error: account \"{}\" exists.", account.id); }
|
||||
return;
|
||||
panic!("Error: account {} exists.", account.id);
|
||||
}
|
||||
|
||||
do_and_log(account.save(path), !cli.quiet, format!("Created account \"{}\".", account.id));
|
||||
let accounts_path = config.full_accounts_path();
|
||||
|
||||
match account.save(accounts_path) {
|
||||
Ok(_) => {
|
||||
println!("Successfully created account \"{}\"", account.id);
|
||||
},
|
||||
Err(error) => {
|
||||
eprintln!("Error while saving account: {error}");
|
||||
}
|
||||
}
|
||||
},
|
||||
AccountCommands::Balance(args) => {
|
||||
let Some(account) = accounts.iter_mut().find(|a| a.id == args.id) else {
|
||||
if !cli.quiet { eprintln!("Error: account \"{}\" not found.", args.id); }
|
||||
return;
|
||||
let mut accounts = config.load_accounts();
|
||||
|
||||
let account = match accounts.iter_mut().find(|a| a.id == args.id) {
|
||||
Some(acc) => acc,
|
||||
None => {
|
||||
panic!("Could not find account \"{}\"", args.id);
|
||||
}
|
||||
};
|
||||
|
||||
match args.action {
|
||||
|
|
@ -269,8 +467,7 @@ fn main() {
|
|||
if args.negative_ok {
|
||||
account.balance = 0u32;
|
||||
} else {
|
||||
if !cli.quiet { eprintln!("Error: account \"{}\" balance is less than {}.", account.id, args.value); }
|
||||
return;
|
||||
panic!("Error: balance ({}) is less than {}.", account.balance, args.value);
|
||||
}
|
||||
} else {
|
||||
account.balance -= args.value;
|
||||
|
|
@ -278,67 +475,69 @@ fn main() {
|
|||
}
|
||||
}
|
||||
|
||||
do_and_log(account.save(path), !cli.quiet, format!("Updated balance of account \"{}\".", account.id));
|
||||
let accounts_path = config.full_accounts_path();
|
||||
|
||||
match account.save(accounts_path) {
|
||||
Ok(_) => {
|
||||
println!("Successfully updated account \"{}\" balance.", account.id);
|
||||
},
|
||||
Err(error) => {
|
||||
eprintln!("Error while saving account: {error}");
|
||||
}
|
||||
};
|
||||
},
|
||||
AccountCommands::Complete(args) => {
|
||||
let Some(account) = accounts.iter_mut().find(|a| a.id == args.account) else {
|
||||
if !cli.quiet { eprintln!("Error: account \"{}\" not found.", args.account); }
|
||||
return;
|
||||
let mut accounts = config.load_accounts();
|
||||
|
||||
let account = match accounts.iter_mut().find(|a| a.id == args.account) {
|
||||
Some(acc) => acc,
|
||||
None => {
|
||||
panic!("Could not find account \"{}\"", args.account);
|
||||
}
|
||||
};
|
||||
|
||||
let quests = config.load_quests();
|
||||
|
||||
let quest = match quests.iter().find(|q| q.id == args.quest) {
|
||||
Some(quest) => quest,
|
||||
None => {
|
||||
if !cli.quiet { eprintln!("Error: quest #{} not found.", args.quest); }
|
||||
return;
|
||||
},
|
||||
};
|
||||
if let None = quests.iter().find(|q| q.id == args.quest) {
|
||||
panic!("Could not find quest #{}", args.quest);
|
||||
}
|
||||
|
||||
match quest.complete_for_account(account) {
|
||||
Err(error) if !cli.quiet => println!("Error: {error}"),
|
||||
Ok(_) => do_and_log(account.save(path), !cli.quiet, format!("Completed quest #{} on account \"{}\".", args.quest, account.id)),
|
||||
_ => {},
|
||||
match account.quests_completed.iter().find(|qid| **qid == args.quest) {
|
||||
Some(_) => {
|
||||
println!("Quest #{} is already completed on account \"{}\"", args.quest, args.account);
|
||||
},
|
||||
None => {
|
||||
account.quests_completed.push(args.quest);
|
||||
let accounts_path = config.full_accounts_path();
|
||||
match account.save(accounts_path) {
|
||||
Ok(_) => {
|
||||
println!("Account \"{}\" completed quest #{}.", args.account, args.quest);
|
||||
},
|
||||
Err(error) => {
|
||||
eprintln!("Error while saving account: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
AccountCommands::Delete(args) => {
|
||||
path.push(format!("{}.toml", args.id));
|
||||
do_and_log(Account::delete(path), !cli.quiet, format!("Deleted account \"{}\".", args.id))
|
||||
},
|
||||
AccountCommands::Unlock(args) => {
|
||||
let Some(account) = accounts.iter_mut().find(|a| a.id == args.account) else {
|
||||
if !cli.quiet { eprintln!("Error: account \"{}\" not found.", args.account) };
|
||||
return;
|
||||
};
|
||||
|
||||
let map = match Map::load(config.full_map_path()) {
|
||||
Ok(map) => map,
|
||||
let mut accounts_path = config.full_accounts_path();
|
||||
accounts_path.push(format!("{}.toml", args.id));
|
||||
match Account::delete(accounts_path) {
|
||||
Ok(_) => {
|
||||
println!("Successfully deleted account \"{}\".", args.id);
|
||||
},
|
||||
Err(error) => {
|
||||
if !cli.quiet { eprintln!("Error: {error}"); }
|
||||
return;
|
||||
eprintln!("Error deleting account: {error}");
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(error) = map.unlock_room_for_account(args.room, account) {
|
||||
eprintln!("Error: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
do_and_log(account.save(path), !cli.quiet, format!("Unlocked room #{} for account \"{}\"", args.room, args.account));
|
||||
},
|
||||
}
|
||||
},
|
||||
Objects::Map(commands) => {
|
||||
let map_path = config.full_map_path();
|
||||
let mut map = match Map::load(map_path.clone()) {
|
||||
Ok(map) => map,
|
||||
Err(error) => {
|
||||
if !cli.quiet { eprintln!("Error: {error}"); }
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let mut map = Map::load(map_path.clone())?;
|
||||
map.room.sort_by(|a,b| a.id.cmp(&b.id));
|
||||
match commands {
|
||||
MapCommands::List => {
|
||||
for room in map.room {
|
||||
|
|
@ -346,7 +545,6 @@ fn main() {
|
|||
}
|
||||
},
|
||||
MapCommands::Add(args) => {
|
||||
map.room.sort_by(|a,b| a.id.cmp(&b.id));
|
||||
let last_id = match map.room.last() {
|
||||
Some(r) => r.id + 1u16,
|
||||
None => 0u16
|
||||
|
|
@ -354,18 +552,24 @@ fn main() {
|
|||
let room = Room {
|
||||
id: last_id,
|
||||
name: args.name.clone(),
|
||||
value: args.value,
|
||||
description: args.description.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let r_id = room.id;
|
||||
map.room.push(room);
|
||||
do_and_log(map_save(map, map_path), !cli.quiet, format!("Created room #{r_id}."))
|
||||
match map.save(map_path.parent().unwrap_or(Path::new("")).to_owned()) {
|
||||
Ok(_) => {
|
||||
println!("Created room #{}.", r_id);
|
||||
println!("Successfully saved map.");
|
||||
},
|
||||
Err(error) => {
|
||||
eprintln!("Error while saving map: {error}");
|
||||
}
|
||||
}
|
||||
},
|
||||
MapCommands::Delete(args) => {
|
||||
let Some(room) = map.room.iter().find(|r| r.id == args.id) else {
|
||||
if !cli.quiet { eprintln!("Error: room #{} not found.", args.id); }
|
||||
return;
|
||||
panic!("Error: Room #{} not found", args.id);
|
||||
};
|
||||
|
||||
let r_id = room.id;
|
||||
|
|
@ -379,30 +583,19 @@ fn main() {
|
|||
room.children.remove(idx);
|
||||
}
|
||||
|
||||
match map_save(map, map_path) {
|
||||
match map.save(map_path.parent().unwrap_or(Path::new("")).to_owned()) {
|
||||
Ok(_) => {
|
||||
if !cli.quiet { println!("Deleted room #{r_id}."); }
|
||||
|
||||
let mut accounts = config.load_accounts();
|
||||
let accounts_path = config.full_accounts_path();
|
||||
|
||||
for account in accounts.iter_mut() {
|
||||
if let Some(index) = account.rooms_unlocked.iter().position(|rid| *rid == r_id) {
|
||||
account.rooms_unlocked.remove(index);
|
||||
do_and_log(account.save(accounts_path.clone()), !cli.quiet, format!("Removed room #{r_id} from account \"{}\" unlocked rooms.", account.id));
|
||||
}
|
||||
}
|
||||
println!("Removed room #{}.", r_id);
|
||||
println!("Successfully saved map.");
|
||||
},
|
||||
Err(error) if !cli.quiet => {
|
||||
eprintln!("Error: {error}");
|
||||
},
|
||||
_ => {},
|
||||
Err(error) => {
|
||||
eprintln!("Error while saving map: {error}");
|
||||
}
|
||||
}
|
||||
},
|
||||
MapCommands::Update(args) => {
|
||||
let Some(room) = map.room.iter_mut().find(|r| r.id == args.id) else {
|
||||
if !cli.quiet { eprintln!("Error: room #{} not found", args.id); }
|
||||
return;
|
||||
panic!("Error: Room #{} not found", args.id);
|
||||
};
|
||||
|
||||
if let Some(name) = &args.name {
|
||||
|
|
@ -417,34 +610,72 @@ fn main() {
|
|||
room.value = value;
|
||||
}
|
||||
|
||||
do_and_log(map_save(map, map_path), !cli.quiet, format!("Updated room #{}.", args.id))
|
||||
match map.save(map_path.parent().unwrap_or(Path::new("")).to_owned()) {
|
||||
Ok(_) => {
|
||||
println!("Updated room #{}.", args.id);
|
||||
println!("Successfully saved map.");
|
||||
},
|
||||
Err(error) => {
|
||||
eprintln!("Error while saving map: {error}");
|
||||
}
|
||||
}
|
||||
},
|
||||
MapCommands::Connect(args) | MapCommands::Disconnect(args) => {
|
||||
let connect = match commands {
|
||||
MapCommands::Connect(_) => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
MapCommands::Connect(args) => {
|
||||
// We iterate twice to make references first->second and second->first
|
||||
for (first, second) in [(args.first, args.second),(args.second, args.first)] {
|
||||
let Some(room) = map.room.iter_mut().find(|r| r.id == first) else {
|
||||
if !cli.quiet { eprintln!("Error: room #{} not found.", first); }
|
||||
return;
|
||||
panic!("Error: Room #{} not found", first);
|
||||
};
|
||||
|
||||
match room.children.iter().position(|id| *id == second) {
|
||||
Some(_) if connect && !cli.quiet => println!("Room #{} already has reference to #{}.", first, second),
|
||||
None if connect => room.children.push(second),
|
||||
Some(id) if !connect => {room.children.remove(id as usize);},
|
||||
None if !connect && !cli.quiet => println!("Room #{} has no reference to #{}.", first, second),
|
||||
_ => {},
|
||||
match room.children.iter().find(|id| **id == second) {
|
||||
Some(_) => {
|
||||
println!("Room #{} already has reference to #{}", first, second);
|
||||
},
|
||||
None => {
|
||||
room.children.push(second);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let connected = if connect { "Connected" } else { "Disconnected" };
|
||||
do_and_log(map_save(map, map_path), !cli.quiet, format!("{connected} rooms #{} <-> #{}.", args.first, args.second));
|
||||
match map.save(map_path.parent().unwrap_or(Path::new("")).to_owned()) {
|
||||
Ok(_) => {
|
||||
println!("Connected rooms #{} <-> #{}.", args.first, args.second);
|
||||
println!("Successfully saved map.");
|
||||
},
|
||||
Err(error) => {
|
||||
eprintln!("Error while saving map: {error}");
|
||||
}
|
||||
}
|
||||
},
|
||||
MapCommands::Disconnect(args) => {
|
||||
// We iterate twice to make references first->second and second->first
|
||||
for (first, second) in [(args.first, args.second),(args.second, args.first)] {
|
||||
let Some(room) = map.room.iter_mut().find(|r| r.id == first) else {
|
||||
panic!("Error: Room #{} not found", first);
|
||||
};
|
||||
|
||||
match room.children.iter().position(|id| *id == second) {
|
||||
Some(id) => {
|
||||
room.children.remove(id as usize);
|
||||
},
|
||||
None => {
|
||||
println!("Room #{} has no reference to #{}", first, second);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match map.save(map_path.parent().unwrap_or(Path::new("")).to_owned()) {
|
||||
Ok(_) => {
|
||||
println!("Disconnected rooms #{} </> #{}.", args.first, args.second);
|
||||
println!("Successfully saved map.");
|
||||
},
|
||||
Err(error) => {
|
||||
eprintln!("Error while saving map: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
//! Configuration file that handles (de-)serializing other components
|
||||
|
||||
use std::{fs::{self, DirEntry}, io::Write, path::{Path, PathBuf}};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{fs::{self, DirEntry},path::{Path, PathBuf}};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{SquadObject, account::Account, error::Error, quest::Quest};
|
||||
|
||||
/// Struct for containing paths to other (de-)serializable things
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Config {
|
||||
/// Path to config directory
|
||||
#[serde(skip)]
|
||||
pub path: PathBuf,
|
||||
path: PathBuf,
|
||||
|
||||
/// Path to serialized [quests][`crate::quest::Quest`] folder
|
||||
pub quests_path: PathBuf,
|
||||
|
|
@ -20,10 +20,7 @@ pub struct Config {
|
|||
pub accounts_path: PathBuf,
|
||||
|
||||
/// Path to serialized [map][`crate::map::Map`] file
|
||||
pub map: PathBuf,
|
||||
|
||||
/// If true, print to std{out/err}
|
||||
pub verbose: bool,
|
||||
pub map: PathBuf
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
|
|
@ -32,8 +29,7 @@ impl Default for Config {
|
|||
path: ".".into(),
|
||||
quests_path: "quests".into(),
|
||||
accounts_path: "accounts".into(),
|
||||
map: "map.toml".into(),
|
||||
verbose: true,
|
||||
map: "map.toml".into()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -71,12 +67,8 @@ fn handle_account_entry(account_entry: DirEntry) -> Result<Account, Error>{
|
|||
}
|
||||
|
||||
impl Config {
|
||||
/// Deserialize config from TOML.
|
||||
///
|
||||
/// This function wraps [try_load][Config::try_load].
|
||||
///
|
||||
/// Logs all errors if `config.verbose == true`.
|
||||
/// Returns default config on error.
|
||||
/// Deserialize config from TOML
|
||||
/// Logs all errors and returns default config if that happens
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust
|
||||
|
|
@ -89,98 +81,25 @@ impl Config {
|
|||
let dir = path.parent()
|
||||
.unwrap_or(Path::new("."))
|
||||
.to_owned();
|
||||
|
||||
match Self::try_load(path) {
|
||||
Ok(conf) => {
|
||||
if conf.verbose {
|
||||
println!("Successfully loaded config");
|
||||
}
|
||||
conf
|
||||
},
|
||||
Err(error) => {
|
||||
let conf = Config {
|
||||
path: dir,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if conf.verbose {
|
||||
println!("Error while loading config: {error}");
|
||||
}
|
||||
|
||||
conf
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize config into TOML.
|
||||
/// Config will be saved as `path/config.toml`
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust
|
||||
/// use squad_quest::config::Config;
|
||||
///
|
||||
/// let path = "cfg".into();
|
||||
///
|
||||
/// let config = Config::default();
|
||||
///
|
||||
/// if let Err(error) = config.save(path) {
|
||||
/// // handle error
|
||||
/// }
|
||||
/// ```
|
||||
pub fn save(&self, path: PathBuf) -> Result<(), Error> {
|
||||
let mut path = path;
|
||||
path.push("config.toml");
|
||||
|
||||
let str = match toml::to_string_pretty(&self) {
|
||||
Ok(string) => string,
|
||||
Err(error) => return Err(Error::TomlSerializeError(error)),
|
||||
};
|
||||
|
||||
let mut file = match fs::File::create(path) {
|
||||
Ok(f) => f,
|
||||
Err(error) => return Err(Error::IoError(error)),
|
||||
};
|
||||
|
||||
if let Err(error) = file.write_all(str.as_bytes()) {
|
||||
return Err(Error::IoError(error));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deserialize config from TOML
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust
|
||||
/// use squad_quest::{config::Config,error::Error};
|
||||
/// # fn main() {
|
||||
/// # let _ = wrapper();
|
||||
/// # }
|
||||
/// # fn wrapper() -> Result<(), Error> {
|
||||
/// let path = "cfg/config.toml".into();
|
||||
/// let config = Config::try_load(path)?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn try_load(path: PathBuf) -> Result<Self, Error> {
|
||||
let dir = path.parent()
|
||||
.unwrap_or(Path::new("."))
|
||||
.to_owned();
|
||||
|
||||
match fs::read_to_string(path) {
|
||||
Ok(string) => {
|
||||
match toml::from_str::<Config>(&string) {
|
||||
Ok(mut conf) => {
|
||||
println!("Successfully loaded config");
|
||||
conf.path = dir;
|
||||
Ok(conf)
|
||||
conf
|
||||
},
|
||||
Err(error) => {
|
||||
Err(Error::TomlDeserializeError(error))
|
||||
eprintln!("Error on parsing config: {error}");
|
||||
let mut cfg = Config::default();
|
||||
cfg.path = dir;
|
||||
cfg
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
Err(Error::IoError(error))
|
||||
eprintln!("Error on reading config path: {error}");
|
||||
Config::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -231,28 +150,23 @@ impl Config {
|
|||
Ok(quest_entry) => {
|
||||
match handle_quest_entry(quest_entry) {
|
||||
Ok(quest) => out_vec.push(quest),
|
||||
Err(error) if self.verbose => {
|
||||
Err(error) => {
|
||||
eprintln!("Error on loading single quest: {error}");
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(error) if self.verbose => {
|
||||
Err(error) => {
|
||||
eprintln!("Error on loading single quest: {error}");
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(error) if self.verbose => {
|
||||
Err(error) => {
|
||||
eprintln!("Error on loading quests: {error}");
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
|
||||
if self.verbose {
|
||||
println!("Loaded {} quests successfully", out_vec.len());
|
||||
}
|
||||
println!("Loaded {} quests successfully", out_vec.len());
|
||||
|
||||
out_vec
|
||||
}
|
||||
|
|
@ -303,28 +217,23 @@ impl Config {
|
|||
Ok(acc_entry) => {
|
||||
match handle_account_entry(acc_entry) {
|
||||
Ok(quest) => out_vec.push(quest),
|
||||
Err(error) if self.verbose => {
|
||||
Err(error) => {
|
||||
eprintln!("Error on loading single account: {error}");
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(error) if self.verbose => {
|
||||
Err(error) => {
|
||||
eprintln!("Error on loading single account: {error}");
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(error) if self.verbose => {
|
||||
Err(error) => {
|
||||
eprintln!("Error on loading accounts: {error}");
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
|
||||
if self.verbose {
|
||||
println!("Loaded {} accounts successfully", out_vec.len());
|
||||
}
|
||||
println!("Loaded {} accounts successfully", out_vec.len());
|
||||
|
||||
out_vec
|
||||
}
|
||||
|
|
|
|||
38
src/error.rs
38
src/error.rs
|
|
@ -26,41 +26,3 @@ impl fmt::Display for Error {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Error related to quest logic
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum QuestError {
|
||||
/// Quest (self.0) is already completed for given account (self.1)
|
||||
AlreadyCompleted(u16, String),
|
||||
}
|
||||
|
||||
impl fmt::Display for QuestError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::AlreadyCompleted(quest_id, account_id) => write!(f, "quest #{quest_id} is already completed for account \"{account_id}\""),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Error related to map logic
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum MapError {
|
||||
/// Room not found in map file
|
||||
RoomNotFound(u16),
|
||||
/// Room (self.0) is already unlocked on account (self.1)
|
||||
RoomAlreadyUnlocked(u16, String),
|
||||
/// Account (self.1) does not have much money (self.0)
|
||||
InsufficientFunds(u16, String),
|
||||
}
|
||||
|
||||
impl fmt::Display for MapError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::RoomNotFound(id) => write!(f, "could not find room #{id}"),
|
||||
Self::RoomAlreadyUnlocked(room_id, account_id) => write!(f, "room #{room_id} is already unlocked on account \"{account_id}\""),
|
||||
Self::InsufficientFunds(room_id, account_id) => write!(f, "account \"{account_id}\" does not have enough money to unlock room #{room_id}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ use std::{fs, io::Write, path::PathBuf};
|
|||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{SquadObject, account::Account, error::{Error, MapError}};
|
||||
use crate::{SquadObject, error::Error};
|
||||
|
||||
/// THE Graph. Actually, this is a Vec.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
|
|
@ -71,43 +71,7 @@ impl SquadObject for Map {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Map {
|
||||
/// Try to unlock room for account, or return [MapError]
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust
|
||||
/// use squad_quest::{account::Account,map::{Map,Room},error::MapError};
|
||||
///
|
||||
/// let map = Map {
|
||||
/// room: vec![Room { id: 0, value: 100, ..Default::default() }],
|
||||
/// };
|
||||
///
|
||||
/// let mut account = Account { balance: 100, ..Default::default() };
|
||||
///
|
||||
/// if let Err(error) = map.unlock_room_for_account(0, &mut account) {
|
||||
/// // handle error
|
||||
/// }
|
||||
/// ```
|
||||
pub fn unlock_room_for_account(&self, room_id: u16, account: &mut Account) -> Result<(), MapError> {
|
||||
let Some(room) = self.room.iter().find(|r| r.id == room_id) else {
|
||||
return Err(MapError::RoomNotFound(room_id));
|
||||
};
|
||||
|
||||
if let Some(_) = account.rooms_unlocked.iter().find(|rid| **rid == room_id) {
|
||||
return Err(MapError::RoomAlreadyUnlocked(room_id, account.id.clone()));
|
||||
}
|
||||
|
||||
if account.balance < room.value {
|
||||
return Err(MapError::InsufficientFunds(room_id, account.id.clone()));
|
||||
}
|
||||
|
||||
account.balance -= room.value;
|
||||
account.rooms_unlocked.push(room_id);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Component of the map
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
use std::{fs, io::Write, path::PathBuf};
|
||||
|
||||
use serde::{ Serialize, Deserialize };
|
||||
use crate::{SquadObject, account::Account, error::{Error, QuestError}};
|
||||
use crate::{SquadObject, error::Error};
|
||||
use toml::value::Date;
|
||||
|
||||
/// Difficulty of the quest
|
||||
|
|
@ -137,32 +137,3 @@ impl SquadObject for Quest {
|
|||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Quest {
|
||||
/// Complete quest for account and add reward to it's balance.
|
||||
/// Does nothing and returns [QuestError::AlreadyCompleted]
|
||||
/// if it is already completed.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// use squad_quest::{account::Account,quest::Quest};
|
||||
///
|
||||
/// let quest = Quest::default();
|
||||
/// let mut account = Account::default();
|
||||
///
|
||||
/// if let Err(error) = quest.complete_for_account(&mut account) {
|
||||
/// // handle error
|
||||
/// }
|
||||
/// ```
|
||||
pub fn complete_for_account(&self, account: &mut Account) -> Result<(),QuestError> {
|
||||
match account.quests_completed.iter().find(|qid| **qid == self.id) {
|
||||
Some(_) => Err(QuestError::AlreadyCompleted(self.id, account.id.clone())),
|
||||
None => {
|
||||
account.quests_completed.push(self.id);
|
||||
account.balance += self.reward;
|
||||
Ok(())
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue