From 63802dfcf9c1e30cc2a72c15953af4c4af9f8eef Mon Sep 17 00:00:00 2001 From: Jeremy Soller Date: Fri, 12 Jan 2024 09:39:35 -0700 Subject: [PATCH] cosmic-config-derive: automatically generate setters --- cosmic-config-derive/src/lib.rs | 25 +++++++++++++++++++++++++ cosmic-theme/src/model/mode.rs | 5 ----- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/cosmic-config-derive/src/lib.rs b/cosmic-config-derive/src/lib.rs index b8b2fb0..79dad71 100644 --- a/cosmic-config-derive/src/lib.rs +++ b/cosmic-config-derive/src/lib.rs @@ -80,6 +80,27 @@ fn impl_cosmic_config_entry_macro(ast: &syn::DeriveInput) -> TokenStream { } }); + let setters = fields.iter().filter_map(|field| { + let field_name = &field.ident.as_ref()?; + let field_type = &field.ty; + let setter_name = quote::format_ident!("set_{}", field_name); + let doc = format!("Sets [`{name}::{field_name}`] and writes to [`cosmic_config::Config`] if changed"); + Some(quote! { + #[doc = #doc] + /// + /// Returns `Ok(true)` when the field's value has changed and was written to disk + pub fn #setter_name(&mut self, config: &cosmic_config::Config, value: #field_type) -> Result { + if self.#field_name != value { + self.#field_name = value; + cosmic_config::ConfigSet::set(config, stringify!(#field_name), &self.#field_name)?; + Ok(true) + } else { + Ok(false) + } + } + }) + }); + let gen = quote! { impl CosmicConfigEntry for #name { const VERSION: u64 = #version; @@ -115,6 +136,10 @@ fn impl_cosmic_config_entry_macro(ast: &syn::DeriveInput) -> TokenStream { (errors, keys) } } + + impl #name { + #(#setters)* + } }; gen.into() diff --git a/cosmic-theme/src/model/mode.rs b/cosmic-theme/src/model/mode.rs index d9a9b14..b2ad99f 100644 --- a/cosmic-theme/src/model/mode.rs +++ b/cosmic-theme/src/model/mode.rs @@ -35,11 +35,6 @@ impl ThemeMode { 1 } - /// Set auto-switch from light to dark mode - pub fn set_auto_switch(config: &Config, value: bool) -> Result<(), cosmic_config::Error> { - config.set("auto_switch", value) - } - /// Get the config for the theme mode pub fn config() -> Result { Config::new(THEME_MODE_ID, Self::version())