feat(client-desktop): Add configuration loading and saving
Introduces a `Config` struct to manage client settings, including server URL and API key. This configuration is stored in a TOML file following OS-standard conventions. The `directories` crate is used to determine the correct path for the configuration file across different operating systems. The `thiserror` crate is used for custom error handling related to configuration loading and saving. Added unit tests to verify the configuration loading and saving logic.
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use directories::ProjectDirs;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
const CONFIG_FILENAME: &str = "client.toml";
|
||||
|
||||
/// Client configuration loaded from a TOML file at OS-standard paths.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct Config {
|
||||
/// Base URL of the doctate server, e.g. `https://doctate.example.org`.
|
||||
pub server_url: String,
|
||||
/// Per-user API key used in the `X-API-Key` header on upload.
|
||||
pub api_key: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ConfigError {
|
||||
#[error("cannot determine OS config directory (is $HOME set?)")]
|
||||
NoConfigDir,
|
||||
#[error("I/O error at {path}: {source}")]
|
||||
Io {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("parse error at {path}: {source}")]
|
||||
Parse {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: toml::de::Error,
|
||||
},
|
||||
#[error("serialize error: {0}")]
|
||||
Serialize(#[from] toml::ser::Error),
|
||||
}
|
||||
|
||||
/// Default config path, following OS conventions:
|
||||
/// Linux: `~/.config/doctate/client.toml`
|
||||
/// Windows: `%APPDATA%\doctate\client.toml`
|
||||
/// macOS: `~/Library/Application Support/doctate/client.toml`
|
||||
pub fn default_config_path() -> Result<PathBuf, ConfigError> {
|
||||
ProjectDirs::from("", "", "doctate")
|
||||
.map(|dirs| dirs.config_dir().join(CONFIG_FILENAME))
|
||||
.ok_or(ConfigError::NoConfigDir)
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Load from `path`. Returns `Ok(None)` if the file does not exist
|
||||
/// (first-run case); `Ok(Some(_))` on success; `Err` on I/O or parse
|
||||
/// errors — caller should surface these to the user, not swallow.
|
||||
pub fn load_from(path: &Path) -> Result<Option<Self>, ConfigError> {
|
||||
let text = match std::fs::read_to_string(path) {
|
||||
Ok(t) => t,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => {
|
||||
return Err(ConfigError::Io {
|
||||
path: path.into(),
|
||||
source: e,
|
||||
});
|
||||
}
|
||||
};
|
||||
let cfg: Config = toml::from_str(&text).map_err(|e| ConfigError::Parse {
|
||||
path: path.into(),
|
||||
source: e,
|
||||
})?;
|
||||
Ok(Some(cfg))
|
||||
}
|
||||
|
||||
/// Save to `path`, creating parent directories as needed.
|
||||
pub fn save_to(&self, path: &Path) -> Result<(), ConfigError> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| ConfigError::Io {
|
||||
path: parent.into(),
|
||||
source: e,
|
||||
})?;
|
||||
}
|
||||
let text = toml::to_string_pretty(self)?;
|
||||
std::fs::write(path, text).map_err(|e| ConfigError::Io {
|
||||
path: path.into(),
|
||||
source: e,
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convenience: load from `default_config_path()`.
|
||||
pub fn load() -> Result<Option<Self>, ConfigError> {
|
||||
Self::load_from(&default_config_path()?)
|
||||
}
|
||||
|
||||
/// Convenience: save to `default_config_path()`.
|
||||
pub fn save(&self) -> Result<(), ConfigError> {
|
||||
self.save_to(&default_config_path()?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn sample() -> Config {
|
||||
Config {
|
||||
server_url: "https://doctate.example.org".into(),
|
||||
api_key: "sk-test-12345".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_through_file() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let path = tmp.path().join("client.toml");
|
||||
|
||||
let original = sample();
|
||||
original.save_to(&path).unwrap();
|
||||
let loaded = Config::load_from(&path).unwrap();
|
||||
assert_eq!(loaded, Some(original));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_missing_file_returns_none() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let path = tmp.path().join("nonexistent.toml");
|
||||
assert!(Config::load_from(&path).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_creates_parent_dirs() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let path = tmp.path().join("deep/nested/client.toml");
|
||||
|
||||
sample().save_to(&path).unwrap();
|
||||
assert!(path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_invalid_toml_returns_parse_error() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let path = tmp.path().join("bad.toml");
|
||||
std::fs::write(&path, "this is not [valid toml").unwrap();
|
||||
let err = Config::load_from(&path).unwrap_err();
|
||||
assert!(matches!(err, ConfigError::Parse { .. }));
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
#[allow(dead_code)]
|
||||
mod config;
|
||||
|
||||
use eframe::egui;
|
||||
use tracing::info;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
Reference in New Issue
Block a user