ccs: migratable config

This commit is contained in:
Alex Janka 2025-01-09 09:20:09 +11:00
parent 8b26a8d6bb
commit 7ceaf73037
2 changed files with 48 additions and 12 deletions

View file

@ -15,7 +15,7 @@ pub(super) struct ConfigWatcher {
pub fn init_config(path: impl AsRef<std::path::Path>) -> Option<ConfigWatcher> {
log::trace!("loading config...");
let config = Config::load(&path);
let config = Config::load(&path).unwrap();
log::trace!("watching config for changes...");
let config_watcher = ConfigWatcher::new(&path);
let _ = CONFIG_PATH.get_or_init(|| path.as_ref().to_path_buf());
@ -48,7 +48,7 @@ impl ConfigWatcher {
loop {
match rx.recv().await {
Some(Ok(_event)) => {
let config = Config::load(&config_path);
let config = Config::load(&config_path).unwrap();
if let Err(e) = overwrite_config(config).await {
log::error!("{e:?}");
@ -114,17 +114,26 @@ pub async fn write_to_config<'a>() -> ConfigHandle<'a> {
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
#[serde(default)]
pub struct Config {
pub primary_charge_controller: String,
pub enable_secondary_control: bool,
pub charge_controllers: Vec<ChargeControllerConfig>,
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(tag = "version")]
pub enum ConfigStorage {
#[serde(rename = "1")]
V1(Config),
}
impl Config {
fn load(path: impl AsRef<std::path::Path>) -> Self {
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
impl Default for ConfigStorage {
fn default() -> Self {
Self::from_latest(Default::default())
}
}
impl ConfigStorage {
const fn from_latest(config: Config) -> Self {
Self::V1(config)
}
fn load(path: impl AsRef<std::path::Path>) -> eyre::Result<Self> {
Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?)
}
fn save_to(&self, path: impl AsRef<std::path::Path>) -> eyre::Result<()> {
@ -137,6 +146,33 @@ impl Config {
fn save(&self) -> eyre::Result<()> {
self.save_to(CONFIG_PATH.get().unwrap())
}
fn into_latest(self) -> Config {
match self {
ConfigStorage::V1(config) => config,
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
#[serde(default)]
pub struct Config {
pub primary_charge_controller: String,
pub enable_secondary_control: bool,
pub charge_controllers: Vec<ChargeControllerConfig>,
}
impl Config {
fn load(path: impl AsRef<std::path::Path>) -> eyre::Result<Self> {
let storage = ConfigStorage::load(path)?;
Ok(storage.into_latest())
}
fn save(&self) -> eyre::Result<()> {
let as_storage = ConfigStorage::from_latest(self.clone());
as_storage.save()?;
Ok(())
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]

View file

@ -59,7 +59,7 @@ async fn run() -> eyre::Result<()> {
match args.command {
Commands::Watch => watch(args).await,
Commands::GenerateConfig => {
let config = config::Config::default();
let config = config::ConfigStorage::default();
let json = serde_json::to_string_pretty(&config)?;
println!("{json}");
Ok(())