Adds more doc

This commit is contained in:
Dandaedre 2024-11-02 02:06:32 +01:00
parent 5649066bd9
commit 0c0aff7106
7 changed files with 169 additions and 51 deletions

View File

@ -9,10 +9,10 @@
# Doc Writing
* [x] Config
* [~] Date
* [ ] Error Handling
* [x] Date
* [x] Error Handling
* [ ] Ids
* [ ] IO
* [x] IO
* [ ] Modules
* [ ] Persistence
* [ ] Server

View File

@ -76,5 +76,5 @@ pub fn init_logger() -> Result<(), IdleError> {
File::create("idlefox.log").unwrap(),
),
])
.map_err(IdleError::LoggingFailed)
.map_err(IdleError::LoggerInitFailure)
}

View File

@ -6,13 +6,52 @@ use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, 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
///
/// # Arguments
///
/// * `day`: The desired weekday.
/// * `context`: An optional date to use as a reference for calculating the relative day.
/// If not provided, the current date plus one week is used.
///
/// # Returns
///
/// A [NaiveDate] representing the calculated date based on the given weekday and context.
///
/// # Example
///
/// ```rust
/// let today = Local::now().date_naive();
/// // Get the date for next Monday relative to today
/// let monday = relative_day_to_date(Weekday::Mon, Some(today));
/// assert_eq!(monday, today + chrono::Duration::weeks(1));
/// ```
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
/// The PartialDate struct represents a placeholder for a partial date, as a date with no year associated.
///
/// ### Fields
///
/// • month: The month implied in the date. This is an optional field, meaning it can be None.
/// • day: The day of the month implied in the date.
///
/// ### Example Usage
/// ```
/// // Create a partial date with only the month set
/// let partial_date = PartialDate {
/// month: Some(Month::February),
/// day: 14,
/// };
///
/// // Create a partial date with only the day set
/// let partial_date = PartialDate {
/// month: None,
/// day: 1,
/// };
/// ```
#[derive(Debug)]
pub(crate) struct PartialDate {
/// The month implied in the date
@ -21,9 +60,32 @@ pub(crate) struct PartialDate {
pub(crate) day: u32,
}
/// Finds the date corresponding to the loosely defined implicit partial date
/// The relative_date_to_date function finds the date corresponding to a loosely defined implicit partial date.
///
/// If no context is given, the date will be inferred as the next valid date from now
/// The date returned will be the next valid date after the context.
///
/// ### Arguments
///
/// • date: The partial date to convert.
/// • context: An optional context date. If no context is given, the date will be inferred as the next valid date from now.
///
/// ### Returns
///
/// A [chrono::NaiveDate] representing the date corresponding to the given partial date in the context of the provided date.
///
/// ### Example
/// ```
/// // In this context we are trying to get the dates relative to the 14th of the month
/// let context_date = NaiveDate::from_ymd(2023, 2, 14);
///
/// // Get the next 16, relative to our context
/// let date = relative_date_to_date(PartialDate {month: None, day: 16}, Some(context_date))?;
/// assert_eq!(date, NaiveDate::from_ymd(2023, 2, 16)); // The next 16th in in february
///
/// // Get the next 1st, relative to our context
/// let date = relative_date_to_date(PartialDate { month: None, day: 1 }, Some(context_date))?;
/// assert_eq!(date, NaiveDate::from_ymd(2023, 2, 16)); // The next 1st in in march, the next month
/// ```
pub(crate) fn relative_date_to_date(
date: PartialDate,
context: Option<NaiveDate>,
@ -34,19 +96,19 @@ pub(crate) fn relative_date_to_date(
match match date.month {
Some(m) if m.number_from_month() >= context.month() => context
.with_month(m.number_from_month())
.ok_or(IdleError::DateParsing),
.ok_or(IdleError::InvalidDate),
Some(_m) => context
.checked_add_months(Months::new(12))
.ok_or(IdleError::DateParsing),
.ok_or(IdleError::InvalidDate),
None if date.day >= context.day() => Ok(context),
None => context
.checked_add_months(Months::new(1))
.ok_or(IdleError::DateParsing),
.ok_or(IdleError::InvalidDate),
} {
Ok(new_base) => new_base
.with_day(date.day)
.ok_or(IdleError::DateParsing(date)),
Err(_) => Err(IdleError::DateParsing(date)),
.ok_or(IdleError::InvalidDate(date)),
Err(_) => Err(IdleError::InvalidDate(date)),
}
}

View File

@ -1,10 +1,13 @@
//! All parsing and logic associated to finding and parsing dates used in all commands
//! The `date` module provides functionality to parse dates from strings and perform operations on dates.
//!
//! It consists of two submodules:
//!
//! - `dateparse`: This submodule is responsible for parsing a string representation of a date into a vector of [DateObject] instances.
//! It utilizes in house representation of date as they are without context and therefore dont represent a real date yet.
//!
//! - `date_tools`: This submodule offers utility functions for working with dates.
//! It's main goal is do give a context for a subjective and incomplete date to transform it into a [chrono::NaiveDate] type from the chrono crate.
//!
//! 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)]
mod date_parse;
@ -22,6 +25,5 @@ pub struct DateEventDate {}
pub struct DateEvent {}
// Defines date routines
pub(crate) mod date_tools;
pub(crate) use date_tools::PartialDate;

View File

@ -1,6 +1,9 @@
//! All error related structures and functions
//!
//! This module provides a set of error types that can be used to handle various issues
//! with interacting with the Discord API or handling date-related tasks.
//!
//! The errors in this module are designed to provide detailed information about what
//! went wrong, making it easier to diagnose and fix problems.
#![allow(dead_code)]
use log::SetLoggerError;
use poise::serenity_prelude;
@ -12,28 +15,48 @@ use crate::date::PartialDate;
// #[allow(clippy::missing_docs_in_private_items)]
/// Global error struct for idlefox
///
/// This enum represents various errors that can occur when interacting with most of the section of the program
#[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")]
GenericDiscordAPI,
/// Error sent when a date given by the user doesn't make sense (aka dec 32, feb 30 etc)
/// Error indicating a critical failure in the Discord API interaction
///
/// This error is raised when an unrecoverable issue occurs while interfacing with the Discord API.
/// It may be recoverable by retrying the request or seeking assistance from the API provider.
#[error("An unrecoverable error occurred during Discord API interaction")]
GenericApiFailure,
/// Error indicating an invalid date format or an invalid date (dec 32, feb 30, etc..)
///
/// This error is raised when a user-provided date string cannot be parsed into a valid [PartialDate].
#[error("An error happened while tring to make sense of the date {0:?}")]
DateParsing(PartialDate),
/// A generic error when handling discord API calls
#[error("An error occured while processing a Discord API call")]
SerenityAPI(#[from] serenity_prelude::Error),
/// A parsing error occured, unwrapping this error into something better will be necessary (helper function ?)
InvalidDate(PartialDate),
/// Generic error indicating an unexpected issue during Discord API call processing
///
/// This error is raised when an unforeseen issue occurs while handling a Discord API request.
/// It may be recoverable by re-trying the request or seeking assistance from the API provider.
#[error("An unexpected error occurred during Discord API processing: {0}")]
ApiProcessingError(#[from] serenity_prelude::Error),
/// Error indicating an invalid date string
///
/// This error is raised when a user-provided date string cannot be parsed into a valid [PartialDate].
/// Notifying the user and asking for manual correction will likely be required
#[error("An error occured while parsing the date given {0:?}")]
IncorrectDate(nom::Err<nom::error::Error<Box<str>>>),
/// An error occured while initializing the logger, this usually indicate that the folfer is read only
#[error("An error occured while tring to initiate the logging module {0:?}")]
LoggingFailed(#[from] SetLoggerError),
InvalidDateParsing(nom::Err<nom::error::Error<Box<str>>>),
/// Error indicating an issue with logging initialization
///
/// This error is raised when a critical issue occurs during logging initialization.
/// It may indicate that the file reader is read-only, and manual intervention will be required to resolve the problem.
#[error("An error occurred while initializing the logger: {0}")]
LoggerInitFailure(#[from] SetLoggerError),
}
impl From<nom::Err<nom::error::Error<&str>>> for IdleError {
fn from(err: nom::Err<nom::error::Error<&str>>) -> Self {
Self::IncorrectDate(err.map_input(|input| input.into()))
Self::InvalidDateParsing(err.map_input(|input| input.into()))
}
}

View File

@ -1,8 +1,24 @@
//! All IO related functions, include all Discord IO functions
//! Features:
//! All recv and send functions to discord
//! Helper function for advanced checks
//! Functions to handle I/O operations with Discord.
//!
//! This module contains functions for interacting with the Discord API,
//! including receiving and sending messages, reactions, and managing channels and guilds. It also includes
//! helper functions for performing advanced checks and validations on received data.
//! ### Notes:
//! - The code provided uses the Serenity and Poise frameworks to create a Discord bot that can interact with users through commands and modals.
//! - The `discord_main_loop()` function starts the bot client and registers all command handlers, while the other functions handle specific tasks related to vote creation.
//! - The `VoteCreation` struct is designed to be filled in by users through a modal form or text command arguments. It can then be used to create a new vote within the guild.
//!
//! ### Example usage:
//!
//! ```rust
//! use crate::discord;
//!
//! #[tokio::main]
//! async fn main() {
//! discord::discord_main_loop().await;
//! }
//! ```
//!
use poise::serenity_prelude as serenity;
/// User data, which is stored and accessible in all command invocations
@ -25,7 +41,9 @@ type Context<'a> = poise::Context<'a, Data, GenericError>;
// Ok(())
// }
/// The result of a vote creation
/// The result of a vote creation.
///
/// This struct is used to store and display the results of creating a new vote via a discord modal form.
#[derive(Debug, poise::Modal)]
#[allow(dead_code)] // fields only used for Debug print
#[name = "Créer un nouveau Vote"]
@ -60,14 +78,19 @@ struct VoteCreation {
// non_days: Option<String>,
}
/// Creates a Discord Modal for a user-friendly vote creation form.
///
/// This function triggers the creation of a modal that allows users to input details about an event they would like to organize.
/// The input fields are predefined and include the title, short name of the game or event, group to tag, description,
/// and hours at which the event will take place.
#[poise::command(slash_command)]
/// Creates a Discord Modal for a user-friendly vote creation form
pub async fn vote_modal(
ctx: poise::ApplicationContext<'_, Data, GenericError>,
) -> Result<(), GenericError> {
use poise::Modal as _;
let data = VoteCreation::execute(ctx).await?;
// TODO: Change with logging
println!("Got data: {:?}", data);
if let Some(unwrapped_data) = data {
let group = unwrapped_data.group.unwrap_or("".into());
@ -86,19 +109,23 @@ pub async fn vote_modal(
Ok(())
}
/// List of choices for all the roles
/// List of choices for all the roles.
///
/// This enum is used to define a set of predefined choices that users can select from when creating a new vote.
/// Each choice represents a role within the guild, and it can be referred to using the enum variant name.
#[derive(Debug, poise::ChoiceParameter)]
pub enum ListOfRoles {
// TODO: This needs to be a list of all guildRoles under Users (included)
// TODO: This needs to be fetched dynamically from the server
/// placeholder for a role
#[name = "hunters"]
Hunters,
}
/// Text command for extensive vote creation
// Since this is a discord command and not a real rust command, this many arguments is "normal"
#[allow(clippy::too_many_arguments)]
#[poise::command(prefix_command, slash_command)]
/// Text command for extensive vote creation
pub async fn vote_command(
ctx: Context<'_>,
#[description = "Titre"] title: String,

View File

@ -1,11 +1,15 @@
//! Handles all votes related logic
//! Module that handles all the logic related to votes within an application.
//!
//! Features:
//! Structs & Traits
//! Votes (struct)
//! Event (struct)
//! ListCurrentEvents (struct)
//! ListFutureEvents (struct)
//! This module provides the necessary structures and traits to manage events and their corresponding votes. It includes:
//!
//! - Structs: `Event`, `Vote`, `PendingEvents`, and `OngoingEvents`.
//! - Traits: None at this time.
//! - Enums: `EventStatus` that represents different states an event can be in.
//!
//! Note:
//! - The types `UserDataType`, `VoteValueType`, and some fields are marked as deprecated and should not be used.
//! They are placeholders for the actual data structures which need to be defined correctly.
//! - Some code is commented out, such as test cases, which are currently unused.
//!
#![allow(dead_code, deprecated)]