Some checks failed
Run Check Script / check (pull_request) Failing after 14s
70 lines
2.3 KiB
Rust
70 lines
2.3 KiB
Rust
//! Example demonstrating configuration prompting with harmony_config
|
|
//!
|
|
//! This example shows how to use `get_or_prompt()` to interactively
|
|
//! ask the user for configuration values when none are found.
|
|
//!
|
|
//! **Note**: This example requires a TTY to work properly since it uses
|
|
//! interactive prompting via `inquire`. Run in a terminal.
|
|
//!
|
|
//! Run with:
|
|
//! - `cargo run --example prompting` - will prompt for values interactively
|
|
//! - If config exists in SQLite, it will be used directly without prompting
|
|
|
|
use std::sync::Arc;
|
|
|
|
use harmony_config::{Config, ConfigManager, EnvSource, PromptSource, SqliteSource};
|
|
use schemars::JsonSchema;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Config)]
|
|
struct UserConfig {
|
|
username: String,
|
|
email: String,
|
|
theme: String,
|
|
}
|
|
|
|
#[tokio::main]
|
|
async fn main() -> anyhow::Result<()> {
|
|
env_logger::init();
|
|
|
|
let sqlite = SqliteSource::default().await?;
|
|
let manager = ConfigManager::new(vec![
|
|
Arc::new(EnvSource),
|
|
Arc::new(sqlite),
|
|
Arc::new(PromptSource::new()),
|
|
]);
|
|
|
|
println!("UserConfig Setup");
|
|
println!("=================\n");
|
|
|
|
println!("Attempting to get UserConfig (env > sqlite > prompt)...\n");
|
|
|
|
match manager.get::<UserConfig>().await {
|
|
Ok(config) => {
|
|
println!("Found existing config:");
|
|
println!(" Username: {}", config.username);
|
|
println!(" Email: {}", config.email);
|
|
println!(" Theme: {}", config.theme);
|
|
println!("\nNo prompting needed - using stored config.");
|
|
}
|
|
Err(harmony_config::ConfigError::NotFound { .. }) => {
|
|
println!("No config found in env or SQLite.");
|
|
println!("Calling get_or_prompt() to interactively request config...\n");
|
|
|
|
let config: UserConfig = manager.get_or_prompt().await?;
|
|
println!("\nConfig received and saved to SQLite:");
|
|
println!(" Username: {}", config.username);
|
|
println!(" Email: {}", config.email);
|
|
println!(" Theme: {}", config.theme);
|
|
}
|
|
Err(e) => {
|
|
println!("Error: {:?}", e);
|
|
}
|
|
}
|
|
|
|
println!("\nConfig is persisted at ~/.local/share/harmony/config/config.db");
|
|
println!("On next run, the stored config will be used without prompting.");
|
|
|
|
Ok(())
|
|
}
|