pub struct SettingsManager<S: StorageBackend = JsonStorage, Schema: SettingsSchema = ()> { /* private fields */ }Expand description
Main settings manager and builder. Main settings manager for loading, saving, and managing application settings.
The SettingsManager provides a complete solution for application configuration:
- Load/Save Settings: Read and write settings with schema validation
- Sub-Settings: Manage per-entity configuration files (e.g., per-remote configs)
- Change Events: Register callbacks for setting changes
- Backup/Restore: Create and restore encrypted backups
- Caching: In-memory caching for fast access
- Secret Settings: Automatic keychain storage for sensitive values
§Example
use rcman::{SettingsManager, SettingsConfig};
// Create with builder
let config = SettingsConfig::builder("my-app", "1.0.0")
.with_config_dir("~/.config/my-app")
.with_credentials() // Enable secret storage
.build();
let manager = SettingsManager::new(config).unwrap();§Type Parameters
Schema: The settings schema type (defaults to()for dynamic usage).
Implementations§
Source§impl<S: StorageBackend + 'static, Schema: SettingsSchema> SettingsManager<S, Schema>
impl<S: StorageBackend + 'static, Schema: SettingsSchema> SettingsManager<S, Schema>
Sourcepub fn new(config: SettingsConfig<S, Schema>) -> Result<Self>
pub fn new(config: SettingsConfig<S, Schema>) -> Result<Self>
Create a new settings manager with the given configuration.
This will create the config directory if it doesn’t exist.
§Arguments
config- Configuration specifying paths, app info, and storage backend
§Errors
Returns an error if the config directory cannot be created.
§Example
use rcman::{SettingsManager, SettingsConfig};
let config = SettingsConfig::builder("my-app", "1.0.0").build();
let manager = SettingsManager::new(config)?;Sourcepub fn config(&self) -> &SettingsConfig<S, Schema>
pub fn config(&self) -> &SettingsConfig<S, Schema>
Get the configuration
Sourcepub fn events(&self) -> &Arc<EventManager>
pub fn events(&self) -> &Arc<EventManager>
Get the event manager for registering change listeners and validators
Callback semantics:
save_setting()emits callbacks only when the effective value changes.reset_setting()delegates tosave_setting(), so unchanged resets emit nothing.reset_all()emits one callback per changed key (no callbacks for already-default values).- With profiles enabled,
switch_profile()emits callbacks for keys whose effective values differ between the old and new profiles.
§Example
// Watch all changes
manager.events().on_change(|key, old, new| {
println!("Changed {}: {:?} -> {:?}", key, old, new);
});
// Watch specific key
manager.events().watch("ui.theme", |key, _old, new| {
println!("Theme changed to: {:?}", new);
});
// Add validator
manager.events().add_validator("network.port", |v: &Value| {
if v.as_i64().map(|n| n > 0 && n <= 65535).unwrap_or(false) {
Ok(())
} else {
Err("Invalid port".into())
}
});Sourcepub fn credentials(&self) -> Option<&CredentialManager>
pub fn credentials(&self) -> Option<&CredentialManager>
Get reference to credential manager (if configured)
Source§impl SettingsManager
impl SettingsManager
Sourcepub fn builder(
app_name: impl Into<String>,
app_version: impl Into<String>,
) -> SettingsManagerBuilder
pub fn builder( app_name: impl Into<String>, app_version: impl Into<String>, ) -> SettingsManagerBuilder
Create a builder for SettingsManager with a fluent API.
This is the recommended way to create a SettingsManager.
§Example
use rcman::{SettingsManager, SubSettingsConfig};
let manager = SettingsManager::builder("my-app", "1.0.0")
.with_config_dir("~/.config/my-app")
.with_credentials()
.with_sub_settings(SubSettingsConfig::new("remotes"))
.build()
.unwrap();Source§impl<S: StorageBackend + 'static, Schema: SettingsSchema> SettingsManager<S, Schema>
impl<S: StorageBackend + 'static, Schema: SettingsSchema> SettingsManager<S, Schema>
Sourcepub fn invalidate_cache(&self)
pub fn invalidate_cache(&self)
Invalidate the settings cache
Call this if the settings file was modified externally.
Sourcepub fn save_setting(
&self,
category: &str,
key: &str,
value: &Value,
) -> Result<()>
pub fn save_setting( &self, category: &str, key: &str, value: &Value, ) -> Result<()>
Save a single setting value.
This method validates the value, updates the cache, and writes to disk.
If the setting is marked as secret: true and credentials are enabled,
the value will be stored in the OS keychain instead of the settings file.
If the value equals the default, it will be removed from storage.
If the value is unchanged, no I/O occurs.
§Arguments
category- Category name (e.g., “ui”, “general”)key- Setting key within the category (e.g., “theme”, “language”)value- New value as JSON
§Errors
Returns an error if:
- Validation fails
- Saving to storage fails
- Parsing the existing settings fails
Sourcepub fn reset_all(&self) -> Result<()>
pub fn reset_all(&self) -> Result<()>
Reset all settings to defaults
§Errors
Returns an error if writing to storage fails or credential clearing fails.
Sourcepub fn ensure_cache_populated(&self) -> Result<()>
pub fn ensure_cache_populated(&self) -> Result<()>
Ensure the settings cache is populated
This method is thread-safe and safe to call multiple times. It uses double-checked locking to avoid unnecessary locks.
§Errors
Returns an error if the settings cannot be loaded from disk.
Source§impl<S: StorageBackend + 'static, Schema: SettingsSchema> SettingsManager<S, Schema>
impl<S: StorageBackend + 'static, Schema: SettingsSchema> SettingsManager<S, Schema>
Sourcepub fn metadata(&self) -> Result<HashMap<String, SettingMetadata>>
pub fn metadata(&self) -> Result<HashMap<String, SettingMetadata>>
Get all setting metadata with current values populated.
Returns a HashMap of all settings with their metadata (type, label, default, current value).
Useful for rendering settings UI.
Returns metadata map with current values populated. Uses in-memory cache when available.
§Errors
Returns an error if:
- Storage read fails
- Data is corrupted
Sourcepub fn get<T>(&self, key: &str) -> Result<T>where
T: DeserializeOwned,
pub fn get<T>(&self, key: &str) -> Result<T>where
T: DeserializeOwned,
Get a single setting value by key path.
§Type Parameters
T- The type to deserialize the value into
§Arguments
key- Setting key in “category.name” format (e.g., “general.restrict”)
§Errors
Returns an error if:
- The setting doesn’t exist (and no default)
- The value cannot be deserialized to type
T - Storage read fails
Sourcepub fn get_all(&self) -> Result<Schema>
pub fn get_all(&self) -> Result<Schema>
Get merged settings struct with caching.
§Errors
Returns an error if settings cannot be read or parsed.
Sourcepub fn register_sub_settings(&self, config: SubSettingsConfig) -> Result<()>
pub fn register_sub_settings(&self, config: SubSettingsConfig) -> Result<()>
Register a sub-settings type for per-entity configuration.
Sub-settings allow you to manage separate config files for each entity (e.g., one file per remote, per profile, etc.).
§Errors
Returns an error if the sub-settings handler cannot be initialized (e.g. invalid path).
Sourcepub fn sub_settings(&self, name: &str) -> Result<Arc<SubSettings<S>>>
pub fn sub_settings(&self, name: &str) -> Result<Arc<SubSettings<S>>>
Get a registered sub-settings handler.
Returns the handler for the specified sub-settings type, which can be used to read, write, and manage individual entries.
§Arguments
name- The name of the sub-settings type to get
§Errors
Returns Error::SubSettingsNotFound if the sub-settings type is not registered.
Sourcepub fn has_sub_settings(&self, name: &str) -> bool
pub fn has_sub_settings(&self, name: &str) -> bool
Check if a sub-settings type exists
Sourcepub fn sub_settings_types(&self) -> Vec<String>
pub fn sub_settings_types(&self) -> Vec<String>
List all registered sub-settings types
Sourcepub fn register_external_provider(
&self,
provider: Box<dyn ExternalConfigProvider>,
)
pub fn register_external_provider( &self, provider: Box<dyn ExternalConfigProvider>, )
Register an external config provider for backups.
This allows dynamic registration of external files to be included in backups.
Sourcepub fn backup(&self) -> BackupManager<'_, S, Schema>
pub fn backup(&self) -> BackupManager<'_, S, Schema>
Get the backup manager
Sourcepub fn external_configs(&self) -> &[ExternalConfig]
pub fn external_configs(&self) -> &[ExternalConfig]
Get all registered external configs
Returns the external config files that were registered via
SettingsConfig::builder().with_external_config(...).
Sourcepub fn get_export_categories(&self) -> Vec<ExportCategory>
pub fn get_export_categories(&self) -> Vec<ExportCategory>
Get all export categories for backup UI
Returns a list of all exportable categories:
- Settings (main settings.json)
- Sub-settings (each registered sub-settings type)
- External configs (each registered external file)
Source§impl<S: StorageBackend + 'static, Schema: SettingsSchema> SettingsManager<S, Schema>
impl<S: StorageBackend + 'static, Schema: SettingsSchema> SettingsManager<S, Schema>
Sourcepub fn is_profiles_enabled(&self) -> bool
pub fn is_profiles_enabled(&self) -> bool
Check if profiles are enabled for main settings
Sourcepub fn profiles(&self) -> Option<&ProfileManager<S>>
pub fn profiles(&self) -> Option<&ProfileManager<S>>
Get the profile manager for main settings
Returns None if profiles are not enabled for main settings.
Sourcepub fn switch_profile(&self, name: &str) -> Result<()>
pub fn switch_profile(&self, name: &str) -> Result<()>
Switch to a different profile
This switches the active profile for main settings and updates internal paths. All subsequent operations will use the new profile’s settings.
If change listeners are registered via events().on_change(...), this emits
callbacks for keys whose effective values differ between the previous and
new active profile.
§Arguments
name- The name of the profile to switch to
§Errors
Returns an error if:
- Profiles are not enabled for this manager
- The profile does not exist
- The profile switch fails (e.g. IO error)
Sourcepub fn create_profile(&self, name: &str) -> Result<()>
pub fn create_profile(&self, name: &str) -> Result<()>
Sourcepub fn list_profiles(&self) -> Result<Vec<String>>
pub fn list_profiles(&self) -> Result<Vec<String>>
List all available profiles
§Errors
Returns an error if profiles are not enabled or reading the profile list fails.
Sourcepub fn active_profile(&self) -> Result<String>
pub fn active_profile(&self) -> Result<String>
Get the active profile name
§Errors
Returns an error if profiles are not enabled or determining the active profile fails.