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