Skip to main content

sonos_cli/
config.rs

1//! Configuration system for the sonos-cli application.
2
3use serde::{Deserialize, Serialize};
4use std::fmt;
5use std::path::PathBuf;
6
7/// Album art rendering mode.
8#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
9#[serde(rename_all = "lowercase")]
10pub enum AlbumArtMode {
11    #[default]
12    Image,
13    Halfblock,
14    Off,
15    /// Catch-all for unrecognized values (e.g. old "auto") — behaves like Image.
16    #[serde(other)]
17    Other,
18}
19
20impl AlbumArtMode {
21    /// Returns true when album art should be disabled.
22    pub fn is_off(&self) -> bool {
23        *self == Self::Off
24    }
25}
26
27impl fmt::Display for AlbumArtMode {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            Self::Image | Self::Other => write!(f, "image"),
31            Self::Halfblock => write!(f, "halfblock"),
32            Self::Off => write!(f, "off"),
33        }
34    }
35}
36
37/// Custom Serialize: `Other` normalizes to `"image"` on save.
38impl Serialize for AlbumArtMode {
39    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
40        serializer.serialize_str(&self.to_string())
41    }
42}
43
44/// User configuration loaded from config file with environment variable overrides.
45#[derive(Debug, Clone, Deserialize, Serialize)]
46#[serde(default)]
47pub struct Config {
48    /// Default group to target when --speaker/--group not specified
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub default_group: Option<String>,
51    /// TUI color theme: "dark", "light", "neon", or "sonos"
52    pub theme: String,
53    /// Album art rendering mode: "image", "halfblock", or "off"
54    pub album_art_mode: AlbumArtMode,
55}
56
57impl Default for Config {
58    fn default() -> Self {
59        Self {
60            default_group: None,
61            theme: "dark".to_string(),
62            album_art_mode: AlbumArtMode::default(),
63        }
64    }
65}
66
67/// Return the path to the config file.
68fn config_path() -> Option<PathBuf> {
69    std::env::var("SONOS_CONFIG_DIR")
70        .ok()
71        .filter(|s| !s.is_empty())
72        .map(PathBuf::from)
73        .filter(|p| p.is_absolute())
74        .or_else(|| dirs::config_dir().map(|p| p.join("sonos")))
75        .map(|d| d.join("config.toml"))
76}
77
78impl Config {
79    /// Load from config file with environment variable overrides.
80    pub fn load() -> Self {
81        let mut config: Config = config_path()
82            .and_then(|p| std::fs::read_to_string(p).ok())
83            .and_then(|s| toml::from_str(&s).ok())
84            .unwrap_or_default();
85
86        // Environment variable overrides
87        if let Ok(group) = std::env::var("SONOS_DEFAULT_GROUP") {
88            config.default_group = Some(group);
89        }
90
91        config
92    }
93
94    /// Persist the current config to disk.
95    pub fn save(&self) -> anyhow::Result<()> {
96        let path =
97            config_path().ok_or_else(|| anyhow::anyhow!("cannot determine config directory"))?;
98        if let Some(dir) = path.parent() {
99            std::fs::create_dir_all(dir)?;
100        }
101        let content = toml::to_string_pretty(self)?;
102        std::fs::write(path, content)?;
103        Ok(())
104    }
105}