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    #[serde(default)]
114    pub display: DisplayConfig,
115}
116
117#[derive(Debug, Clone, Serialize, Deserialize, Default)]
118pub struct AuthConfig {
119    pub username: Option<String>,
120    pub default_workspace: Option<String>,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize, Default)]
124pub struct DefaultsConfig {
125    pub workspace: Option<String>,
126    pub repository: Option<String>,
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct DisplayConfig {
131    pub color: bool,
132    pub pager: bool,
133}
134
135impl Default for DisplayConfig {
136    fn default() -> Self {
137        Self {
138            color: true,
139            pager: true,
140        }
141    }
142}
143
144impl Config {
145    /// Get the configuration directory path (XDG compliant)
146    ///
147    /// Returns `$XDG_CONFIG_HOME/bitbucket-cli` on Linux,
148    /// or platform-appropriate equivalent on other systems.
149    pub fn config_dir() -> Result<PathBuf> {
150        xdg::config_dir()
151    }
152
153    /// Get the configuration file path
154    pub fn config_path() -> Result<PathBuf> {
155        Ok(Self::config_dir()?.join(CONFIG_FILE))
156    }
157
158    /// Get the data directory path (XDG compliant)
159    ///
160    /// Returns `$XDG_DATA_HOME/bitbucket-cli` on Linux.
161    /// Use this for persistent application data.
162    pub fn data_dir() -> Result<PathBuf> {
163        xdg::data_dir()
164    }
165
166    /// Get the cache directory path (XDG compliant)
167    ///
168    /// Returns `$XDG_CACHE_HOME/bitbucket-cli` on Linux.
169    /// Use this for cached data that can be regenerated.
170    pub fn cache_dir() -> Result<PathBuf> {
171        xdg::cache_dir()
172    }
173
174    /// Get the state directory path (XDG compliant)
175    ///
176    /// Returns `$XDG_STATE_HOME/bitbucket-cli` on Linux.
177    /// Use this for state data like logs and history.
178    pub fn state_dir() -> Result<PathBuf> {
179        xdg::state_dir()
180    }
181
182    /// Load configuration from file, or create default if it doesn't exist
183    pub fn load() -> Result<Self> {
184        let config_path = Self::config_path()?;
185
186        if !config_path.exists() {
187            return Ok(Self::default());
188        }
189
190        let contents = fs::read_to_string(&config_path)
191            .with_context(|| format!("Failed to read config file: {:?}", config_path))?;
192
193        let config: Config = toml::from_str(&contents)
194            .with_context(|| format!("Failed to parse config file: {:?}", config_path))?;
195
196        Ok(config)
197    }
198
199    /// Save configuration to file
200    pub fn save(&self) -> Result<()> {
201        let config_dir = Self::config_dir()?;
202        let config_path = Self::config_path()?;
203
204        // Create config directory if it doesn't exist (XDG compliant)
205        xdg::ensure_dir(&config_dir)?;
206
207        let contents = toml::to_string_pretty(self).context("Failed to serialize config")?;
208
209        fs::write(&config_path, contents)
210            .with_context(|| format!("Failed to write config file: {:?}", config_path))?;
211
212        Ok(())
213    }
214
215    /// Set the authenticated username
216    pub fn set_username(&mut self, username: &str) {
217        self.auth.username = Some(username.to_string());
218    }
219
220    /// Get the authenticated username
221    pub fn username(&self) -> Option<&str> {
222        self.auth.username.as_deref()
223    }
224
225    /// Set the default workspace
226    pub fn set_default_workspace(&mut self, workspace: &str) {
227        self.auth.default_workspace = Some(workspace.to_string());
228    }
229
230    /// Get the default workspace
231    ///
232    /// `[auth] default_workspace` is the primary source; `[defaults] workspace`
233    /// remains as a legacy fallback. Remove the fallback (and the
234    /// `defaults.workspace` field) in the first release after 1.0.
235    pub fn default_workspace(&self) -> Option<&str> {
236        self.auth
237            .default_workspace
238            .as_deref()
239            .or(self.defaults.workspace.as_deref())
240    }
241
242    /// Clear authentication settings (for logout)
243    pub fn clear_auth(&mut self) {
244        self.auth.username = None;
245        self.auth.default_workspace = None;
246        self.defaults.workspace = None;
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    #[test]
255    fn test_default_config() {
256        let config = Config::default();
257        assert!(config.auth.username.is_none());
258        assert!(config.display.color);
259    }
260
261    #[test]
262    fn test_config_serialization() {
263        let config = Config::default();
264        let serialized = toml::to_string(&config).unwrap();
265        let deserialized: Config = toml::from_str(&serialized).unwrap();
266        assert_eq!(config.display.color, deserialized.display.color);
267    }
268
269    #[test]
270    fn test_default_workspace_prefers_auth_field() {
271        let mut config = Config::default();
272        config.auth.default_workspace = Some("auth-ws".to_string());
273        config.defaults.workspace = Some("legacy-ws".to_string());
274        assert_eq!(config.default_workspace(), Some("auth-ws"));
275    }
276
277    #[test]
278    fn test_default_workspace_falls_back_to_defaults_field() {
279        let mut config = Config::default();
280        config.defaults.workspace = Some("legacy-ws".to_string());
281        assert_eq!(config.default_workspace(), Some("legacy-ws"));
282    }
283
284    #[test]
285    fn test_set_default_workspace_writes_auth_field() {
286        let mut config = Config::default();
287        config.set_default_workspace("my-ws");
288        assert_eq!(config.auth.default_workspace.as_deref(), Some("my-ws"));
289        assert!(config.defaults.workspace.is_none());
290        assert_eq!(config.default_workspace(), Some("my-ws"));
291    }
292
293    #[test]
294    fn test_clear_auth_clears_default_workspace() {
295        let mut config = Config::default();
296        config.set_username("someone");
297        config.auth.default_workspace = Some("auth-ws".to_string());
298        config.defaults.workspace = Some("legacy-ws".to_string());
299
300        config.clear_auth();
301
302        assert!(config.username().is_none());
303        assert!(config.default_workspace().is_none());
304    }
305
306    #[test]
307    fn test_xdg_directories() {
308        // These should not panic and should return valid paths
309        let config_dir = xdg::config_dir().unwrap();
310        let data_dir = xdg::data_dir().unwrap();
311        let cache_dir = xdg::cache_dir().unwrap();
312        let state_dir = xdg::state_dir().unwrap();
313
314        // All paths should end with our app name
315        assert!(config_dir.ends_with("bitbucket-cli"));
316        assert!(data_dir.ends_with("bitbucket-cli"));
317        assert!(cache_dir.ends_with("bitbucket-cli"));
318        assert!(state_dir.ends_with("bitbucket-cli"));
319    }
320
321    #[test]
322    #[cfg(unix)]
323    fn test_xdg_env_override() {
324        use std::env;
325
326        // Save original values
327        let orig_config = env::var("XDG_CONFIG_HOME").ok();
328
329        // SAFETY: This test runs single-threaded and we restore the original value after
330        unsafe {
331            // Set custom XDG_CONFIG_HOME
332            env::set_var("XDG_CONFIG_HOME", "/tmp/test-xdg-config");
333        }
334
335        let config_dir = xdg::config_dir().unwrap();
336        assert_eq!(
337            config_dir,
338            PathBuf::from("/tmp/test-xdg-config/bitbucket-cli")
339        );
340
341        // SAFETY: Restoring original environment state
342        unsafe {
343            match orig_config {
344                Some(val) => env::set_var("XDG_CONFIG_HOME", val),
345                None => env::remove_var("XDG_CONFIG_HOME"),
346            }
347        }
348    }
349}