Skip to main content

worktree_io/config/
ops_get_set.rs

1use anyhow::{Context, Result};
2
3use super::Config;
4
5impl Config {
6    /// Get a config value by dot-separated key path.
7    ///
8    /// # Errors
9    ///
10    /// Returns an error if `key` is not a recognised config key.
11    pub fn get_value(&self, key: &str) -> Result<String> {
12        match key {
13            "editor.command" => Ok(self.editor.command.clone().unwrap_or_default()),
14            "open.editor" => Ok(self.open.editor.to_string()),
15            "workspace.ttl" => Ok(self
16                .workspace
17                .ttl
18                .map_or_else(String::new, |t| t.to_string())),
19            _ => anyhow::bail!("Unknown config key: {key}"),
20        }
21    }
22
23    /// Set a config value by dot-separated key path.
24    ///
25    /// # Errors
26    ///
27    /// Returns an error if `key` is not a recognised config key or if the
28    /// value cannot be parsed (e.g. a non-boolean for `open.editor`).
29    pub fn set_value(&mut self, key: &str, value: &str) -> Result<()> {
30        match key {
31            "editor.command" => {
32                self.editor.command = (!value.is_empty()).then(|| value.to_string());
33            }
34            "open.editor" => {
35                self.open.editor = value
36                    .parse::<bool>()
37                    .with_context(|| format!("Invalid boolean value: {value}"))?;
38            }
39            "workspace.ttl" => {
40                self.workspace.ttl = (!value.is_empty())
41                    .then(|| {
42                        value
43                            .parse()
44                            .map_err(|e| anyhow::anyhow!("Invalid duration {value:?}: {e}"))
45                    })
46                    .transpose()?;
47            }
48            _ => anyhow::bail!("Unknown config key: {key}"),
49        }
50        Ok(())
51    }
52}