bitbucket_cli/config/
settings.rs1use 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
9pub mod xdg {
27 use super::*;
28
29 pub fn config_dir() -> Result<PathBuf> {
33 #[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 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 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 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()
92 .or_else(dirs::data_dir)
93 .map(|p| p.join(APP_NAME))
94 .context("Could not determine state directory")
95 }
96
97 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 pub fn config_dir() -> Result<PathBuf> {
132 xdg::config_dir()
133 }
134
135 pub fn config_path() -> Result<PathBuf> {
137 Ok(Self::config_dir()?.join(CONFIG_FILE))
138 }
139
140 pub fn data_dir() -> Result<PathBuf> {
145 xdg::data_dir()
146 }
147
148 pub fn cache_dir() -> Result<PathBuf> {
153 xdg::cache_dir()
154 }
155
156 pub fn state_dir() -> Result<PathBuf> {
161 xdg::state_dir()
162 }
163
164 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 pub fn save(&self) -> Result<()> {
183 let config_dir = Self::config_dir()?;
184 let config_path = Self::config_path()?;
185
186 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 pub fn set_username(&mut self, username: &str) {
199 self.auth.username = Some(username.to_string());
200 }
201
202 pub fn username(&self) -> Option<&str> {
204 self.auth.username.as_deref()
205 }
206
207 pub fn set_default_workspace(&mut self, workspace: &str) {
209 self.auth.default_workspace = Some(workspace.to_string());
210 }
211
212 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 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 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 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 let orig_config = env::var("XDG_CONFIG_HOME").ok();
311
312 unsafe {
314 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 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}