worktree_io/config/
ops.rs1use anyhow::{Context, Result};
2use std::path::PathBuf;
3
4use super::Config;
5
6impl Config {
7 pub fn path() -> Result<PathBuf> {
8 let home = dirs::home_dir().context("Could not determine home directory")?;
9 Ok(home.join(".config").join("worktree").join("config.toml"))
10 }
11
12 pub fn load() -> Result<Self> {
13 let path = Self::path()?;
14 if !path.exists() {
15 return Ok(Self::default());
16 }
17 let content = std::fs::read_to_string(&path)
19 .with_context(|| format!("Failed to read config from {}", path.display()))?;
20 let config: Self = toml::from_str(&content)
21 .with_context(|| format!("Failed to parse config at {}", path.display()))?;
22 Ok(config)
23 }
25
26 pub fn save(&self) -> Result<()> {
27 let path = Self::path()?;
30 if let Some(parent) = path.parent() {
31 std::fs::create_dir_all(parent)
32 .with_context(|| format!("Failed to create config dir {}", parent.display()))?;
33 }
34 let content = toml::to_string_pretty(self).context("Failed to serialize config")?;
35 std::fs::write(&path, content)
36 .with_context(|| format!("Failed to write config to {}", path.display()))?;
37 Ok(())
38 }
40
41 pub fn get_value(&self, key: &str) -> Result<String> {
43 match key {
44 "editor.command" => Ok(self.editor.command.clone().unwrap_or_default()),
45 "open.editor" => Ok(self.open.editor.to_string()),
46 _ => anyhow::bail!("Unknown config key: {key}"),
47 }
48 }
49
50 pub fn set_value(&mut self, key: &str, value: &str) -> Result<()> {
52 match key {
53 "editor.command" => {
54 self.editor.command = if value.is_empty() {
55 None
56 } else {
57 Some(value.to_string())
58 };
59 }
60 "open.editor" => {
61 self.open.editor = value
62 .parse::<bool>()
63 .with_context(|| format!("Invalid boolean value: {value}"))?;
64 }
65 _ => anyhow::bail!("Unknown config key: {key}"),
66 }
67 Ok(())
68 }
69}