diff --git a/badges/coverage.svg b/badges/coverage.svg new file mode 100644 index 0000000..16d4a9f --- /dev/null +++ b/badges/coverage.svg @@ -0,0 +1 @@ +test-coverage: 96%test-coverage96% diff --git a/badges/test.svg b/badges/test.svg index a34aaf8..a7859aa 100644 --- a/badges/test.svg +++ b/badges/test.svg @@ -1 +1 @@ -build: passingbuildpassing +test: passingtestpassing diff --git a/badges/version.svg b/badges/version.svg new file mode 100644 index 0000000..c28c459 --- /dev/null +++ b/badges/version.svg @@ -0,0 +1 @@ +version: 0.1.0version0.1.0 diff --git a/src/error_handling.rs b/src/error_handling.rs index 9e4c343..44963c3 100644 --- a/src/error_handling.rs +++ b/src/error_handling.rs @@ -51,6 +51,18 @@ pub enum IdleError { /// 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), + + /// Represents an error while acquiring a Discord group + /// + /// Raised when there is an error attempting to acquire the discord group + #[error("An error occured while tring to acquire the discord group: {0}")] + AcquiringDiscordGroup(String), + + /// Indicates an error while acquiring Discord guilds + /// + /// This may happen when a function was called outside of the context of a server (likely a DM to the bot). + #[error("An error occured while tring to acquire discord guilds")] + AcquiringDiscordGuild, } impl From>> for IdleError { diff --git a/src/io.rs b/src/io.rs index 5b33b4b..c568376 100644 --- a/src/io.rs +++ b/src/io.rs @@ -19,10 +19,15 @@ //! } //! ``` //! +#![allow(dead_code)] use crate::modules::handler; use distance::levenshtein; use poise::serenity_prelude::{self as serenity}; +use poise::Modal as _; + +use crate::error_handling::IdleError; + /// User data, which is stored and accessible in all command invocations pub struct Data {} /// A generic temporary serenity error @@ -30,21 +35,34 @@ type GenericError = Box; /// The context (in a discord sence) of a message type Context<'a> = poise::Context<'a, Data, GenericError>; +/// A `VoteContainer` holds the details of a vote that is to be created. +/// +/// This struct aggregates all the necessary data describing this event within a Discord guild (server). /// Generic object that is used to transfer vote data to other parts of the code. +#[derive(Default)] pub struct VoteContainer { + /// The title of the event title: String, + /// Description of the event description: String, + /// An optional serenity::RoleId to specify the role group concerned by the vote. group: Option, + /// Optional hours describing the specific date of the event hours: Option, + /// Short name, used in voting titles short_name: Option, + /// Auto-Start date of the event (in human-readable format) start_date: Option, - non_days: Option, - days: String, + /// Days not selected for the vote + non_days: Option, // TODO: What ? + /// Days selected for the vote + days: String, // TODO: What ? + /// Date the event begins date_begin: String, + /// Date the event ends date_end: String, + /// An identifier for the vote identifier: VoteTypeIdentifier, - // ctx: Context<'_>, - // Context needs a "lifetime" parameter, I have no idea what that is } /// Only title, description and identifier are mandatory @@ -59,29 +77,40 @@ impl VoteContainer { } } -/// Default is None -impl Default for VoteContainer { - fn default() -> Self { - Self { - title: "".to_string(), - description: "".to_string(), - group: None, - hours: None, - short_name: None, - start_date: None, - non_days: None, - days: "".to_string(), - date_begin: "".to_string(), - date_end: "".to_string(), - identifier: VoteTypeIdentifier::Uninitialised, - } - } -} +// /// Default is None +// impl Default for VoteContainer { +// fn default() -> Self { +// Self { +// title: "".to_string(), +// description: "".to_string(), +// group: None, +// hours: None, +// short_name: None, +// start_date: None, +// non_days: None, +// days: "".to_string(), +// date_begin: "".to_string(), +// date_end: "".to_string(), +// identifier: VoteTypeIdentifier::Uninitialised, +// } +// } +// } +/// Identifies the type of the vote being created. +/// +/// This enum represents different types of votes, such as regular weekly votes, +/// short-term votes, and long-term votes. It also serves as an indicator when a vote type +/// hasn't been initialized yet. +#[derive(Default)] pub enum VoteTypeIdentifier { + // Represents a recurring weekly vote, with the list of days voted upon being one week WeeklyVote, + /// Represents a short-term vote, that can be of any length and can be cast at any time without any form or plan. ShortVote, + /// Represents a long-term vote, where the list of days voted upon extends beyond a week. LongVote, + /// Indicates that the vote type has not been set yet, should only be used by default and is not a valid value. + #[default] Uninitialised, } @@ -145,50 +174,46 @@ impl Default for WeeklyVoteModal { pub async fn vote_modal( ctx: poise::ApplicationContext<'_, Data, GenericError>, ) -> Result<(), GenericError> { - use poise::Modal as _; - let data = WeeklyVoteModal::execute(ctx).await?; - if let Some(unwrapped_data) = data { + if let Some(underlying_data) = data { log::info!( "@{:?} **{:?}**\n{:?}\n{:?}, {:?}", - unwrapped_data.group, - unwrapped_data.title, - unwrapped_data.description, - unwrapped_data.short_name, - unwrapped_data.hours + underlying_data.group, + underlying_data.title, + underlying_data.description, + underlying_data.short_name, + underlying_data.hours ); log::info!("{:?}", &ctx); - // let group = unwrapped_data.group.unwrap_or("".into()); - // let title = unwrapped_data.title; - // let description = unwrapped_data.description; - // let short_name = unwrapped_data.short_name.unwrap_or("".into()); - // let hours = unwrapped_data.hours.unwrap_or("".into()); - - let saucisse = find_role_from_string( - unwrapped_data.group, - ctx.guild() - .unwrap() - .roles - .values() - .map(|v| v.name.clone()) - .collect(), + // This whole shenennigan only exists to find a group as specified by text and if so apply it + // However many steps can subtly break and cannot be truly accounted for + let guild = ctx + .guild() + .ok_or_else(|| IdleError::AcquiringDiscordGuild)?; // Maybe the guild cannot be retrieved from the context, such as in a DM + let group = find_role_from_str( + underlying_data.group.as_deref(), + guild.roles.values().map(|v| v.name.as_str()).collect(), ) - .map(|find_role_from_string| { - ctx.guild() - .unwrap() - .role_by_name(&find_role_from_string) - .unwrap() - .id - }); + .ok_or(IdleError::AcquiringDiscordGuild) // Maybe the guild doesn't exits or the match is too far or the group wasn't specified + .and_then(|role_found: String| { + guild + .role_by_name(&role_found) + .ok_or(IdleError::AcquiringDiscordGroup(role_found)) // Maybe somehow the group canno't be acquired by that name + .map(|v| v.id) + }) + .inspect_err( + |e| /* Do something when an error occurs*/ log::error!("An error occured when selecting groups from {:?}: {}",&underlying_data.group,e), + ) // An inspect that could be used to signal something went wrong acquiring or applying the guild + .ok(); let serotoninenjoyer = VoteContainer { - title: unwrapped_data.title, - description: unwrapped_data.description, - group: saucisse, - hours: unwrapped_data.hours, - short_name: unwrapped_data.short_name, + title: underlying_data.title, + description: underlying_data.description, + group, + hours: underlying_data.hours, + short_name: underlying_data.short_name, identifier: VoteTypeIdentifier::WeeklyVote, ..Default::default() }; @@ -205,36 +230,46 @@ pub async fn vote_modal( Ok(()) } -fn find_role_from_string(group: Option, roles: Vec) -> Option { +/// Attempts to find the most closely matching role from a list based on a provided group name. +/// +/// This function takes a `group` string and a vector of role names, and returns the closest match found. +/// If the input `group` is None or the `roles` vector is empty, the function will return None. +/// The search uses the Levenshtein distance algorithm to determine the similarity between strings. +/// +/// # Arguments +/// +/// * `group` - An `Option` representing the target group name for which a match should be found. +/// * `roles` - A vector of `String`s containing role names to compare against the target group name. +fn find_role_from_str(group: Option<&str>, roles: Vec<&str>) -> Option { if group.is_none() || roles.is_empty() { return None; } let group = group.unwrap(); // We are hard-coding the maximum value above which we prefer returning None rather than a guess - let mut lowest: (Option, usize) = (None, 5); + let mut lowest = (None, 5); for role in roles { - let d = levenshtein(&role, &group); + let d = levenshtein(role, group); if d < lowest.1 { lowest = (Some(role), d); }; } - lowest.0 + lowest.0.map(|s| s.to_owned()) } -/// 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, -} +// /// 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" @@ -283,7 +318,7 @@ pub async fn vote_command( pub async fn short_vote( ctx: Context<'_>, #[description = "Titre"] title: String, - #[description = "Groupe"] group: ListOfRoles, + #[description = "Groupe"] group: Option, #[description = "Description"] description: String, #[description = "Horaires"] hours: Option, #[description = "Jours"] days: String, @@ -291,7 +326,7 @@ pub async fn short_vote( ) -> Result<(), GenericError> { let aortavalve = VoteContainer { title, - // group, + group, description, hours, days, @@ -375,7 +410,7 @@ mod tests { use super::*; #[test] fn test_levenshtein() { - let arguments: Vec = vec![ + let arguments = [ "hunters", "ffxiv_idle", "ffxiv_progfish", @@ -385,15 +420,28 @@ mod tests { "r6", "apex", "boardgames", - ] - .iter() - .map(|v| v.to_string()) - .collect(); - println!("{:?}", arguments); - println!( - "{:?}", - find_role_from_string(Some("bodyoncetoldme".to_string()), arguments.clone()) + ]; + // println!("{:?}", arguments); + // println!( + // "{:?}", + // find_role_from_str(Some("bodyoncetoldme"), arguments.to_vec()) + // ); + assert!(find_role_from_str(Some("bodyoncetoldme"), arguments.to_vec()).is_none()); + assert_eq!( + find_role_from_str(Some("ffxivid"), arguments.to_vec()), + Some("ffxiv_idle".to_string()) + ); + assert_eq!( + find_role_from_str(Some("hunte"), arguments.to_vec()), + Some("hunters".to_string()) + ); + assert_eq!( + find_role_from_str(Some("dbd"), arguments.to_vec()), + Some("dbd".to_string()) + ); + assert_eq!( + find_role_from_str(Some("ffxivpogfish"), arguments.to_vec()), + Some("ffxiv_progfish".to_string()) ); - assert!(find_role_from_string(Some("bodyoncetoldme".to_string()), arguments).is_none()) } } diff --git a/src/lib.rs b/src/lib.rs index f04cbe3..23910d4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,6 +7,7 @@ //! //! The root module serves as a central entry point for users interested in using any part of the library. //! +#![warn(clippy::missing_docs_in_private_items)] pub mod config; // Maybe in lib pub mod date; // Definitely in lib diff --git a/src/modules.rs b/src/modules.rs index cce54b5..3f416ba 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -7,16 +7,7 @@ use crate::io::VoteContainer; -struct LongVote { - // todo -} -struct ShortVote { - // todo -} -struct WeeklyVote { - // todo -} - +/// Handles the vote ? pub fn handler(vc: VoteContainer) { todo!() }