use std::path::PathBuf;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
pub struct Config {
pub data_dir: PathBuf,
pub remote: Option<String>,
}
impl Config {
pub fn load() -> Self {
let file = FileConfig::read();
let data_dir = std::env::var_os("TASU_DATA")
.map(PathBuf::from)
.or(file.data_dir)
.unwrap_or_else(default_data_dir);
let remote = std::env::var("TASU_REMOTE")
.ok()
.filter(|url| !url.trim().is_empty())
.or(file.remote);
Self { data_dir, remote }
}
pub fn board_path(&self) -> PathBuf {
self.data_dir.join("todos.json")
}
pub fn config_file() -> Option<PathBuf> {
dirs::config_dir().map(|dir| dir.join("tasu").join("config.json"))
}
pub fn set_remote(remote: Option<&str>) -> std::io::Result<PathBuf> {
let mut file = FileConfig::read();
file.remote = remote.map(str::to_string);
file.write()
}
}
#[derive(Debug, Default, Deserialize, Serialize)]
struct FileConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
data_dir: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
remote: Option<String>,
}
impl FileConfig {
fn read() -> Self {
let Some(path) = Config::config_file() else {
return Self::default();
};
let Ok(text) = std::fs::read_to_string(path) else {
return Self::default();
};
serde_json::from_str(&text).unwrap_or_default()
}
fn write(&self) -> std::io::Result<PathBuf> {
let path = Config::config_file()
.ok_or_else(|| std::io::Error::other("no config directory on this platform"))?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let json = serde_json::to_string_pretty(self)?;
std::fs::write(&path, json)?;
Ok(path)
}
}
fn default_data_dir() -> PathBuf {
dirs::data_dir()
.map(|dir| dir.join("tasu"))
.unwrap_or_else(|| PathBuf::from("."))
}