Updates the doc changes some string into &str and updates coverage

This commit is contained in:
Dandaedre 2024-11-05 23:18:53 +01:00
parent aa79b75b59
commit 5e27a178ce
7 changed files with 149 additions and 95 deletions

1
badges/coverage.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 96%"><title>test-coverage: 96%</title><linearGradient id="bms-6e323fc21180b9c4" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-6e323fc21180b9c4"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-6e323fc21180b9c4)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#fe7d37"/><rect width="122" height="18" fill="url(#bms-6e323fc21180b9c4)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">96%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">96%</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="88" height="18" role="img" aria-label="build: passing"><title>build: passing</title><linearGradient id="bms-de44f1c0747536f7" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-de44f1c0747536f7"><rect width="88" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-de44f1c0747536f7)"><rect width="37" height="18" fill="#555"/><rect x="37" width="51" height="18" fill="#97ca00"/><rect width="88" height="18" fill="url(#bms-de44f1c0747536f7)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="195" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="270">build</text><text x="195" y="130" transform="scale(.1)" fill="#fff" textLength="270">build</text><text aria-hidden="true" x="615" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">passing</text><text x="615" y="130" transform="scale(.1)" fill="#fff" textLength="410">passing</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="18" role="img" aria-label="test: passing"><title>test: passing</title><linearGradient id="bms-5402c39dce014bd3" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-5402c39dce014bd3"><rect width="82" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-5402c39dce014bd3)"><rect width="31" height="18" fill="#555"/><rect x="31" width="51" height="18" fill="#97ca00"/><rect width="82" height="18" fill="url(#bms-5402c39dce014bd3)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="165" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">test</text><text x="165" y="130" transform="scale(.1)" fill="#fff" textLength="210">test</text><text aria-hidden="true" x="555" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">passing</text><text x="555" y="130" transform="scale(.1)" fill="#fff" textLength="410">passing</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

1
badges/version.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="90" height="18" role="img" aria-label="version: 0.1.0"><title>version: 0.1.0</title><linearGradient id="bms-0431e50b7af7883f" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-0431e50b7af7883f"><rect width="90" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-0431e50b7af7883f)"><rect width="51" height="18" fill="#555"/><rect x="51" width="39" height="18" fill="#fe7d37"/><rect width="90" height="18" fill="url(#bms-0431e50b7af7883f)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="265" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">version</text><text x="265" y="130" transform="scale(.1)" fill="#fff" textLength="410">version</text><text aria-hidden="true" x="695" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="290">0.1.0</text><text x="695" y="130" transform="scale(.1)" fill="#fff" textLength="290">0.1.0</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -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<nom::Err<nom::error::Error<&str>>> for IdleError {

216
src/io.rs
View File

@ -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<dyn std::error::Error + Send + Sync>;
/// 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<serenity::RoleId>,
/// Optional hours describing the specific date of the event
hours: Option<String>,
/// Short name, used in voting titles
short_name: Option<String>,
/// Auto-Start date of the event (in human-readable format)
start_date: Option<String>,
non_days: Option<String>,
days: String,
/// Days not selected for the vote
non_days: Option<String>, // 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<String>, roles: Vec<String>) -> Option<String> {
/// 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<String>` 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<String> {
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<String>, 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<serenity::RoleId>,
#[description = "Description"] description: String,
#[description = "Horaires"] hours: Option<String>,
#[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<String> = 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())
}
}

View File

@ -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

View File

@ -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!()
}