invoice_cli/commands/
config.rs1use crate::cli::ConfigCmd;
2use crate::config;
3use crate::error::{AppError, Result};
4use crate::output::{print_success, Ctx};
5
6pub fn run(cmd: ConfigCmd, ctx: Ctx) -> Result<()> {
7 match cmd {
8 ConfigCmd::Show => {
9 let cfg = config::load()?;
10 print_success(ctx, &cfg, |c| println!("{:#?}", c));
11 Ok(())
12 }
13 ConfigCmd::Path => {
14 let p = config::config_path()?;
15 print_success(ctx, &p, |p| println!("{}", p.display()));
16 Ok(())
17 }
18 ConfigCmd::Set { key, value } => {
19 let path = config::config_path()?;
21 let existing = if path.exists() {
22 std::fs::read_to_string(&path)?
23 } else {
24 String::new()
25 };
26 let mut doc: toml::Value =
27 toml::from_str(&existing).unwrap_or(toml::Value::Table(Default::default()));
28 if let toml::Value::Table(ref mut t) = doc {
29 t.insert(key.clone(), parse_value(&value));
30 } else {
31 return Err(AppError::Config("config root is not a table".into()));
32 }
33 std::fs::write(&path, toml::to_string_pretty(&doc).unwrap())?;
34 print_success(
35 ctx,
36 &serde_json::json!({"key": key, "value": value}),
37 |_| println!("set {} = {}", key, value),
38 );
39 Ok(())
40 }
41 }
42}
43
44fn parse_value(v: &str) -> toml::Value {
45 if v == "true" {
46 toml::Value::Boolean(true)
47 } else if v == "false" {
48 toml::Value::Boolean(false)
49 } else if let Ok(n) = v.parse::<i64>() {
50 toml::Value::Integer(n)
51 } else {
52 toml::Value::String(v.to_string())
53 }
54}