llm-config-cli 0.5.0

Command-line interface for LLM Config Manager with interactive prompts, colored output, and comprehensive configuration management
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
//! LLM Config Manager CLI

use clap::{Parser, Subcommand, ValueEnum};
use colored::Colorize;
use llm_config_core::{ConfigManager, ConfigValue, Environment};
use llm_config_crypto::{Algorithm, SecretKey};
use std::path::PathBuf;

#[derive(Parser)]
#[command(name = "llm-config")]
#[command(about = "LLM Configuration Manager - Secure configuration and secrets management", long_about = None)]
#[command(version)]
struct Cli {
    /// Storage directory path
    #[arg(short, long, default_value = ".llm-config")]
    storage: PathBuf,

    /// Encryption key (base64 encoded)
    #[arg(short = 'k', long, env = "LLM_CONFIG_KEY")]
    encryption_key: Option<String>,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Get a configuration value
    Get {
        /// Namespace (e.g., "org/project/service")
        namespace: String,

        /// Configuration key
        key: String,

        /// Environment
        #[arg(short, long, value_enum, default_value = "development")]
        env: Env,

        /// Apply environment overrides
        #[arg(short = 'o', long)]
        with_overrides: bool,
    },

    /// Set a configuration value
    Set {
        /// Namespace (e.g., "org/project/service")
        namespace: String,

        /// Configuration key
        key: String,

        /// Configuration value
        value: String,

        /// Environment
        #[arg(short, long, value_enum, default_value = "development")]
        env: Env,

        /// User performing the operation
        #[arg(short, long, default_value = "cli-user")]
        user: String,

        /// Store as a secret (encrypted)
        #[arg(short, long)]
        secret: bool,
    },

    /// List configurations in a namespace
    List {
        /// Namespace (e.g., "org/project/service")
        namespace: String,

        /// Environment
        #[arg(short, long, value_enum, default_value = "development")]
        env: Env,

        /// Output format
        #[arg(short, long, value_enum, default_value = "table")]
        format: OutputFormat,
    },

    /// Delete a configuration
    Delete {
        /// Namespace
        namespace: String,

        /// Configuration key
        key: String,

        /// Environment
        #[arg(short, long, value_enum, default_value = "development")]
        env: Env,

        /// Skip confirmation
        #[arg(short = 'y', long)]
        yes: bool,
    },

    /// Show version history
    History {
        /// Namespace
        namespace: String,

        /// Configuration key
        key: String,

        /// Environment
        #[arg(short, long, value_enum, default_value = "development")]
        env: Env,
    },

    /// Rollback to a specific version
    Rollback {
        /// Namespace
        namespace: String,

        /// Configuration key
        key: String,

        /// Target version number
        version: u64,

        /// Environment
        #[arg(short, long, value_enum, default_value = "development")]
        env: Env,
    },

    /// Export all configurations
    Export {
        /// Export directory path
        path: PathBuf,
    },

    /// Generate a new encryption key
    Keygen,
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
enum Env {
    Base,
    Dev,
    Development,
    Staging,
    Stage,
    Prod,
    Production,
    Edge,
}

impl From<Env> for Environment {
    fn from(env: Env) -> Self {
        match env {
            Env::Base => Environment::Base,
            Env::Dev | Env::Development => Environment::Development,
            Env::Staging | Env::Stage => Environment::Staging,
            Env::Prod | Env::Production => Environment::Production,
            Env::Edge => Environment::Edge,
        }
    }
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
enum OutputFormat {
    Table,
    Json,
    Yaml,
}

fn main() {
    // Initialize tracing
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive(tracing::Level::INFO.into()),
        )
        .init();

    let cli = Cli::parse();

