use std::fs;
use std::path::PathBuf;
use lobe_core::error::{Result, TloxError};
use serde::{Deserialize, Serialize};
pub const DEFAULT_WEB_URL: &str = "https://getlobe.dev";
pub const DEFAULT_API_URL: &str = "https://ceaseless-beagle-861.convex.site";
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Config {
#[serde(default)]
pub auth: Auth,
#[serde(default)]
pub urls: Urls,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Auth {
pub token: Option<String>,
pub email: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Urls {
pub web: String,
pub api: String,
}
impl Default for Urls {
fn default() -> Self {
Self {
web: DEFAULT_WEB_URL.to_string(),
api: DEFAULT_API_URL.to_string(),
}
}
}
pub fn config_path() -> Result<PathBuf> {
let home = home::home_dir().ok_or_else(|| {
TloxError::Io(std::io::Error::other(
"could not determine home directory",
))
})?;
Ok(home.join(".config").join("lobe").join("config.toml"))
}
pub fn load() -> Result<Config> {
let path = config_path()?;
if !path.exists() {
return Ok(Config::default());
}
let contents = fs::read_to_string(&path)?;
toml::from_str(&contents)
.map_err(|e| TloxError::Io(std::io::Error::other(format!("config parse error: {e}"))))
}
pub fn save(config: &Config) -> Result<()> {
let path = config_path()?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let contents = toml::to_string_pretty(config)
.map_err(|e| TloxError::Io(std::io::Error::other(format!("config write error: {e}"))))?;
fs::write(&path, contents)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(&path)?.permissions();
perms.set_mode(0o600);
fs::set_permissions(&path, perms)?;
}
Ok(())
}