use crate::{logging, theme::ThemeName};
use serde::{Deserialize, Serialize};
use std::env;
const GOVMR_TEST_VERSION: &str = "GOVMR_TEST_VERSION";
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ConfigFile {
#[serde(default)]
theme: String,
}
impl Default for ConfigFile {
fn default() -> Self {
Self {
theme: ThemeName::GoCyan.key().to_string(),
}
}
}
pub(crate) struct Config {
pub(crate) theme: ThemeName,
path: std::path::PathBuf,
}
impl Config {
#[must_use]
pub(crate) fn load(base_dir: &std::path::Path) -> Self {
let path = base_dir.join("config.toml");
let legacy = base_dir.join("config");
let mut source = "defaults";
let mut cfg = match std::fs::read_to_string(&path) {
Ok(raw) => match toml::from_str::<ConfigFile>(&raw) {
Ok(cfg) => {
source = "config.toml";
Some(cfg)
}
Err(e) => {
logging::warn(&format!(
"config: parse failed path=\"{}\" error={e} action=try_legacy",
path.display()
));
None
}
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => {
logging::warn(&format!(
"config: unreadable path=\"{}\" error={e} action=try_legacy",
path.display()
));
None
}
};
if cfg.is_none() {
let migrated = std::fs::read_to_string(&legacy)
.ok()
.and_then(|raw| parse_legacy_theme(&raw));
if let Some(theme) = migrated {
logging::info(&format!(
"config: migrated legacy=\"{}\" to=\"{}\" theme={theme} note=pending_first_save",
legacy.display(),
path.display()
));
cfg = Some(ConfigFile { theme });
source = "legacy config";
}
}
let cfg = cfg.unwrap_or_default();
let theme = ThemeName::from_key(&cfg.theme).unwrap_or_else(|| {
logging::warn(&format!(
"config: unknown theme value=\"{}\" path=\"{}\" fallback={}",
cfg.theme,
path.display(),
ThemeName::default().key()
));
ThemeName::default()
});
logging::info(&format!(
"config: loaded path=\"{}\" theme={} source={source}",
path.display(),
theme.key()
));
Self { theme, path }
}
pub(crate) fn set_theme(&mut self, theme: ThemeName) -> std::io::Result<()> {
self.theme = theme;
let cfg = ConfigFile {
theme: theme.key().to_string(),
};
let body = format!(
"# GoVMR user preferences\n# Re-generate with `govmr theme <name>` or press T in the TUI.\n\n{}\n",
toml::to_string(&cfg).map_err(std::io::Error::other)?
);
std::fs::write(&self.path, &body).map_err(|e| {
logging::error(&format!(
"config: write failed path=\"{}\" theme={} error={e}",
self.path.display(),
theme.key()
));
e
})?;
logging::debug(&format!(
"config: written path=\"{}\" theme={}",
self.path.display(),
theme.key()
));
Ok(())
}
}
pub(crate) fn current_govmr_version() -> String {
env::var(GOVMR_TEST_VERSION).unwrap_or_else(|_| env!("CARGO_PKG_VERSION").to_string())
}
fn parse_legacy_theme(contents: &str) -> Option<String> {
for line in contents.lines() {
let mut parts = line.splitn(2, '=');
let key = parts.next()?.trim();
let value = parts.next()?.trim();
if key == "theme" {
return Some(value.to_string());
}
}
None
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use std::{
path::PathBuf,
sync::atomic::{AtomicU64, Ordering},
};
static COUNTER: AtomicU64 = AtomicU64::new(0);
fn temp_dir() -> PathBuf {
let n = COUNTER.fetch_add(1, Ordering::SeqCst);
let dir = std::env::temp_dir().join(format!(
"govmr-cfg-test-{}-{}-{}",
std::process::id(),
n,
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn defaults_to_gocyan_when_absent() {
let dir = temp_dir();
let cfg = Config::load(&dir);
assert_eq!(cfg.theme, ThemeName::GoCyan);
}
#[test]
fn saves_and_reloads_theme_via_toml() {
let dir = temp_dir();
{
let mut cfg = Config::load(&dir);
cfg.set_theme(ThemeName::Nord).unwrap();
}
let toml_path = dir.join("config.toml");
let raw = std::fs::read_to_string(&toml_path).unwrap();
assert!(raw.contains("theme"), "toml body: {raw}");
assert!(raw.contains("nord"), "toml body: {raw}");
let cfg = Config::load(&dir);
assert_eq!(cfg.theme, ThemeName::Nord);
}
#[test]
fn migrates_legacy_plain_text_config() {
let dir = temp_dir();
std::fs::write(dir.join("config"), "theme = midnight\n").unwrap();
let cfg = Config::load(&dir);
assert_eq!(cfg.theme, ThemeName::Midnight);
}
#[test]
fn corrupt_toml_falls_back_to_default() {
let dir = temp_dir();
std::fs::write(dir.join("config.toml"), "this is = = not valid toml [").unwrap();
let cfg = Config::load(&dir);
assert_eq!(cfg.theme, ThemeName::GoCyan);
}
}