From 5649066bd9d130ce954d0792e7fcfda824f8c78c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 1 Nov 2024 18:58:42 +0100 Subject: [PATCH] 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;