    if let Err(e) = run(cli) {
        eprintln!("{} {}", "Error:".red().bold(), e);
        std::process::exit(1);
    }
}

fn run(cli: Cli) -> anyhow::Result<()> {
    // Create manager
    let mut manager = ConfigManager::new(&cli.storage)?;

    // Set encryption key if provided
    let has_key = cli.encryption_key.is_some();
    if let Some(key_str) = cli.encryption_key {
        let key = SecretKey::from_base64(Algorithm::Aes256Gcm, &key_str)?;
        manager = manager.with_encryption_key(key);
    }

    match cli.command {
        Commands::Get {
            namespace,
            key,
            env,
            with_overrides,
        } => {
            let env: Environment = env.into();

            if with_overrides {
                if let Some(value) = manager.get_with_overrides(&namespace, &key, env)? {
                    println!("{}", format_value(&value));
                } else {
                    println!("{}", "Configuration not found".yellow());
                }
            } else {
                if let Some(entry) = manager.get(&namespace, &key, env)? {
                    println!("{}", "Configuration:".green().bold());
                    println!("  Namespace: {}", entry.namespace);
                    println!("  Key: {}", entry.key);
                    println!("  Environment: {}", entry.environment);
                    println!("  Value: {}", format_value(&entry.value));
                    println!("  Version: {}", entry.version);
                    println!("  Updated: {}", entry.metadata.updated_at);
                    println!("  Updated by: {}", entry.metadata.updated_by);
                } else {
                    println!("{}", "Configuration not found".yellow());
                }
            }
        }

        Commands::Set {
            namespace,
            key,
            value,
            env,
            user,
            secret,
        } => {
            let env: Environment = env.into();

            let entry = if secret {
                if !has_key {
                    anyhow::bail!("Encryption key required for secrets. Set --encryption-key or LLM_CONFIG_KEY environment variable.");
                }
                manager.set_secret(&namespace, &key, value.as_bytes(), env, &user)?
            } else {
                let config_value = parse_value(&value)?;
                manager.set(&namespace, &key, config_value, env, &user)?
            };

            println!("{}", "Configuration saved successfully!".green().bold());
            println!("  Version: {}", entry.version);
            println!("  ID: {}", entry.id);
        }

        Commands::List {
            namespace,
            env,
            format,
        } => {
            let env: Environment = env.into();
            let entries = manager.list(&namespace, env)?;

            if entries.is_empty() {
                println!("{}", "No configurations found".yellow());
                return Ok(());
            }

            match format {
                OutputFormat::Table => {
                    println!("{}", format!("Configurations in {} ({})", namespace, env).green().bold());
                    println!();
                    for entry in entries {
                        println!("  {} {} = {}", "".blue(), entry.key.bold(), format_value(&entry.value));
                        println!("    Version: {} | Updated: {} by {}",
                            entry.version,
                            entry.metadata.updated_at.format("%Y-%m-%d %H:%M:%S"),
                            entry.metadata.updated_by
                        );
                        println!();
                    }
                }
                OutputFormat::Json => {
                    println!("{}", serde_json::to_string_pretty(&entries)?);
                }
                OutputFormat::Yaml => {
                    println!("{}", serde_yaml::to_string(&entries)?);
                }
            }
        }

        Commands::Delete {
            namespace,
            key,
            env,
            yes,
        } => {
            let env: Environment = env.into();

            if !yes {
                print!("Delete configuration {}:{} in {} environment? [y/N] ", namespace, key, env);
                use std::io::{self, Write};
                io::stdout().flush()?;

                let mut input = String::new();
                io::stdin().read_line(&mut input)?;

                if !input.trim().eq_ignore_ascii_case("y") {
                    println!("Cancelled.");
                    return Ok(());
                }
            }

            let deleted = manager.delete(&namespace, &key, env)?;

            if deleted {
                println!("{}", "Configuration deleted successfully!".green().bold());
            } else {
                println!("{}", "Configuration not found".yellow());
            }
        }

        Commands::History {
            namespace,
            key,
            env,
        } => {
            let env: Environment = env.into();
            let history = manager.get_history(&namespace, &key, env)?;

            if history.is_empty() {
                println!("{}", "No version history found".yellow());
                return Ok(());
            }

            println!("{}", format!("Version history for {}:{}", namespace, key).green().bold());
            println!();

            for version in history {
                println!("  {} Version {}", "".blue(), version.version.to_string().bold());
                println!("    Value: {}", format_value(&version.value));
                println!("    Created: {} by {}", version.created_at.format("%Y-%m-%d %H:%M:%S"), version.created_by);
                if let Some(desc) = version.change_description {
                    println!("    Note: {}", desc);
                }
                println!();
            }
        }

        Commands::Rollback {
            namespace,
            key,
            version,
            env,
        } => {
            let env: Environment = env.into();

            if let Some(entry) = manager.rollback(&namespace, &key, env, version)? {
                println!("{}", "Rollback successful!".green().bold());
                println!("  New version: {}", entry.version);
                println!("  Value: {}", format_value(&entry.value));
            } else {
                println!("{}", format!("Version {} not found", version).yellow());
            }
        }

        Commands::Export { path } => {
            let count = manager.export_all(&path)?;
            println!("{}", format!("Exported {} configurations to {}", count, path.display()).green().bold());
        }

        Commands::Keygen => {
            let key = SecretKey::generate(Algorithm::Aes256Gcm)?;
            println!("{}", "Generated encryption key:".green().bold());
            println!();
            println!("{}", key.to_base64());
            println!();
            println!("Set this key using:");
            println!("  {} export LLM_CONFIG_KEY=\"{}\"", "".blue(), key.to_base64());
            println!("  {} llm-config --encryption-key <key> ...", "".blue());
        }
    }

    Ok(())
}

fn parse_value(s: &str) -> anyhow::Result<ConfigValue> {
    // Try to parse as JSON first
    if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(s) {
        return Ok(match json_value {
            serde_json::Value::String(s) => ConfigValue::String(s),
            serde_json::Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    ConfigValue::Integer(i)
                } else if let Some(f) = n.as_f64() {
                    ConfigValue::Float(f)
                } else {
                    ConfigValue::String(s.to_string())
                }
            }
            serde_json::Value::Bool(b) => ConfigValue::Boolean(b),
            serde_json::Value::Array(arr) => {
                let values: Result<Vec<_>, _> = arr
                    .iter()
                    .map(|v| parse_value(&v.to_string()))
                    .collect();
                ConfigValue::Array(values?)
            }
            serde_json::Value::Object(_) => {
                // For objects, store as JSON string
                ConfigValue::String(s.to_string())
            }
            serde_json::Value::Null => ConfigValue::String(String::new()),
        });
    }

    // Otherwise treat as string
    Ok(ConfigValue::String(s.to_string()))
}

fn format_value(value: &ConfigValue) -> String {
    match value {
        ConfigValue::String(s) => s.clone(),
        ConfigValue::Integer(i) => i.to_string(),
        ConfigValue::Float(f) => f.to_string(),
        ConfigValue::Boolean(b) => b.to_string(),
        ConfigValue::Array(arr) => format!("[{}]", arr.iter().map(format_value).collect::<Vec<_>>().join(", ")),
        ConfigValue::Object(_) => "<object>".to_string(),
        ConfigValue::Secret(_) => "<encrypted>".yellow().to_string(),
    }
}