Skip to main content

Crate rcman

Crate rcman 

Source
Expand description

§rcman - Rust Config Manager

A generic, framework-agnostic Rust library for managing application settings with backup/restore, sub-settings, and automatic secret storage.

§Features

  • Settings Management: Load, save, and reset settings with schema metadata
  • Secret Settings: Mark settings with .secret() to auto-store in OS keychain (requires keychain or encrypted-file feature)
  • Sub-Settings: Per-entity configuration files (e.g., one file per “remote”)
  • Backup & Restore: Create and restore encrypted backups with AES-256
  • Profiles: Named configurations for switching between different setups (e.g., “work”, “home”)
  • Schema Validation: Regex patterns, numeric ranges, and option constraints
  • Performance: In-memory caching for fast access

§Quick Start

use rcman::{SettingsConfig, SettingsManager, SubSettingsConfig};

let manager = SettingsManager::builder("my-app", "1.0.0")
    .with_config_dir("~/.config/my-app")
    .with_credentials()  // Enable automatic secret storage
    .with_sub_settings(SubSettingsConfig::new("remotes"))
    .with_schema::<MySettings>()
    .build()
    .unwrap();

§Defining Settings Schema

use rcman::{settings, SettingsSchema, SettingMetadata, opt};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Default, Serialize, Deserialize)]
struct MySettings {
    theme: String,
    font_size: f64,
}

impl SettingsSchema for MySettings {
    fn get_metadata() -> HashMap<String, SettingMetadata> {
        settings! {
            "ui.theme" => SettingMetadata::select("dark", vec![
                opt("light", "Light"),
                opt("dark", "Dark"),
            ])
            .meta_str("label", "Theme")
            .meta_str("category", "appearance"),

            "ui.font_size" => SettingMetadata::number(14.0)
                .min(8.0).max(32.0).step(1.0)
                .meta_str("label", "Font Size"),

            "logging.output" => SettingMetadata::text("/var/log/app.log")
                .meta_str("label", "Log File")
                .meta_str("description", "Path to the log output file")
                .meta_str("input_type", "file"),

            "api.key" => SettingMetadata::text("")
                .meta_str("label", "API Key")
                .meta_str("input_type", "password")
                .secret(),  // Auto-stored in OS keychain!
        }
    }
}

§Default Value Behavior

When you save a setting that equals its default value, rcman removes it from storage to keep files minimal. This applies to both regular settings and secrets:

  • Regular settings: Removed from settings file
  • Secret settings: Removed from keychain

This means:

  • Settings files only contain user customizations
  • Changing defaults in code auto-applies to users who haven’t customized
  • Using reset_setting() removes the key from storage

§Sub-Settings (Per-Entity Config)

use rcman::{SettingsManager, SubSettingsConfig};
use serde_json::json;

// Register sub-settings via builder
let manager = SettingsManager::builder("my-app", "1.0.0")
    .with_sub_settings(SubSettingsConfig::new("remotes"))  // Multi-file mode
    .with_sub_settings(SubSettingsConfig::singlefile("backends"))  // Single-file mode
    .with_schema::<MySettings>()
    .build()?;

// Access sub-settings
let remotes = manager.sub_settings("remotes")?;
remotes.set("gdrive", &json!({"type": "drive"}))?;

§Profiles (Named Configurations)

rcman supports creating multiple profiles (e.g., “default”, “work”, “home”) and switching between them. Profiles are supported for both main settings and sub-settings.

use rcman::{SettingsManager, SubSettingsConfig};

let manager = SettingsManager::builder("my-app", "1.0.0")
    .with_profiles() // Enable profiles for main settings
    .with_sub_settings(SubSettingsConfig::new("remotes").with_profiles()) // Enable for sub-settings
    .with_schema::<MySettings>()
    .build()?;

// Create and switch profiles
manager.create_profile("work")?;
manager.switch_profile("work")?;

// Sub-settings automatically use the active profile
let remotes = manager.sub_settings("remotes")?;
// This will save to .../remotes/profiles/work/gdrive.<ext>
remotes.set("gdrive", &serde_json::json!({"type": "drive"}))?;

§Backup & Restore

use rcman::{SettingsManager, SettingsConfig, BackupOptions, RestoreOptions};

let config = SettingsConfig::builder("my-app", "1.0.0")
    .with_schema::<MySettings>()
    .build();
let manager = SettingsManager::new(config)?;

// Create encrypted backup using builder pattern
let path = manager.backup()
    .create(&BackupOptions::new()
        .output_dir("backups/")
        .password("secret")
        .note("Weekly backup"))?;

// Analyze a backup before restoring (inspect contents, check if encrypted)
let analysis = manager.backup().analyze(&path)?;
println!("Encrypted: {}", analysis.requires_password);
println!("Valid: {}", analysis.is_valid);
println!("App version: {}", analysis.manifest.backup.app_version);

