From 5649066bd9d130ce954d0792e7fcfda824f8c78c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 1 Nov 2024 18:58:42 +0100 Subject: [PATCH 1/2] Adds doc for the config and some of the date handling --- TODO.md | 15 ++++ src/config.rs | 64 +++++++++++--- src/date/date_parse.rs | 193 +++++++++++++++++++++++++++++++++++------ src/error_handling.rs | 4 + src/main.rs | 2 +- 5 files changed, 240 insertions(+), 38 deletions(-) diff --git a/TODO.md b/TODO.md index b547b5c..46ede3d 100644 --- a/TODO.md +++ b/TODO.md @@ -7,6 +7,21 @@ * [ ] Config recovery * [ ] Error testing framework +# Doc Writing +* [x] Config +* [~] Date +* [ ] Error Handling +* [ ] Ids +* [ ] IO +* [ ] Modules +* [ ] Persistence +* [ ] Server +* [ ] Votes +* [ ] Watchdog + +# Examples testing +* [ ] Date + # Tasks ## Dan * [ ] Finish testing to reach 100% coverage diff --git a/src/config.rs b/src/config.rs index 0741014..591d0e4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,27 +1,67 @@ -//! Handles all config related functions +//! # IdleFox Configuration Module //! -//! Tries to load a config from .idlefox.toml -//! and creates a default version if it fails to do so +//! This module provides a centralized configuration system for IdleFox, allowing you to load and manage your settings in an efficient and flexible manner. //! -//! Features: -//! Create, loads and saves config -//! Default config -//! Import old data from outdated configs -//! Recover from importing faulty data +//! The primary goal of this module is to provide a robust and reliable way to store and retrieve configuration data from the `.idlefox.toml` file. +//! If the file does not exist or cannot be loaded, it will automatically create a default version for you. +//! +//! ### Key Features +//! +//! * **Config Loading**: Seamlessly load your existing config from the `.idlefox.toml` file, ensuring that all settings are preserved and up-to-date. +//! * **Default Config Creation**: Automatically generate a default configuration if the specified file cannot be loaded or is missing. +//! * **Legacy Data Import**: Safely import old data from outdated configurations to minimize disruptions during upgrades. +//! * **Faulty Data Recovery**: Implement measures to recover from importing faulty data, ensuring that your IdleFox instance remains stable and functional. +//! +//! ### Usage +//! +//! To use this module effectively, you can follow these steps: +//! +//! 1. Use the `init_logger()` function from the IdleFox logging module (as shown below) to initialize the logger with your custom log level and output destination. +//! +//! Example usage: +//! +//! ```rust +//! # use idlefox::config; +//! # fn main() { +//! // Initialize the logger with a custom log level of info +//! config::init_logger().expect("Failed to initialize logger"); +//! // Log some messages at different levels (e.g., debug, warn, error) +//! let message = "This is an example message"; +//! log::warn!("{}", message); +//! log::error!("{}", message); +//! # } //! - use std::fs::File; use log::LevelFilter; use serde::{Deserialize, Serialize}; use simplelog::{ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger}; +use crate::error_handling::IdleError; + /// The global config +/// TODO: Update this doc as the config module is done #[derive(Serialize, Deserialize)] pub(crate) struct GlobalConfig {} -/// Init the logging -pub fn init_logger() { +/// Initializes a logger for logging purposes. +/// +/// This function sets up two loggers: one for terminal output (with warning level) and another for file-based logging (with info level). +/// +/// The terminal logger will display warnings, while the file logger will write all logs at or above the info level to an "idlefox.log" file in the current working directory. +/// +/// # Examples +/// +/// ``` +/// init_logger().expect("Failed to initialize logger"); +/// // Log a message at the info level. +/// log::info!("This will be written to idlefox.log"); +/// +/// // Log a warning at the warn level, which should appear on screen as well. +/// log::warn!("Warning: This will be written on file and on screen"); +/// ``` +/// +pub fn init_logger() -> Result<(), IdleError> { CombinedLogger::init(vec![ TermLogger::new( LevelFilter::Warn, @@ -36,5 +76,5 @@ pub fn init_logger() { File::create("idlefox.log").unwrap(), ), ]) - .unwrap(); + .map_err(IdleError::LoggingFailed) } diff --git a/src/date/date_parse.rs b/src/date/date_parse.rs index bb3d114..b5b98a3 100644 --- a/src/date/date_parse.rs +++ b/src/date/date_parse.rs @@ -1,11 +1,23 @@ -//! Parse a date string sequence into structs -//! +//! The module provides functions for parsing date strings into Rust structs. //! The pseudo grammar is defined as: -//! date = (day) (month) | (month) (day) | (weekday) -//! daterange = (date) - (date) -//! dateobject = (date) | (daterange) -//! datelist = (dateobject) (, (dateobject))* +//! ``` +//! date = (day) (month) | (month) (day) | (weekday) +//! daterange = (date) - (date) +//! dateobject = (date) | (daterange) +//! datelist = (dateobject) (, (dateobject))* +//! ``` +//! All strings parsed will be parsed into a [DateList], as the function [parse_str_into_date] always assume you are providing it a list of ranges. +//! Parsing a single date is outside of the scope of this module and should be implemented separately if needed. //! +//! Please note that while an invalid input will return an error, a partially valid input will yield partial results. +//! +//! ### Usage +//! ``` +//! let result = parse_str_into_date("12 dec - 23 feb, lun - mer, 12, 14"); +//! +//! // Parses into 12 dec - 23 feb +//! let partial_result = parse_str_into_date("12 dec - 23 febelunmer"); +//! ``` #![allow(dead_code)] use chrono::{Month, Weekday}; @@ -19,10 +31,27 @@ use nom::{ IResult, ParseTo, }; -/// A single relative date, which is either a day and an optionnal month or a weekday +/// The DatePoint enum represents a single relative date, which can be either a day and an optional month or a weekday. /// -/// Parsed from: (\d) (Month)? | Day -#[derive(Clone, Debug)] +/// ### Parsing +/// The date is parsed from the following formats: +/// * ``Day (Month)?`` - with ``Day`` as a day as a ``(\d)+`` and month as a two or three letter str. Specifies a day and an optional month. +/// * ``WeekDay`` - with ``WeekDay`` as a three letter str. Specifies a weekday. +/// +/// ### Data Structure +/// * Date: Represents a day specified by its position in the month, along with an optional month. +/// * day: The day of the month. +/// * month: An optional Month enum value (see [chrono::Month]). +/// * Weekday: Represents a Weekday (as in Mon, Tue, etc.). (see [chrono::Weekday]) +/// +/// ### Examples +/// ``` +/// // Manually create a date with day and month +/// let date_point1 = DatePoint::Date { day: 15, month: Some(Month::January) }; +/// // Manually create a weekday +/// let date_point3 = DatePoint::Weekday(Weekday::Monday); +/// ``` +#[derive(Debug, Clone, Copy)] #[cfg_attr(test, derive(PartialEq))] pub(crate) enum DatePoint { /// A day specified by it's position in the month, and an optionnal month @@ -36,9 +65,23 @@ pub(crate) enum DatePoint { Weekday(Weekday), } -/// A date range, signals a range between a starting point and an endpoint +/// The DateRange struct represents a date range, encompassing a starting point and an endpoint. /// -/// Parsed from : DatePoint - DatePoint +/// ### Parsing +/// The date range is parsed from the following format: +/// * ``DatePoint - DatePoint`` - with DatePoint as a [DatePoint] +/// +/// ### Data Structure +/// • start: The starting date in the range. +/// • stop: The end date in the range. +/// ``` +/// ### Examples +/// // Create a date range from two DatePoint values +/// let date_range = DateRange { +/// start: DatePoint::Date { day: 1, month: Some(Month::January) }, +/// stop: DatePoint::Date { day: 31, month: Some(Month::December) }, +/// }; +/// ``` #[derive(Clone, Debug)] #[cfg_attr(test, derive(PartialEq))] pub(crate) struct DateRange { @@ -48,9 +91,25 @@ pub(crate) struct DateRange { stop: DatePoint, } -/// Main date structure, signals either a range between two relative dates or a single date +/// The DateObject enum represents the main date structure, which can be either a date range or a single date. /// -/// Parsed from : DateRange | DatePoint +/// ### Parsing +/// The date object is parsed from the following formats: +/// * [DateRange]: Represents a range between two relative dates. +/// * [DatePoint]: Represents a single date. +/// +/// +/// ### Examples +/// ``` +/// // Create a DateObject representing a range +/// let date_object1 = DateObject::Range(DateRange { +/// start: DatePoint::Date { day: 1, month: Some(Month::January) }, +/// stop: DatePoint::Date { day: 31, month: Some(Month::December) }, +/// }); +/// +/// // Create a DateObject representing a single date +/// let date_object2 = DateObject::Single(DatePoint::Date { day: 15, month: Some(Month::February) }); +/// ``` #[derive(Clone, Debug)] #[cfg_attr(test, derive(PartialEq))] pub enum DateObject { @@ -64,14 +123,41 @@ pub enum DateObject { // inner: Vec, // } -/// Type defining a list of dates +/// The DateList type represents a list of dates, which can contain either single dates or date ranges. /// -/// This type is parsed from : DateObject (, DateObject)* +/// ### Parsing +/// The date list is parsed from the following format: +/// * ``DateObject (, DateObject)*`` - with ``DateObject`` as a [DateObject] +/// +/// ### Data Structure +/// A vector of DateObject elements. +/// +/// ### Examples +/// ``` +/// // Create a DateList with a single date and a range +/// let date_list = DateList::new([ +/// DateObject::Single(DatePoint::Date { day: 15, month: Some(Month::January) }), +/// DateObject::Range(DateRange { +/// start: DatePoint::Date { day: 1, month: Some(Month::February) }, +/// stop: DatePoint::Date { day: 28, month: Some(Month::February) }, +/// }), +/// ]); +/// ``` pub type DateList = Vec; -/// Parse a month with either french or english delimitation +/// The parse_month function parses a month from a given input string. It supports both French and English denominations. /// -/// Ignores all trailing and leading spaces +/// ### Parsing Logic +/// The function uses the [nom::branch::alt] combinator to handle both French and English month denominations. +/// Each denomination is represented by an alt combinator that matches the corresponding month value. +/// +/// ### Examples +/// ``` +/// // Parse January from "jan" +/// let result1 = parse_month("jan"); +/// // Parse February from "fr" +/// let result2 = parse_month("fr"); +/// ``` fn parse_month(input: &str) -> IResult<&str, Month> { alt(( alt(( @@ -111,7 +197,23 @@ fn parse_month(input: &str) -> IResult<&str, Month> { ))(input) } -/// Parse a weekday using either french or english day acronims +/// The parse_weekday function parses a weekday from a given input string. +/// It supports both French and English weekday abbreviations. +/// +/// ### Parsing Logic +/// The function uses the [nom::sequence::delimited] combinator to remove leading and trailing spaces from the input string. +/// Inside the delimiter, it uses the [nom::branch::alt] combinator to match any of the supported weekday abbreviations. +/// +/// ### Examples +/// ``` +/// // Parse Monday from "Mon" +/// let result1 = parse_weekday("Mon"); +/// +/// // Parse Saturday from "sam" +/// let result2 = parse_weekday("sam"); +/// ``` +/// ### Errors +/// Will return an Error if the input can't be matched to a day fn parse_weekday(input: &str) -> IResult<&str, Weekday> { delimited( space0, @@ -135,9 +237,28 @@ fn parse_weekday(input: &str) -> IResult<&str, Weekday> { )(input) } -/// Parse a single date ignoring all whitespace +/// The parse_simple_date function parses a single date from a given input string. +/// It supports different date formats: +/// * Day (Month)? +/// * (Month)? Day +/// * Day /// -/// Parse from: Day (Month)? | (Month)? Day | Day +/// ### Parsing Logic +/// The function uses the [nom::branch::alt] combinator to handle the different date formats. +/// Each format is represented by a separate [nom::combinator::map] combinator that extracts +/// the necessary date information and constructs the DatePoint object. +/// +/// ### Examples +/// ``` +/// // Parse "15 Jan" +/// let result1 = parse_simple_date("15 Jan"); +/// +/// // Parse "Jan 15" +/// let result2 = parse_simple_date("Jan 15"); +/// +/// // Parse "15" +/// let result3 = parse_simple_date("15"); +/// ``` fn parse_simple_date(input: &str) -> IResult<&str, DatePoint> { alt(( map( @@ -164,10 +285,23 @@ fn parse_simple_date(input: &str) -> IResult<&str, DatePoint> { ))(input) } -/// Parse a single date, either a range or a single day +/// The parse_date_object function parses a single date object from a given input string. +/// It supports two formats: +/// * Date - Date +/// * Date +/// ### Parsing Logic /// -/// Parse from: Date - Date | Date -fn parse_date_object(input: &str) -> IResult<&str, DateObject> { +/// The function uses the [nom::branch::alt] combinator to handle the two date formats. +/// Each format is represented by a separate [nom::combinator::map] combinator that parses the date range or single date object. +/// ### Examples +/// ``` +/// // Parse "20dec -31jan" +/// let result1 = parse_date_object("20dec -31jan"); +/// +/// // Parse "Lun" +/// let result2 = parse_date_object("Lun"); +/// ``` +pub fn parse_date_object(input: &str) -> IResult<&str, DateObject> { alt(( map( separated_pair(parse_simple_date, char('-'), parse_simple_date), @@ -177,9 +311,18 @@ fn parse_date_object(input: &str) -> IResult<&str, DateObject> { ))(input) } -/// Parse a complete list of days separated by ',' +/// The parse_str_into_date function parses a list of date objects from a given input string. +/// Each date object is separated by a comma. /// -/// Parses from: DateObject (, DateObject)* +/// ### Parsing Logic +/// +/// The function uses the [nom::multi::separated_list1] combinator to parse a list of date objects separated by commas. +/// Each date object is then parsed again using the [parse_date_object] function. +/// # Examples +/// ``` +/// // Parse "12 dec - 23 feb, lun - mer, 12, 14" +/// let result = parse_str_into_date("12 dec - 23 feb, lun - mer, 12, 14"); +/// ``` pub fn parse_str_into_date(input: &str) -> IResult<&str, Vec> { separated_list1(char(','), parse_date_object)(input) } diff --git a/src/error_handling.rs b/src/error_handling.rs index bae4624..09346f5 100644 --- a/src/error_handling.rs +++ b/src/error_handling.rs @@ -2,6 +2,7 @@ //! //! #![allow(dead_code)] +use log::SetLoggerError; use poise::serenity_prelude; use thiserror::Error; @@ -25,6 +26,9 @@ pub enum IdleError { /// A parsing error occured, unwrapping this error into something better will be necessary (helper function ?) #[error("An error occured while parsing the date given {0:?}")] IncorrectDate(nom::Err>>), + /// 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), } impl From>> for IdleError { diff --git a/src/main.rs b/src/main.rs index c6884c0..fbae895 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,7 +22,7 @@ mod watchdog; #[cfg(not(tarpaulin_include))] #[tokio::main] async fn main() { - init_logger(); + init_logger().unwrap(); discord_main_loop().await; // use date_parse::test_parsing; -- 2.45.1 From 0c0aff7106498574f469bc9c5b22aad6ba8edf77 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 2 Nov 2024 02:06:32 +0100 Subject: [PATCH 2/2] Adds more doc --- TODO.md | 6 ++-- src/config.rs | 2 +- src/date/date_tools.rs | 78 +++++++++++++++++++++++++++++++++++++----- src/date/mod.rs | 16 +++++---- src/error_handling.rs | 55 ++++++++++++++++++++--------- src/io.rs | 45 +++++++++++++++++++----- src/votes.rs | 18 ++++++---- 7 files changed, 169 insertions(+), 51 deletions(-) diff --git a/TODO.md b/TODO.md index 46ede3d..33b864e 100644 --- a/TODO.md +++ b/TODO.md @@ -9,10 +9,10 @@ # Doc Writing * [x] Config -* [~] Date -* [ ] Error Handling +* [x] Date +* [x] Error Handling * [ ] Ids -* [ ] IO +* [x] IO * [ ] Modules * [ ] Persistence * [ ] Server diff --git a/src/config.rs b/src/config.rs index 591d0e4..818c5b5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -76,5 +76,5 @@ pub fn init_logger() -> Result<(), IdleError> { File::create("idlefox.log").unwrap(), ), ]) - .map_err(IdleError::LoggingFailed) + .map_err(IdleError::LoggerInitFailure) } diff --git a/src/date/date_tools.rs b/src/date/date_tools.rs index 1983560..487d932 100644 --- a/src/date/date_tools.rs +++ b/src/date/date_tools.rs @@ -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 { 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, @@ -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)), } } diff --git a/src/date/mod.rs b/src/date/mod.rs index 7e7e8f2..1c7ec9d 100644 --- a/src/date/mod.rs +++ b/src/date/mod.rs @@ -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; diff --git a/src/error_handling.rs b/src/error_handling.rs index 09346f5..2fe4025 100644 --- a/src/error_handling.rs +++ b/src/error_handling.rs @@ -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>>), - /// 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>>), + + /// 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>> for IdleError { fn from(err: nom::Err>) -> Self { - Self::IncorrectDate(err.map_input(|input| input.into())) + Self::InvalidDateParsing(err.map_input(|input| input.into())) } } diff --git a/src/io.rs b/src/io.rs index 0282e63..2a8cf88 100644 --- a/src/io.rs +++ b/src/io.rs @@ -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, } +/// 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, diff --git a/src/votes.rs b/src/votes.rs index 99ab501..90e219e 100644 --- a/src/votes.rs +++ b/src/votes.rs @@ -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)] -- 2.45.1