1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! # 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
//! - **Hot Reload**: Optional file watcher runtime for external settings updates (requires `hot-reload` feature)
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use rcman::{SettingsConfig, SettingsManager, SubSettingsConfig};
//!
//! # use rcman::*;
//! # use serde::{Serialize, Deserialize};
//! # use std::collections::HashMap;
//! # #[derive(Default, Serialize, Deserialize)] struct MySettings;
//! # impl SettingsSchema for MySettings { fn get_metadata() -> HashMap<String, SettingMetadata> { HashMap::new() } }
//! 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
//!
//! ```rust,no_run
//! 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)
//!
//! ```rust,no_run
//! use rcman::{SettingsManager, SubSettingsConfig};
//! use serde_json::json;
//!
//! # fn example() -> rcman::Result<()> {
//! # use rcman::*;
//! # use serde::{Serialize, Deserialize};
//! # use std::collections::HashMap;
//! # #[derive(Default, Serialize, Deserialize)] struct MySettings;
//! # impl SettingsSchema for MySettings { fn get_metadata() -> HashMap<String, SettingMetadata> { HashMap::new() } }
//! // 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"}))?;
//! # Ok(())
//! # }
//! ```
//!
//! ## 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.
//!
//! ```rust,no_run
//! use rcman::{SettingsManager, SubSettingsConfig};
//!
//! # fn example() -> rcman::Result<()> {
//! # #[cfg(feature = "profiles")]
//! # {
//! # use rcman::*;
//! # use serde::{Serialize, Deserialize};
//! # use std::collections::HashMap;
//! # #[derive(Default, Serialize, Deserialize)] struct MySettings;
//! # impl SettingsSchema for MySettings { fn get_metadata() -> HashMap<String, SettingMetadata> { HashMap::new() } }
//! 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"}))?;
//! # }
//! # Ok(())
//! # }
//! ```
//!
//! ## Backup & Restore
//!
//! ```rust,no_run
//! use rcman::{SettingsManager, SettingsConfig, BackupOptions, RestoreOptions};
//!
//! # fn example() -> rcman::Result<()> {
//! # use rcman::*;
//! # use serde::{Serialize, Deserialize};
//! # use std::collections::HashMap;
//! # #[derive(Default, Serialize, Deserialize)] struct MySettings;
//! # impl SettingsSchema for MySettings { fn get_metadata() -> HashMap<String, SettingMetadata> { HashMap::new() } }
//! 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))?;
//! # Ok(())
//! # }
//! ```
//!
//! Secret export behavior:
//! - Secret keys declared in your main settings schema are exported under main settings structure.
//! - `SecretBackupPolicy::Exclude` redacts secrets.
//! - `SecretBackupPolicy::EncryptedOnly` includes secrets only when a backup password is provided; otherwise it behaves like redact.
//! - `SecretBackupPolicy::Include` always includes secrets.
//! - When credentials are enabled, restore rehydrates included main-schema secrets back into credential storage and redacts them in restored settings files.
//!
//! ## Credentials
//!
//! **Note**: `CredentialManager` is only available when the `keychain` or `encrypted-file` feature is enabled.
//!
//! ```rust,no_run
//! #[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:
//!
//! ```rust,ignore
//! // Recommended: flat imports
//! use rcman::{SettingsManager, JsonStorage, SettingMetadata};
//!
//! // Alternative: prelude for common types
//! use rcman::prelude::*;
//! ```
//!
//! ## Hot Reload (Feature-Gated)
//!
//! Enable with:
//! `rcman = { version = "0.1", features = ["hot-reload"] }`
//!
//! ```rust,no_run
//! use rcman::{HotReloadConfig, HotReloadRuntime, SettingsManager};
//! use std::sync::Arc;
//!
//! # fn demo() -> rcman::Result<()> {
//! let manager = Arc::new(
//! SettingsManager::builder("my-app", "1.0.0")
//! .with_hot_reload()
//! .build()?,
//! );
//!
//! let mut runtime = HotReloadRuntime::start(
//! Arc::clone(&manager),
//! HotReloadConfig::default(),
//! |event| {
//! println!("hot-reload event: {event:?}");
//! },
//! )?;
//!
//! // ... app loop
//! runtime.stop();
//! # Ok(())
//! # }
//! ```
//!
//! Scope note:
//! - Hot reload currently watches only the active main settings file.
//! - Sub-settings (single-file and multi-file categories) are not watched.
// =============================================================================
// INTERNAL MODULES (private implementation details)
// =============================================================================
// Core modules
// Feature-gated modules
// =============================================================================
// PUBLIC API RE-EXPORTS
// =============================================================================
// -----------------------------------------------------------------------------
// Core Types (always available)
// -----------------------------------------------------------------------------
/// Core configuration types and traits for settings management.
pub use ;
pub use ;
/// Documentation generation utilities.
pub use ;
/// Error types for the library.
pub use ;
/// Re-exported `serde_json` for macro-generated integrations.
pub use serde_json;
/// Event system for reactive settings changes.
pub use EventManager;
/// Main settings manager and builder.
pub use ;
pub use ;
/// Sub-settings for per-entity configuration.
pub use ;
// -----------------------------------------------------------------------------
// Storage Backends
// -----------------------------------------------------------------------------
/// JSON storage backend (default).
pub use ;
/// Convenience type alias for the most common configuration:
/// `SettingsManager` using `JsonStorage`.
pub type JsonManager<S> = ;
/// TOML storage backend (requires `toml` feature).
pub use TomlStorage;
/// YAML storage backend (requires `yaml` feature).
pub use YamlStorage;
// -----------------------------------------------------------------------------
// Cache
// -----------------------------------------------------------------------------
/// Cache strategy for settings components.
pub use CacheStrategy;
// -----------------------------------------------------------------------------
// Backup & Restore (requires backup feature)
// -----------------------------------------------------------------------------
pub use ;
// -----------------------------------------------------------------------------
// Profiles (requires profiles feature)
// -----------------------------------------------------------------------------
pub use ;
// -----------------------------------------------------------------------------
// Credentials
// -----------------------------------------------------------------------------
/// Credential storage backend trait and types.
pub use ;
/// Keychain backend (requires `keychain` feature).
pub use KeychainBackend;
/// Encrypted file backend (requires `encrypted-file` feature).
pub use EncryptedFileBackend;
/// Credential manager for secure secret storage.
/// Requires `keychain` or `encrypted-file` feature.
pub use CredentialManager;
// -----------------------------------------------------------------------------
// Derive Macro (requires derive feature)
// -----------------------------------------------------------------------------
/// Derive macro for auto-generating `SettingsSchema` implementations.
///
/// Use this to reduce boilerplate when defining settings structs.
///
/// The derive also generates:
/// - Snapshot accessors on the settings struct (`ui_theme()`, `set_ui_theme(...)`)
/// - A manager extension trait named `<SchemaName>ManagerAccessors`
/// for typed manager reads/writes (`manager.ui_theme()?`, `manager.set_ui_theme(...)`)
///
/// # Example
///
/// ```rust,ignore
/// use rcman::DeriveSettingsSchema;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Default, Serialize, Deserialize, DeriveSettingsSchema)]
/// #[schema(category = "general")]
/// struct GeneralSettings {
/// #[setting(label = "Enable Tray")]
/// tray_enabled: bool,
/// }
/// ```
pub use SettingsSchema as DeriveSettingsSchema;
// =============================================================================
// PRELUDE MODULE (convenient glob import)
// =============================================================================
/// Prelude module for convenient glob imports.
///
/// Import all commonly-used types with a single line:
///
/// ```rust
/// use rcman::prelude::*;
/// ```
///
/// This includes the core types needed for most use cases:
/// - `SettingsManager`, `SettingsConfig`, `SettingsSchema`
/// - `SettingMetadata`, `SettingOption`, `opt`
/// - `SubSettingsConfig`
/// - `JsonStorage`, `StorageBackend`
/// - `Error`, `Result`
///
/// Feature-gated types are also included when their features are enabled.