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            "workspace.auto_prune" => Ok(self.workspace.auto_prune.to_string()),
20            _ => anyhow::bail!("Unknown config key: {key}"),
21        }
22    }
23
24    /// Set a config value by dot-separated key path.
25    ///
26    /// # Errors
27    ///
28    /// Returns an error if `key` is not a recognised config key or if the
29    /// value cannot be parsed (e.g. a non-boolean for `open.editor`).
30    pub fn set_value(&mut self, key: &str, value: &str) -> Result<()> {
31        match key {
32            "editor.command" => {
33                self.editor.command = (!value.is_empty()).then(|| value.to_string());
34            }
35            "open.editor" => {
36                self.open.editor = value
37                    .parse::<bool>()
38                    .with_context(|| format!("Invalid boolean value: {value}"))?;
39            }
40            "workspace.ttl" => {
41                self.workspace.ttl = (!value.is_empty())
42                    .then(|| {
43                        value
44                            .parse()
45                            .map_err(|e| anyhow::anyhow!("Invalid duration {value:?}: {e}"))
46                    })
47                    .transpose()?;
48            }
49            "workspace.auto_prune" => {
50                self.workspace.auto_prune = value
51                    .parse::<bool>()
52                    .with_context(|| format!("Invalid boolean value: {value}"))?;
53            }
54            _ => anyhow::bail!("Unknown config key: {key}"),
55        }
56        Ok(())
57    }
58}