Adds all docs for date, adds functions to make a Naivedate from the parsed strings #7
3
TODO.md
3
TODO.md
|
|
@ -32,3 +32,6 @@
|
|||
* [x] Write documentation for all functions in IO.rs
|
||||
* [ ] Replace the usage of print with the appropriate logging where needed
|
||||
* [ ] Create all module signature for queries
|
||||
* [ ] Make worker functions (dedup code)
|
||||
* [ ] Create a smaller context (?)
|
||||
* [ ] Have a testing preset
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ pub(crate) enum DatePoint {
|
|||
/// A day specified by it's position in the month, and an optionnal month
|
||||
Date {
|
||||
/// The day of the month
|
||||
day: usize,
|
||||
day: u32,
|
||||
/// An optional month
|
||||
month: Option<Month>,
|
||||
},
|
||||
|
|
@ -86,9 +86,9 @@ pub(crate) enum DatePoint {
|
|||
#[cfg_attr(test, derive(PartialEq))]
|
||||
pub(crate) struct DateRange {
|
||||
/// The starting date in the range
|
||||
start: DatePoint,
|
||||
pub(crate) start: DatePoint,
|
||||
/// The end date in the range
|
||||
stop: DatePoint,
|
||||
pub(crate) stop: DatePoint,
|
||||
}
|
||||
|
||||
/// The DateObject enum represents the main date structure, which can be either a date range or a single date.
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@
|
|||
use crate::error_handling::IdleError;
|
||||
use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, Weekday};
|
||||
|
||||
use super::date_parse::{DateObject, DatePoint};
|
||||
|
||||
/// Returns the date corresponding to the implicit Weekday
|
||||
///
|
||||
/// Aka the next day implied by the day given
|
||||
|
|
@ -25,41 +27,12 @@ use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, Weekday};
|
|||
/// 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 {
|
||||
pub(crate) fn relative_day_to_date(weekday: 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;
|
||||
let offset = context.weekday() as i64 - weekday as i64;
|
||||
context - Duration::days(offset)
|
||||
}
|
||||
|
||||
/// 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
|
||||
pub(crate) month: Option<Month>,
|
||||
/// The day of the month implied in the date
|
||||
pub(crate) day: u32,
|
||||
}
|
||||
|
||||
/// The relative_date_to_date function finds the date corresponding to a loosely defined implicit partial date.
|
||||
///
|
||||
/// The date returned will be the next valid date after the context.
|
||||
|
|
@ -87,31 +60,188 @@ pub(crate) struct PartialDate {
|
|||
/// 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,
|
||||
day: u32,
|
||||
month: Option<Month>,
|
||||
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 {
|
||||
match match month {
|
||||
Some(m) if m.number_from_month() >= context.month() => context
|
||||
.with_month(m.number_from_month())
|
||||
.ok_or(IdleError::InvalidDate),
|
||||
Some(_m) => context
|
||||
.checked_add_months(Months::new(12))
|
||||
.ok_or(IdleError::InvalidDate),
|
||||
None if date.day >= context.day() => Ok(context),
|
||||
None if day >= context.day() => Ok(context),
|
||||
None => context
|
||||
.checked_add_months(Months::new(1))
|
||||
.ok_or(IdleError::InvalidDate),
|
||||
} {
|
||||
Ok(new_base) => new_base
|
||||
.with_day(date.day)
|
||||
.ok_or(IdleError::InvalidDate(date)),
|
||||
Err(_) => Err(IdleError::InvalidDate(date)),
|
||||
.with_day(day)
|
||||
.ok_or(IdleError::InvalidDate(day, month)),
|
||||
Err(_) => Err(IdleError::InvalidDate(day, month)),
|
||||
}
|
||||
}
|
||||
|
||||
impl DatePoint {
|
||||
/// Converts a DatePoint to a NaiveDate, optionally relative to a given context date.
|
||||
///
|
||||
/// The conversion depends on the specific type of [DatePoint]:
|
||||
/// - For `DatePoint::Date { day, month }`, it calculates the next valid date after the provided or current context.
|
||||
/// - For `DatePoint::Weekday(weekday)`, it finds the next occurrence of that weekday relative to the context.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `self`: The [DatePoint] to convert.
|
||||
/// * `context`: An optional reference date. If not provided, the function uses the current date as a default.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A Result containing a [NaiveDate] if successful, or an [IdleError] if the date could not be calculated due to invalid input.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// let today = Local::now().date_naive();
|
||||
/// // Example for DatePoint::Date where the month and day are specified.
|
||||
/// let date_point = DatePoint::Date { day: 14, month: Some(2) }; // February 14
|
||||
/// let next_valid_date = date_point.to_naive_date(Some(today));
|
||||
///
|
||||
/// // Example for DatePoint::Weekday where only a weekday is specified.
|
||||
/// let date_point_weekday = DatePoint::Weekday(chrono::Weekday::Mon); // Next Monday
|
||||
/// let next_valid_date_weekday = date_point_weekday.to_naive_date(Some(today));
|
||||
///
|
||||
/// assert!(next_valid_date.is_ok());
|
||||
/// assert!(next_valid_date_weekday.is_ok());
|
||||
/// ```
|
||||
fn to_naive_date(self, context: Option<NaiveDate>) -> Result<NaiveDate, IdleError> {
|
||||
match self {
|
||||
DatePoint::Date { day, month } => relative_date_to_date(day, month, context),
|
||||
DatePoint::Weekday(weekday) => Ok(relative_day_to_date(weekday, context)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An enum representing either a single [NaiveDate] or a date range between two [NaiveDate].
|
||||
#[derive(Clone, Debug)]
|
||||
#[cfg_attr(test, derive(PartialEq))]
|
||||
pub enum NaiveDateObject {
|
||||
/// A range between two dates, inclusive at both ends.
|
||||
Range {
|
||||
/// Start of the range
|
||||
start: NaiveDate,
|
||||
/// End of the range
|
||||
stop: NaiveDate,
|
||||
},
|
||||
/// A single [NaiveDate] object.
|
||||
Single(NaiveDate),
|
||||
}
|
||||
|
||||
/// A collection of [NaiveDateObject]s, allowing for sequential and random access to their start dates.
|
||||
///
|
||||
/// This struct can be used to iterate over a list of dates in order or access any date by its index.
|
||||
pub(crate) struct NaiveDateList {
|
||||
/// The inner vector
|
||||
inner: Vec<NaiveDateObject>,
|
||||
}
|
||||
|
||||
impl DateObject {
|
||||
/// Converts this [DateObject] to a corresponding [NaiveDateObject], using the provided context for relative date calculations.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use chrono::{Local, Datelike};
|
||||
/// use idle_error_handling::date_parse::{NaiveDateList, DateObject, DatePoint};
|
||||
/// use chrono::naive::NaiveDate;
|
||||
///
|
||||
/// let today = Local::now().date_naive();
|
||||
/// let date_point = DatePoint::Date { day: 14, month: Some(2) }; // February 14
|
||||
/// let next_valid_date_object = DateObject::new(date_point);
|
||||
///
|
||||
/// let naive_date = next_valid_date_object.to_naive_date_object(Some(today)).unwrap();
|
||||
///
|
||||
/// assert_eq!(naive_date.start(), today.with_day(14).with_month(2));
|
||||
/// ```
|
||||
pub fn to_naive_date_object(
|
||||
&self,
|
||||
context: Option<NaiveDate>,
|
||||
) -> Result<NaiveDateObject, IdleError> {
|
||||
match self {
|
||||
DateObject::Range(date_range) => Ok(NaiveDateObject::Range {
|
||||
start: date_range.start.to_naive_date(context)?,
|
||||
stop: date_range.stop.to_naive_date(context)?,
|
||||
}),
|
||||
DateObject::Single(date_point) => {
|
||||
Ok(NaiveDateObject::Single(date_point.to_naive_date(context)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NaiveDateList {
|
||||
/// Creates a new [NaiveDateList] from an existing vector of [NaiveDateObject]s.
|
||||
pub fn new(inner: Vec<NaiveDateObject>) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
/// Returns the number of dates in this [NaiveDateList].
|
||||
pub fn len(&self) -> usize {
|
||||
self.inner.len()
|
||||
}
|
||||
|
||||
/// Checks if this [NaiveDateList] is empty.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.inner.is_empty()
|
||||
}
|
||||
|
||||
/// Retrieves a reference to the [NaiveDateObject] at the specified index.
|
||||
pub fn get(&self, index: usize) -> Option<&NaiveDateObject> {
|
||||
self.inner.get(index)
|
||||
}
|
||||
|
||||
/// Creates a new [NaiveDateList] from an existing vector of [DateObject]s and a context date.
|
||||
///
|
||||
/// The `context` is used to resolve any relative dates in the `inner` list.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use chrono::{Local, Datelike};
|
||||
/// use idle_error_handling::date_parse::{NaiveDateList, DateObject, DatePoint};
|
||||
/// use chrono::naive::NaiveDate;
|
||||
///
|
||||
/// let today = Local::now().date_naive();
|
||||
/// let date_point = DatePoint::Date { day: 14, month: Some(2) }; // February 14
|
||||
/// let next_valid_date_object = DateObject::new(date_point);
|
||||
///
|
||||
/// let list = NaiveDateList::from_context(vec![next_valid_date_object], Some(today));
|
||||
///
|
||||
/// assert!(list.is_ok());
|
||||
/// ```
|
||||
pub(crate) fn from_context(
|
||||
inner: Vec<DateObject>,
|
||||
context: Option<NaiveDate>,
|
||||
) -> Result<Self, IdleError> {
|
||||
let mut new = Vec::new();
|
||||
for elem in inner {
|
||||
new.push(elem.to_naive_date_object(context)?);
|
||||
}
|
||||
Ok(Self { inner: new })
|
||||
}
|
||||
}
|
||||
|
||||
// impl IntoIterator for NaiveDateList {
|
||||
// type Item = NaiveDate;
|
||||
// type IntoIter = std::vec::IntoIter<Self::Item>;
|
||||
|
||||
// fn into_iter(self) -> Self::IntoIter {
|
||||
// self.inner.into_iter()
|
||||
// }
|
||||
// }
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
//!
|
||||
//! It consists of two submodules:
|
||||
//!
|
||||
//! - `dateparse`: This submodule is responsible for parsing a string representation of a date into a vector of [DateObject] instances.
|
||||
//! - `dateparse`: This submodule is responsible for parsing a string representation of a date into a vector of [date_parse::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.
|
||||
|
|
@ -10,7 +10,6 @@
|
|||
//!
|
||||
#![allow(dead_code)]
|
||||
|
||||
mod date_parse;
|
||||
// All structures
|
||||
/// A punctual day (just one date)
|
||||
pub struct DateEventPunctual {}
|
||||
|
|
@ -25,5 +24,5 @@ pub struct DateEventDate {}
|
|||
pub struct DateEvent {}
|
||||
|
||||
// Defines date routines
|
||||
pub(crate) mod date_parse;
|
||||
pub(crate) mod date_tools;
|
||||
pub(crate) use date_tools::PartialDate;
|
||||
|
|
|
|||
|
|
@ -5,12 +5,11 @@
|
|||
//! went wrong, making it easier to diagnose and fix problems.
|
||||
|
||||
#![allow(dead_code)]
|
||||
use chrono::Month;
|
||||
use log::SetLoggerError;
|
||||
use poise::serenity_prelude;
|
||||
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)]
|
||||
|
||||
|
|
@ -28,9 +27,9 @@ pub enum IdleError {
|
|||
|
||||
/// 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:?}")]
|
||||
InvalidDate(PartialDate),
|
||||
/// This error is raised when a user-provided date string cannot be parsed into a valid (date, month).
|
||||
#[error("An error happened while tring to make sense of the date ({0:?},{1:?})")]
|
||||
InvalidDate(u32, Option<Month>),
|
||||
|
||||
/// Generic error indicating an unexpected issue during Discord API call processing
|
||||
///
|
||||
|
|
@ -41,7 +40,7 @@ pub enum IdleError {
|
|||
|
||||
/// Error indicating an invalid date string
|
||||
///
|
||||
/// This error is raised when a user-provided date string cannot be parsed into a valid [PartialDate].
|
||||
/// This error is raised when a user-provided date string cannot be parsed into a valid [crate::date::date_parse::DatePoint].
|
||||
/// Notifying the user and asking for manual correction will likely be required
|
||||
#[error("An error occured while parsing the date given {0:?}")]
|
||||
InvalidDateParsing(nom::Err<nom::error::Error<Box<str>>>),
|
||||
|
|
|
|||
Loading…
Reference in New Issue