Adds error handling and dates

This commit is contained in:
Dandaedre 2024-10-30 17:50:15 +01:00
parent 7c6fee6914
commit 1513f25c76
8 changed files with 170 additions and 0 deletions

4
.gitignore vendored
View File

@ -23,3 +23,7 @@ Cargo.lock
# The discord token
.token
# The coverage report
tarpaulin-report.html

View File

@ -7,7 +7,12 @@ edition = "2021"
poise = "0.6.1"
poise_macros = "0.6.1"
tokio = { version = "1.41.0", features = ["rt-multi-thread"] }
chrono = { version = "0.4.38", features = ["serde"] }
human_ids = "0.1.1"
once_cell = { version = "1.20.2", features = ["std"] }
serde = { version = "1.0.214", features = ["alloc", "derive"] }
thiserror = "1.0.65"
tracing = { version = "0.1.40", features = ["async-await", "std"] }
uuid = { version = "1.11.0", features = ["v4", "v7", "serde", "fast-rng"] }
[profile.dev]

5
TODO.md Normal file
View File

@ -0,0 +1,5 @@
# Test Driven
[ ] Config Load and persistance
[ ] Config recovery
[ ] Error testing framework

109
src/date.rs Normal file
View File

@ -0,0 +1,109 @@
//! All parsing and logic associated to finding and parsing dates used in all commands
//!
//! Features:
//! Simple parsing logic: (dayname, daynumber, day month) with implicit month / year
//! Range finding: (date) - (date)
//! Comma separated dates: (date), (date)
//! Date utilities: Finding next monday etc...
#![allow(dead_code)]
use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, Weekday};
use crate::error_handling::IdleError;
// All structures
/// A punctual day (just one date)
pub struct DateEventPunctual {}
/// An interval
pub struct DateEventInterval {}
/// A date, wether punctual or interval
pub struct DateEventDate {}
/// A series of dates or intervals
pub struct DateEvent {}
// Define parser
// Defines date routines
/// Returns the date corresponding to the implicit Weekday
///
/// Aka the next day implied by the day given
/// If no context is given, the date is the same day next week from the current day
pub(crate) fn relative_day_to_date(day: Weekday, context: Option<NaiveDate>) -> NaiveDate {
let context = context.unwrap_or(Local::now().date_naive()) + Duration::weeks(1);
let offset = context.weekday() as i64 - day as i64;
context - Duration::days(offset)
}
/// A placeholder for a partial date, as a date with no year associated
#[derive(Debug)]
pub(crate) struct PartialDate {
/// The month implied in the date
month: Option<Month>,
/// The day of the month implied in the date
day: u32,
}
/// Finds the date corresponding to the loosely defined implicit partial date
///
/// If no context is given, the date will be inferred as the next valid date from now
pub(crate) fn relative_date_to_date(
date: PartialDate,
context: Option<NaiveDate>,
) -> Result<NaiveDate, IdleError> {
let context = context.unwrap_or(Local::now().date_naive());
// Change the base date depending on the context
match match date.month {
Some(m) if m.number_from_month() >= context.month() => context
.with_month(m.number_from_month())
.ok_or(IdleError::DateError),
Some(_m) => context
.checked_add_months(Months::new(12))
.ok_or(IdleError::DateError),
None if date.day >= context.day() => Ok(context),
None => context
.checked_add_months(Months::new(1))
.ok_or(IdleError::DateError),
} {
Ok(new_base) => new_base
.with_day(date.day)
.ok_or(IdleError::DateError(date)),
Err(_) => Err(IdleError::DateError(date)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_relatave_dates() {
let date = NaiveDate::from_ymd_opt(2024, 10, 30);
let date_next_mon = NaiveDate::from_ymd_opt(2024, 11, 4);
let date_next_tue = NaiveDate::from_ymd_opt(2024, 11, 7);
let date2 = NaiveDate::from_ymd_opt(2024, 12, 30);
let date2_next_sat = NaiveDate::from_ymd_opt(2025, 1, 11);
let date3 = NaiveDate::from_ymd_opt(2025, 1, 16);
let date3_next_sat = NaiveDate::from_ymd_opt(2025, 1, 26);
assert_eq!(
relative_day_to_date(Weekday::Mon, date),
date_next_mon.unwrap()
);
assert_eq!(
relative_day_to_date(Weekday::Thu, date),
date_next_tue.unwrap()
);
assert_eq!(
relative_day_to_date(Weekday::Sat, date2),
date2_next_sat.unwrap()
);
assert_eq!(
relative_day_to_date(Weekday::Sun, date3),
date3_next_sat.unwrap()
);
}
}

25
src/error_handling.rs Normal file
View File

@ -0,0 +1,25 @@
//! All error related structures and functions
//!
//!
#![allow(dead_code)]
use thiserror::Error;
use crate::date::PartialDate;
// // Since the errors themselves are very verbose, this seemed like complete overkill
// #[allow(clippy::missing_docs_in_private_items)]
/// Global error struct for idlefox
#[derive(Error, Debug)]
pub enum IdleError {
/// Error republished when encountering an unrecoverable state in the API
#[error("An unrecoverable error occured while interfacing with the Discord API")]
DiscordAPIError,
#[error("An error happened while tring to make sense of the date {0:?}")]
DateError(PartialDate),
}
#[cfg(test)]
mod tests {
// use super::*;
}

8
src/ids.rs Normal file
View File

@ -0,0 +1,8 @@
//! Handle all Ids functionalities
//!
//! Features:
//! Generating a human readable ID for a UUID
//! Finding the UUID from an ID
//! Removing ID as needed
// use human_ids::generate;

View File

@ -6,6 +6,9 @@
#![warn(clippy::missing_docs_in_private_items)]
mod config;
mod date;
mod error_handling;
mod ids;
mod io;
mod modules;
mod persistence;
@ -146,6 +149,13 @@ pub async fn component_modal(ctx: crate::Context<'_>) -> Result<(), Error> {
#[cfg(not(tarpaulin_include))]
#[tokio::main]
async fn main() {
// use human_ids::generate;
// use std::{env, time::Instant};
// let tk = env::var("DISCORD_TOKEN");
// let id = generate(None);
// println!("Token: {:?} Id: {}", tk, id);
let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN");
let intents = serenity::GatewayIntents::non_privileged();
let framework = poise::Framework::builder()

View File

@ -7,6 +7,7 @@
//! ListCurrentEvents (struct)
//! ListFutureEvents (struct)
//!
#![allow(dead_code)]
use std::{collections::HashMap, sync::LazyLock};
@ -105,6 +106,9 @@ pub(crate) struct OngoingEvents {
}
impl OngoingEvents {
/// Create a new empty list of ongoing events, called in case of a first initialization
///
/// However a deserialisation will always be performed if possible
fn new() -> Self {
Self {
ongoing_events: EventListType::new(),