Minor config manager refactor

This commit is contained in:
August 2024-10-01 09:58:58 -04:00
parent 244dfac270
commit 398f2d8b2a
Signed by: shibedrill
GPG Key ID: 5FE0CB25945EFAA2
7 changed files with 37 additions and 27 deletions

2
Cargo.lock generated
View File

@ -1514,7 +1514,7 @@ dependencies = [
[[package]]
name = "shibe-bot"
version = "0.3.1"
version = "0.3.2"
dependencies = [
"build-time",
"dotenvy",

View File

@ -3,7 +3,7 @@ name = "shibe-bot"
description = "A Discord bot written in Rust, using Poise."
license = "MIT"
readme = "README.md"
version = "0.3.1"
version = "0.3.2"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -1,4 +1,4 @@
# Shibe Bot 0.3.1
# Shibe Bot 0.3.2
[![Rust](https://github.com/shibedrill/shibe-bot/actions/workflows/rust.yml/badge.svg)](https://github.com/shibedrill/shibe-bot/actions/workflows/rust.yml)
[![GitHub License](https://img.shields.io/github/license/shibedrill/shibe-bot)](LICENSE.txt)

View File

@ -35,7 +35,7 @@ pub async fn meow(ctx: Context<'_>) -> Result<(), Error> {
"woof"
// Will never return None. The source is statically defined.
// We know it will always have items in it.
} else {
} else {
meows
.choose(&mut rng)
.ok_or("`meows` array is empty")
@ -155,8 +155,11 @@ pub async fn deer(ctx: Context<'_>) -> Result<(), Error> {
error!("Executing command `deer` failed: {}", e);
})?
};
ctx.say(format!("https://vxreddit.com{}", &chosen_post.data.permalink))
.await?;
ctx.say(format!(
"https://vxreddit.com{}",
&chosen_post.data.permalink
))
.await?;
info!("Executed command `deer` successfully");
Ok(())
}

View File

@ -68,7 +68,9 @@ pub async fn add_channel(
match config.channels.iter().find(|item| **item == channel_id) {
None => {
config.channels.push(channel_id);
ctx.say(format!("Successfully added <#{channel_id}> to the channel registry."))
ctx.say(format!(
"Successfully added <#{channel_id}> to the channel registry."
))
.await?;
}
Some(_) => {
@ -92,12 +94,16 @@ pub async fn remove_channel(
let channel_id = { u64::from(channel.id()) };
match config.channels.iter().position(|item| *item == channel_id) {
None => {
ctx.say(format!("Channel <#{channel_id}> was not in the channel registry."))
ctx.say(format!(
"Channel <#{channel_id}> was not in the channel registry."
))
.await?;
}
Some(found) => {
config.channels.remove(found);
ctx.say(format!("Successfully removed <#{channel_id}> from the channel registry."))
ctx.say(format!(
"Successfully removed <#{channel_id}> from the channel registry."
))
.await?;
}
}
@ -145,7 +151,7 @@ pub async fn dice(
}
)
}
_ => format!("Rolled a random number from 1 to {sides}, got: {answer}")
_ => format!("Rolled a random number from 1 to {sides}, got: {answer}"),
};
ctx.say(response).await?;
info!("Executed command `dice` successfully");

View File

@ -88,10 +88,11 @@ async fn main() {
// Configure persistent options
let config_manager: Arc<Mutex<Manager<Settings>>> = Arc::new(Mutex::new(
Manager::load(SETTINGS_PATH)
.unwrap_or(Manager::manage(SETTINGS_PATH, Settings::default())),
Manager::load(SETTINGS_PATH).unwrap_or(Manager::manage(SETTINGS_PATH, Settings::default())),
));
config_manager.lock().await.store();
let _ = config_manager.lock().await.store().inspect_err(|e| {
error!("Failed to store config: {}", e);
});
// Set up framework
let framework = poise::Framework::builder()

View File

@ -13,12 +13,12 @@ pub struct Manager<T: Default + Serialize + for<'a> Deserialize<'a>> {
impl<T: Default + Serialize + for<'a> Deserialize<'a>> Manager<T> {
/// Instantiate new self if the path contains a valid serialization of
/// the settings structure.
pub fn load(path: &str) -> Option<Self> {
let mut file = std::fs::File::open(path).ok()?;
pub fn load(path: &str) -> Result<Self, std::io::Error> {
let mut file = std::fs::File::open(path)?;
let mut data = String::new();
file.read_to_string(&mut data).ok()?;
let settings = serde_json::from_str(&data).ok()?;
Some(Self {
file.read_to_string(&mut data)?;
let settings = serde_json::from_str(&data)?;
Ok(Self {
internal: settings,
path: String::from(path),
})
@ -27,20 +27,20 @@ impl<T: Default + Serialize + for<'a> Deserialize<'a>> Manager<T> {
/// disk but not in memory. Because this is a stupid method, it will most
/// likely go unused by most.
#[allow(dead_code)]
pub fn update(&mut self) -> Option<()> {
let mut file = std::fs::File::open(self.path.clone()).ok()?;
pub fn update(&mut self) -> Result<(), std::io::Error> {
let mut file = std::fs::File::open(self.path.clone())?;
let mut data = String::new();
file.read_to_string(&mut data).ok()?;
self.internal = serde_json::from_str(&data).ok()?;
Some(())
file.read_to_string(&mut data)?;
self.internal = serde_json::from_str(&data)?;
Ok(())
}
/// Serialize settings structure to the stored path. Returns None if
/// unsuccessful.
pub fn store(&self) -> Option<()> {
let data = serde_json::to_string_pretty(&self.internal).ok()?;
let mut file = std::fs::File::create(&self.path).ok()?;
pub fn store(&self) -> Result<(), std::io::Error> {
let data = serde_json::to_string_pretty(&self.internal)?;
let mut file = std::fs::File::create(&self.path)?;
let _ = file.write(data.as_bytes());
Some(())
Ok(())
}
/// Create a new manager, passing in the path, and a structure to manage.
/// We cannot initialize a settings manager without fully initialized settings.