// Restore from backup
manager.backup()
    .restore(&RestoreOptions::from_path(&path)
        .password("secret")
        .overwrite(true))?;

§Credentials

Note: CredentialManager is only available when the keychain or encrypted-file feature is enabled.

#[cfg(feature = "keychain")]
{
    use rcman::CredentialManager;

    let creds = CredentialManager::new("my-app");
    creds.store("api-key", "secret-value").unwrap();
    let key = creds.get("api-key").unwrap();
}

§Import Patterns

All public types are re-exported at the crate root for convenience:

// Recommended: flat imports
use rcman::{SettingsManager, JsonStorage, SettingMetadata};

// Alternative: prelude for common types
use rcman::prelude::*;

Re-exports§

pub use backup::BackupInfo;
pub use backup::BackupManager;
pub use backup::BackupOptions;
pub use backup::ExportType;
pub use backup::ProfileEntry;
pub use backup::ProgressCallback;
pub use backup::RestoreOptions;
pub use backup::RestoreResult;
pub use backup::SubSettingsManifestEntry;

Modules§

backup
Backup and restore module for rcman
meta
Core configuration types and traits for settings management. Internal metadata keys used by the library itself.
prelude
Prelude module for convenient glob imports.

Macros§

settings
Macro for building settings metadata HashMap more cleanly

Structs§

CredentialManager
Credential manager for secure secret storage. Requires keychain or encrypted-file feature. Credential manager with configurable backend and fallback
DefaultEnvSource
Core configuration types and traits for settings management. Default implementation using std::env
DocsConfig
Documentation generation utilities. Configuration for docs generation
EncryptedFileBackend
Encrypted file backend (requires encrypted-file feature). Encrypted file backend using AES-256-GCM
EventManager
Event system for reactive settings changes. Manages event listeners for settings changes
JsonStorage
JSON storage backend (default). JSON storage backend (default)
KeychainBackend
Keychain backend (requires keychain feature). OS Keychain backend for secure credential storage
MemoryBackend
Credential storage backend trait and types. In-memory credential storage (not persisted)
NumberConstraints
Core configuration types and traits for settings management. Constraints for Number type settings
ProfileManager
Manages profiles for a specific target (settings or sub-settings)
ProfileManifest
Profile manifest stored in .profiles.json
SettingConstraints
Core configuration types and traits for settings management. Type-specific constraints
SettingMetadata
Core configuration types and traits for settings management. Metadata for a single setting
SettingOption
Core configuration types and traits for settings management. Option for Select type settings
SettingsConfig
Core configuration types and traits for settings management. Configuration for initializing the SettingsManager
SettingsConfigBuilder
Core configuration types and traits for settings management. Builder for creating SettingsConfig with a fluent API.
SettingsManager
Main settings manager and builder. Main settings manager for loading, saving, and managing application settings.
SettingsManagerBuilder
Main settings manager and builder. Builder for creating a SettingsManager with a fluent API.
SubSettings
Sub-settings for per-entity configuration. Handler for a single sub-settings type
SubSettingsConfig
Sub-settings for per-entity configuration. Configuration for a sub-settings type.
TextConstraints
Core configuration types and traits for settings management. Constraints for Text type settings
TomlStorage
TOML storage backend (requires toml feature). TOML storage backend

Enums§

CacheStrategy
Cache strategy for settings components. Cache strategy for settings components
Error
Error types for the library. Main error type for rcman library
ProfileEvent
Events emitted when profiles change
ProfileMigrator
Migration strategy
SecretBackupPolicy
Credential storage backend trait and types.
SecretStorage
Credential storage backend trait and types. Where to store secret values
SettingType
Core configuration types and traits for settings management. Type of setting for UI rendering
SubSettingsAction
Sub-settings for per-entity configuration. Action type for change callbacks
SubSettingsMode
Sub-settings for per-entity configuration. Mode of storage for sub-settings

Constants§

DEFAULT_PROFILE
Default profile name used when migrating or initializing
PROFILES_DIR
Directory name containing profile subdirectories

Traits§

CredentialBackend
Credential storage backend trait and types. Trait for credential storage backends
EnvSource
Core configuration types and traits for settings management. Trait for retrieving environment variables
SettingsSchema
Core configuration types and traits for settings management. Trait for types that define a settings schema
StorageBackend
JSON storage backend (default). Trait for storage backend implementations

Functions§

generate_docs
Documentation generation utilities. Generate markdown documentation from a settings schema
generate_docs_from_metadata
Documentation generation utilities. Generate docs from raw metadata (useful when schema isn’t available)
migrate
Execute migration if needed
opt
Core configuration types and traits for settings management. Shorthand for creating a SettingOption
validate_profile_name
Validate a profile name

Type Aliases§

Result
Error types for the library. Result type alias for rcman operations

Derive Macros§

DeriveSettingsSchema
Derive macro for auto-generating SettingsSchema implementations.