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 #[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 pub fn config_dir() -> Result<PathBuf> {
150 xdg::config_dir()
151 }
152
153 pub fn config_path() -> Result<PathBuf> {
155 Ok(Self::config_dir()?.join(CONFIG_FILE))
156 }
157
158 pub fn data_dir() -> Result<PathBuf> {
163 xdg::data_dir()
164 }
165
166 pub fn cache_dir() -> Result<PathBuf> {
171 xdg::cache_dir()
172 }
173
174 pub fn state_dir() -> Result<PathBuf> {
179 xdg::state_dir()
180 }
181
182 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 pub fn save(&self) -> Result<()> {
201 let config_dir = Self::config_dir()?;
202 let config_path = Self::config_path()?;
203
204 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 pub fn set_username(&mut self, username: &str) {
217 self.auth.username = Some(username.to_string());
218 }
219
220 pub fn username(&self) -> Option<&str> {
222 self.auth.username.as_deref()
223 }
224
225 pub fn set_default_workspace(&mut self, workspace: &str) {
227 self.auth.default_workspace = Some(workspace.to_string());
228 }
229
230 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 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 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 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 let orig_config = env::var("XDG_CONFIG_HOME").ok();
328
329 unsafe {
331 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 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}