feat: add saving and reading server setting from config file

This commit is contained in:
2026-08-18 21:55:30 +02:00
parent aebf4f626f
commit 894c4c1cfb
7 changed files with 204 additions and 14 deletions

View File

@@ -0,0 +1,48 @@
use core::error;
use std::path::PathBuf;
use log::warn;
use serde::{Serialize, de::DeserializeOwned};
// maybe consider some better name for this
pub trait SettingsLike: Serialize + DeserializeOwned + Default {
fn get_config_dir() -> Result<PathBuf, Box<dyn error::Error>> {
Ok(dirs::config_local_dir()
.ok_or("Couldn't get config dir!")?
.join("checkers"))
}
fn get_file_path() -> Result<PathBuf, Box<dyn error::Error>>;
fn save_to_file(&self) -> Result<(), Box<dyn error::Error>> {
let path: PathBuf = Self::get_file_path()?;
if let Some(parent_dir) = path.parent() {
std::fs::create_dir_all(parent_dir)?;
}
let toml = toml::to_string(&self)?;
std::fs::write(path, toml)?;
Ok(())
}
fn read_from_file() -> Result<Self, Box<dyn error::Error>> {
Ok(toml::from_slice(&std::fs::read(Self::get_file_path()?)?)?) // i love rust
}
fn new() -> Self {
match Self::read_from_file() {
Ok(settings) => return settings,
Err(e) => warn!("Could not load settings from file, because: {}", e),
}
let settings = Self::default();
if let Err(e) = settings.save_to_file() {
warn!("Could not save server settings to the file, because: {}", e);
}
settings
}
}

2
src/settings/mod.rs Normal file
View File

@@ -0,0 +1,2 @@
pub mod general_settings;
pub mod server_settings;

View File

@@ -0,0 +1,33 @@
use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf,
};
use serde::{Deserialize, Serialize};
use crate::settings::general_settings::SettingsLike;
// TODO! More settings!
#[derive(Serialize, Deserialize)]
pub struct ServerSettings {
pub addr: SocketAddr,
pub max_connections: usize,
pub allow_spectators: bool,
}
impl SettingsLike for ServerSettings {
fn get_file_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
Ok(Self::get_config_dir()?.join("server.toml"))
}
}
impl Default for ServerSettings {
fn default() -> Self {
Self {
addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6767),
max_connections: 2, // Maybe this should be a const somewhere in the server code? It
// makes no sense to have different value than this
allow_spectators: false,
}
}
}