Adds a lib and fixes all doctests #8

Merged
Dandaedre merged 1 commits from split_lib into dev 2024-11-02 19:11:58 +01:00
10 changed files with 139 additions and 107 deletions

View File

@ -29,3 +29,12 @@ panic = "abort"
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(tarpaulin_include)'] }
[[bin]]
name = "idlefox"
path = "src/main.rs"
[lib]
name = "idlefox"
path = "src/lib.rs"

View File

@ -20,7 +20,9 @@
* [ ] Watchdog
# Examples testing
* [ ] Date
* [x] Dates
# Testing
* [ ] Thouroughly test the naivedate objects creations
# Tasks
## Dan

View File

@ -31,6 +31,7 @@
//! log::error!("{}", message);
//! # }
//!
use std::fs::File;
use log::LevelFilter;
@ -53,7 +54,7 @@ pub(crate) struct GlobalConfig {}
/// # Examples
///
/// ```
/// init_logger().expect("Failed to initialize logger");
/// idlefox::config::init_logger().expect("Failed to initialize logger");
/// // Log a message at the info level.
/// log::info!("This will be written to idlefox.log");
///

View File

@ -1,6 +1,6 @@
//! The module provides functions for parsing date strings into Rust structs.
//! The pseudo grammar is defined as:
//! ```
//! ```py
//! date = (day) (month) | (month) (day) | (weekday)
//! daterange = (date) - (date)
//! dateobject = (date) | (daterange)
@ -13,6 +13,7 @@
//!
//! ### Usage
//! ```
//! use idlefox::date::parse_str_into_date;
//! let result = parse_str_into_date("12 dec - 23 feb, lun - mer, 12, 14");
//!
//! // Parses into 12 dec - 23 feb
@ -46,14 +47,16 @@ use nom::{
///
/// ### Examples
/// ```
/// # use chrono::{Month, Weekday};
/// # use idlefox::date::date_parse::DatePoint;
/// // 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);
/// let date_point3 = DatePoint::Weekday(Weekday::Mon);
/// ```
#[derive(Debug, Clone, Copy)]
#[cfg_attr(test, derive(PartialEq))]
pub(crate) enum DatePoint {
pub enum DatePoint {
/// A day specified by it's position in the month, and an optionnal month
Date {
/// The day of the month
@ -74,8 +77,10 @@ pub(crate) enum DatePoint {
/// ### Data Structure
/// • start: The starting date in the range.
/// • stop: The end date in the range.
/// ```
/// ### Examples
/// ```
/// # use chrono::Month;
/// # use idlefox::date::date_parse::{DatePoint, DateRange};
/// // Create a date range from two DatePoint values
/// let date_range = DateRange {
/// start: DatePoint::Date { day: 1, month: Some(Month::January) },
@ -84,11 +89,11 @@ pub(crate) enum DatePoint {
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub(crate) struct DateRange {
pub struct DateRange {
/// The starting date in the range
pub(crate) start: DatePoint,
pub start: DatePoint,
/// The end date in the range
pub(crate) stop: DatePoint,
pub stop: DatePoint,
}
/// The DateObject enum represents the main date structure, which can be either a date range or a single date.
@ -101,6 +106,8 @@ pub(crate) struct DateRange {
///
/// ### Examples
/// ```
/// # use chrono::Month;
/// # use idlefox::date::date_parse::{DateObject, DatePoint, DateRange};
/// // Create a DateObject representing a range
/// let date_object1 = DateObject::Range(DateRange {
/// start: DatePoint::Date { day: 1, month: Some(Month::January) },
@ -134,12 +141,23 @@ pub enum DateObject {
///
/// ### Examples
/// ```
/// # use chrono::Month;
/// # use idlefox::date::date_parse::{DateList, DateObject, DatePoint, DateRange};
/// // 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) }),
/// let date_list = DateList::from(vec![
/// 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) },
/// start: DatePoint::Date {
/// day: 1,
/// month: Some(Month::February),
/// },
/// stop: DatePoint::Date {
/// day: 28,
/// month: Some(Month::February),
/// },
/// }),
/// ]);
/// ```
@ -150,14 +168,6 @@ pub type DateList = Vec<DateObject>;
/// ### 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((
@ -204,14 +214,6 @@ fn parse_month(input: &str) -> IResult<&str, Month> {
/// 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> {
@ -247,18 +249,6 @@ fn parse_weekday(input: &str) -> IResult<&str, Weekday> {
/// 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(
@ -295,11 +285,12 @@ fn parse_simple_date(input: &str) -> IResult<&str, DatePoint> {
/// Each format is represented by a separate [nom::combinator::map] combinator that parses the date range or single date object.
/// ### Examples
/// ```
/// # use idlefox::date::date_parse::parse_date_object;
/// // Parse "20dec -31jan"
/// let result1 = parse_date_object("20dec -31jan");
/// let result1 = parse_date_object("20dec -31jan").unwrap();
///
/// // Parse "Lun"
/// let result2 = parse_date_object("Lun");
/// let result2 = parse_date_object("Lun").unwrap();
/// ```
pub fn parse_date_object(input: &str) -> IResult<&str, DateObject> {
alt((
@ -320,8 +311,9 @@ pub fn parse_date_object(input: &str) -> IResult<&str, DateObject> {
/// Each date object is then parsed again using the [parse_date_object] function.
/// # Examples
/// ```
/// # use idlefox::date::parse_str_into_date;
/// // Parse "12 dec - 23 feb, lun - mer, 12, 14"
/// let result = parse_str_into_date("12 dec - 23 feb, lun - mer, 12, 14");
/// let list_dates = parse_str_into_date("12 dec - 23 feb, lun - mer, 12, 14").unwrap();
/// ```
pub fn parse_str_into_date(input: &str) -> IResult<&str, Vec<DateObject>> {
separated_list1(char(','), parse_date_object)(input)

View File

@ -22,12 +22,14 @@ use super::date_parse::{DateObject, DatePoint};
/// # Example
///
/// ```rust
/// # use chrono::{Weekday, Local};
/// # use idlefox::date::date_tools::relative_day_to_date;
///
/// 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(weekday: Weekday, context: Option<NaiveDate>) -> NaiveDate {
pub 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 - weekday as i64;
context - Duration::days(offset)
@ -47,19 +49,19 @@ pub(crate) fn relative_day_to_date(weekday: Weekday, context: Option<NaiveDate>)
/// A [chrono::NaiveDate] representing the date corresponding to the given partial date in the context of the provided date.
///
/// ### Example
/// ```
/// ```
/// # use chrono::NaiveDate;
/// # use idlefox::date::date_tools::relative_date_to_date;
/// // 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);
///
/// let context_date = NaiveDate::from_ymd_opt(2023, 2, 14).unwrap();
/// // 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
///
/// let date = relative_date_to_date(16, None, Some(context_date)).unwrap();
/// assert_eq!(date, NaiveDate::from_ymd_opt(2023, 2, 16).unwrap()); // 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
/// let date = relative_date_to_date(1, None, Some(context_date)).unwrap();
/// assert_eq!(date, NaiveDate::from_ymd_opt(2023, 3, 1).unwrap()); // The next 1st in in march, the next month
/// ```
pub(crate) fn relative_date_to_date(
pub fn relative_date_to_date(
day: u32,
month: Option<Month>,
context: Option<NaiveDate>,
@ -105,17 +107,19 @@ impl DatePoint {
/// # 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());
///use chrono::{Local, Month};
///use idlefox::date::date_parse::{DateObject, DatePoint};
///let today = Local::now().date_naive();
///let date_point = DatePoint::Date {
/// day: 14,
/// month: Some(Month::February),
///};
///let next_valid_date_object = DateObject::Single(date_point);
///let naive_date = next_valid_date_object
/// .to_naive_date_object(Some(today))
/// .unwrap();
/// ```
fn to_naive_date(self, context: Option<NaiveDate>) -> Result<NaiveDate, IdleError> {
match self {
@ -126,8 +130,8 @@ impl DatePoint {
}
/// An enum representing either a single [NaiveDate] or a date range between two [NaiveDate].
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
#[derive(Clone, Debug, PartialEq, Eq)]
// #[cfg_attr(test, derive(PartialEq))]
pub enum NaiveDateObject {
/// A range between two dates, inclusive at both ends.
Range {
@ -143,7 +147,7 @@ pub enum NaiveDateObject {
/// 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 {
pub struct NaiveDateList {
/// The inner vector
inner: Vec<NaiveDateObject>,
}
@ -154,17 +158,17 @@ impl DateObject {
/// # Examples
///
/// ```
/// use chrono::{Local, Datelike};
/// use idle_error_handling::date_parse::{NaiveDateList, DateObject, DatePoint};
/// use chrono::naive::NaiveDate;
///
/// # use idlefox::date::date_parse::{DateObject, DatePoint};
/// # use chrono::{Local, Month};
/// 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));
/// let date_point = DatePoint::Date {
/// day: 14,
/// month: Some(Month::March),
/// }; // February 14
/// let next_valid_date_object = DateObject::Single(date_point);
/// let naive_date = next_valid_date_object
/// .to_naive_date_object(Some(today))
/// .unwrap();
/// ```
pub fn to_naive_date_object(
&self,
@ -210,19 +214,21 @@ impl NaiveDateList {
/// # Examples
///
/// ```
/// use chrono::{Local, Datelike};
/// use idle_error_handling::date_parse::{NaiveDateList, DateObject, DatePoint};
/// use chrono::naive::NaiveDate;
///
/// # use chrono::Local;
/// # use idlefox::date::{
/// # date_parse::{DateObject, DatePoint},
/// # date_tools::NaiveDateList,
/// # };
/// 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 date_point = DatePoint::Date {
/// day: 14,
/// month: Some(chrono::Month::January),
/// };
/// let next_valid_date_object = DateObject::Single(date_point);
/// let list = NaiveDateList::from_context(vec![next_valid_date_object], Some(today));
///
/// assert!(list.is_ok());
/// ```
pub(crate) fn from_context(
pub fn from_context(
inner: Vec<DateObject>,
context: Option<NaiveDate>,
) -> Result<Self, IdleError> {

View File

@ -24,5 +24,11 @@ pub struct DateEventDate {}
pub struct DateEvent {}
// Defines date routines
pub(crate) mod date_parse;
pub(crate) mod date_tools;
pub mod date_parse;
pub mod date_tools;
// Republishing important functions
pub use date_parse::parse_str_into_date;
// TODO: Add these final user function
// pub use date_tools::naivelistfromstr;
// pub use date_tools::naivedayfromstr;

View File

@ -10,12 +10,12 @@
//!
//! ### Example usage:
//!
//! ```rust
//! use crate::discord;
//! ```no_run
//! use idlefox::io::discord_main_loop;
//!
//! #[tokio::main]
//! async fn main() {
//! discord::discord_main_loop().await;
//! discord_main_loop().await;
//! }
//! ```
//!

22
src/lib.rs Normal file
View File

@ -0,0 +1,22 @@
//! This is the root module of the `idlefox` library.
//!
//! It includes modules related to configuration, date parsing and handling, input/output operations, persistence management,
//! server-side operations, voting mechanisms, and process watchdog functionality. Each module provides functionalities for
//! managing different aspects of idle processes, such as reading from/write to files, storing data persistently,
//! running servers, receiving votes, monitoring process status, and more.
//!
//! The root module serves as a central entry point for users interested in using any part of the library.
//!
pub mod config; // Maybe in lib
pub mod date; // Definitely in lib
mod error_handling; // Likely in lib
mod ids; // Definitely in lib
pub mod io; // Maybe in lib
mod modules; // Maybe in lib
mod persistence; // Likely in lib
mod server; // Maybe in lib
mod votes; // Likely in lib
mod watchdog; // Definitely in lib
// TODO: Make sensible module re-export

View File

@ -5,25 +5,13 @@
// This line is here to force the use of extensive documentation
#![warn(clippy::missing_docs_in_private_items)]
use config::init_logger;
use io::discord_main_loop;
mod config;
mod date;
mod error_handling;
mod ids;
mod io;
mod modules;
mod persistence;
mod server;
mod votes;
mod watchdog;
use idlefox::config::init_logger;
use idlefox::io::discord_main_loop;
#[cfg(not(tarpaulin_include))]
#[tokio::main]
async fn main() {
init_logger().unwrap();
discord_main_loop().await;
// use date_parse::test_parsing;
// test_parsing();

6
tests/generic.rs Normal file
View File

@ -0,0 +1,6 @@
#[cfg(test)]
mod tests {
#[test]
fn generic_integration_test() {}
}