Skip to main content

bitbucket_cli/config/
settings.rs

1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use std::fs;
4use std::path::PathBuf;
5
6const APP_NAME: &str = "bitbucket-cli";
7const CONFIG_FILE: &str = "config.toml";
8
9/// XDG Base Directory helper functions
10///
11/// On Linux, these follow the XDG Base Directory Specification:
12/// - Config: `$XDG_CONFIG_HOME/bitbucket-cli` (default: `~/.config/bitbucket-cli`)
13/// - Data: `$XDG_DATA_HOME/bitbucket-cli` (default: `~/.local/share/bitbucket-cli`)
14/// - Cache: `$XDG_CACHE_HOME/bitbucket-cli` (default: `~/.cache/bitbucket-cli`)
15/// - State: `$XDG_STATE_HOME/bitbucket-cli` (default: `~/.local/state/bitbucket-cli`)
16///
17/// On macOS:
18/// - Config: `~/Library/Application Support/bitbucket-cli`
19/// - Data: `~/Library/Application Support/bitbucket-cli`
20/// - Cache: `~/Library/Caches/bitbucket-cli`
21///
22/// On Windows:
23/// - Config: `%APPDATA%\bitbucket-cli`
24/// - Data: `%APPDATA%\bitbucket-cli`
25/// - Cache: `%LOCALAPPDATA%\bitbucket-cli`
26pub mod xdg {
27    use super::*;
28
29    /// Get the XDG config directory for the application
30    ///
31    /// Respects `$XDG_CONFIG_HOME` on Linux (falls back to `~/.config`)
32    pub fn config_dir() -> Result<PathBuf> {
33        // First check for explicit XDG_CONFIG_HOME on Unix
34        #[cfg(unix)]
35        if let Ok(xdg_config) = std::env::var("XDG_CONFIG_HOME") {
36            if !xdg_config.is_empty() {
37                return Ok(PathBuf::from(xdg_config).join(APP_NAME));
38            }
39        }
40
41        dirs::config_dir()
42            .map(|p| p.join(APP_NAME))
43            .context("Could not determine config directory")
44    }
45
46    /// Get the XDG data directory for the application
47    ///
48    /// Respects `$XDG_DATA_HOME` on Linux (falls back to `~/.local/share`)
49    pub fn data_dir() -> Result<PathBuf> {
50        #[cfg(unix)]
51        if let Ok(xdg_data) = std::env::var("XDG_DATA_HOME") {
52            if !xdg_data.is_empty() {
53                return Ok(PathBuf::from(xdg_data).join(APP_NAME));
54            }
55        }
56
57        dirs::data_dir()
58            .map(|p| p.join(APP_NAME))
59            .context("Could not determine data directory")
60    }
61
62    /// Get the XDG cache directory for the application
63    ///
64    /// Respects `$XDG_CACHE_HOME` on Linux (falls back to `~/.cache`)
65    pub fn cache_dir() -> Result<PathBuf> {
66        #[cfg(unix)]
67        if let Ok(xdg_cache) = std::env::var("XDG_CACHE_HOME") {
68            if !xdg_cache.is_empty() {
69                return Ok(PathBuf::from(xdg_cache).join(APP_NAME));
70            }
71        }
72
73        dirs::cache_dir()
74            .map(|p| p.join(APP_NAME))
75            .context("Could not determine cache directory")
76    }
77
78    /// Get the XDG state directory for the application
79    ///
80    /// Respects `$XDG_STATE_HOME` on Linux (falls back to `~/.local/state`)
81    /// On non-Linux platforms, falls back to data directory
82    pub fn state_dir() -> Result<PathBuf> {
83        #[cfg(unix)]
84        if let Ok(xdg_state) = std::env::var("XDG_STATE_HOME") {
85            if !xdg_state.is_empty() {
86                return Ok(PathBuf::from(xdg_state).join(APP_NAME));
87            }
88        }
89
90        // dirs::state_dir() is available on Linux, falls back to data_dir on other platforms
91        dirs::state_dir()
92            .or_else(dirs::data_dir)
93            .map(|p| p.join(APP_NAME))
94            .context("Could not determine state directory")
95    }
96
97    /// Ensure a directory exists, creating it if necessary
98    pub fn ensure_dir(path: &PathBuf) -> Result<()> {
99        if !path.exists() {
100            fs::create_dir_all(path)
101                .with_context(|| format!("Failed to create directory: {:?}", path))?;
102        }
103        Ok(())
104    }
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize, Default)]
108pub struct Config {
109    #[serde(default)]
110    pub auth: AuthConfig,
111    #[serde(default)]
112    pub defaults: DefaultsConfig,
113}
114
115#[derive(Debug, Clone, Serialize, Deserialize, Default)]
116pub struct AuthConfig {
117    pub username: Option<String>,
118    pub default_workspace: Option<String>,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize, Default)]
122pub struct DefaultsConfig {
123    pub workspace: Option<String>,
124}
125
126impl Config {
127    /// Get the configuration directory path (XDG compliant)
128    ///
129    /// Returns `$XDG_CONFIG_HOME/bitbucket-cli` on Linux,
130    /// or platform-appropriate equivalent on other systems.
131    pub fn config_dir() -> Result<PathBuf> {
132        xdg::config_dir()
133    }
134
135    /// Get the configuration file path
136    pub fn config_path() -> Result<PathBuf> {
137        Ok(Self::config_dir()?.join(CONFIG_FILE))
138    }
139
140    /// Get the data directory path (XDG compliant)
141    ///
142    /// Returns `$XDG_DATA_HOME/bitbucket-cli` on Linux.
143    /// Use this for persistent application data.
144    pub fn data_dir() -> Result<PathBuf> {
145        xdg::data_dir()
146    }
147
148    /// Get the cache directory path (XDG compliant)
149    ///
150    /// Returns `$XDG_CACHE_HOME/bitbucket-cli` on Linux.
151    /// Use this for cached data that can be regenerated.
152    pub fn cache_dir() -> Result<PathBuf> {
153        xdg::cache_dir()
154    }
155
156    /// Get the state directory path (XDG compliant)
157    ///
158    /// Returns `$XDG_STATE_HOME/bitbucket-cli` on Linux.
159    /// Use this for state data like logs and history.
160    pub fn state_dir() -> Result<PathBuf> {
161        xdg::state_dir()
162    }
163
164    /// Load configuration from file, or create default if it doesn't exist
165    pub fn load() -> Result<Self> {
166        let config_path = Self::config_path()?;
167
168        if !config_path.exists() {
169            return Ok(Self::default());
170        }
171
172        let contents = fs::read_to_string(&config_path)
173            .with_context(|| format!("Failed to read config file: {:?}", config_path))?;
174
175        let config: Config = toml::from_str(&contents)
176            .with_context(|| format!("Failed to parse config file: {:?}", config_path))?;
177
178        Ok(config)
179    }
180
181    /// Save configuration to file
182    pub fn save(&self) -> Result<()> {
183        let config_dir = Self::config_dir()?;
184        let config_path = Self::config_path()?;
185
186        // Create config directory if it doesn't exist (XDG compliant)
187        xdg::ensure_dir(&config_dir)?;
188
189        let contents = toml::to_string_pretty(self).context("Failed to serialize config")?;
190
191        fs::write(&config_path, contents)
192            .with_context(|| format!("Failed to write config file: {:?}", config_path))?;
193
194        Ok(())
195    }
196
197    /// Set the authenticated username
198    pub fn set_username(&mut self, username: &str) {
199        self.auth.username = Some(username.to_string());
200    }
201
202    /// Get the authenticated username
203    pub fn username(&self) -> Option<&str> {
204        self.auth.username.as_deref()
205    }
206
207    /// Set the default workspace
208    pub fn set_default_workspace(&mut self, workspace: &str) {
209        self.auth.default_workspace = Some(workspace.to_string());
210    }
211
212    /// Get the default workspace
213    ///
214    /// `[auth] default_workspace` is the primary source; `[defaults] workspace`
215    /// remains as a legacy fallback. Removing the fallback (and the
216    /// `defaults.workspace` field) is a breaking change, so it must wait for
217    /// the next major release (2.0.0).
218    pub fn default_workspace(&self) -> Option<&str> {
219        self.auth
220            .default_workspace
221            .as_deref()
222            .or(self.defaults.workspace.as_deref())
223    }
224
225    /// Clear authentication settings (for logout)
226    pub fn clear_auth(&mut self) {
227        self.auth.username = None;
228        self.auth.default_workspace = None;
229        self.defaults.workspace = None;
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    #[test]
238    fn test_default_config() {
239        let config = Config::default();
240        assert!(config.auth.username.is_none());
241        assert!(config.defaults.workspace.is_none());
242    }
243
244    #[test]
245    fn test_config_serialization() {
246        let config = Config::default();
247        let serialized = toml::to_string(&config).unwrap();
248        let deserialized: Config = toml::from_str(&serialized).unwrap();
249        assert_eq!(config.auth.username, deserialized.auth.username);
250    }
251
252    #[test]
253    fn test_default_workspace_prefers_auth_field() {
254        let mut config = Config::default();
255        config.auth.default_workspace = Some("auth-ws".to_string());
256        config.defaults.workspace = Some("legacy-ws".to_string());
257        assert_eq!(config.default_workspace(), Some("auth-ws"));
258    }
259
260    #[test]
261    fn test_default_workspace_falls_back_to_defaults_field() {
262        let mut config = Config::default();
263        config.defaults.workspace = Some("legacy-ws".to_string());
264        assert_eq!(config.default_workspace(), Some("legacy-ws"));
265    }
266
267    #[test]
268    fn test_set_default_workspace_writes_auth_field() {
269        let mut config = Config::default();
270        config.set_default_workspace("my-ws");
271        assert_eq!(config.auth.default_workspace.as_deref(), Some("my-ws"));
272        assert!(config.defaults.workspace.is_none());
273        assert_eq!(config.default_workspace(), Some("my-ws"));
274    }
275
276    #[test]
277    fn test_clear_auth_clears_default_workspace() {
278        let mut config = Config::default();
279        config.set_username("someone");
280        config.auth.default_workspace = Some("auth-ws".to_string());
281        config.defaults.workspace = Some("legacy-ws".to_string());
282
283        config.clear_auth();
284
285        assert!(config.username().is_none());
286        assert!(config.default_workspace().is_none());
287    }
288
289    #[test]
290    fn test_xdg_directories() {
291        // These should not panic and should return valid paths
292        let config_dir = xdg::config_dir().unwrap();
293        let data_dir = xdg::data_dir().unwrap();
294        let cache_dir = xdg::cache_dir().unwrap();
295        let state_dir = xdg::state_dir().unwrap();
296
297        // All paths should end with our app name
298        assert!(config_dir.ends_with("bitbucket-cli"));
299        assert!(data_dir.ends_with("bitbucket-cli"));
300        assert!(cache_dir.ends_with("bitbucket-cli"));
301        assert!(state_dir.ends_with("bitbucket-cli"));
302    }
303
304    #[test]
305    #[cfg(unix)]
306    fn test_xdg_env_override() {
307        use std::env;
308
309        // Save original values
310        let orig_config = env::var("XDG_CONFIG_HOME").ok();
311
312        // SAFETY: This test runs single-threaded and we restore the original value after
313        unsafe {
314            // Set custom XDG_CONFIG_HOME
315            env::set_var("XDG_CONFIG_HOME", "/tmp/test-xdg-config");
316        }
317
318        let config_dir = xdg::config_dir().unwrap();
319        assert_eq!(
320            config_dir,
321            PathBuf::from("/tmp/test-xdg-config/bitbucket-cli")
322        );
323
324        // SAFETY: Restoring original environment state
325        unsafe {
326            match orig_config {
327                Some(val) => env::set_var("XDG_CONFIG_HOME", val),
328                None => env::remove_var("XDG_CONFIG_HOME"),
329            }
330        }
331    }
332}