atlassian-cli-config 0.2.8

Configuration management for Atlassian CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
use std::{
    fs,
    path::{Path, PathBuf},
};

use indexmap::IndexMap;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use tracing::info;

const NEW_CONFIG_DIR: &str = ".atlassian-cli";
const OLD_CONFIG_DIR: &str = ".atlcli";
const CONFIG_FILENAME: &str = "config.yaml";

/// Result of config directory migration attempt.
#[derive(Debug)]
pub enum MigrationResult {
    /// No migration needed (new config exists or old doesn't)
    NotNeeded,
    /// Migration was performed successfully
    Migrated { from: PathBuf, to: PathBuf },
    /// Migration failed with an error
    Failed(String),
}

/// Check and perform migration from old config directory (~/.atlcli/) to new one (~/.atlassian-cli/).
/// Copies config file if old exists and new doesn't. Does not delete old config.
pub fn migrate_config_if_needed() -> MigrationResult {
    let home = match dirs::home_dir() {
        Some(h) => h,
        None => return MigrationResult::NotNeeded,
    };

    let old_config = home.join(OLD_CONFIG_DIR).join(CONFIG_FILENAME);
    let new_config = home.join(NEW_CONFIG_DIR).join(CONFIG_FILENAME);

    // Only migrate if old exists AND new doesn't
    if !old_config.exists() || new_config.exists() {
        return MigrationResult::NotNeeded;
    }

    // Create new directory
    let new_dir = home.join(NEW_CONFIG_DIR);
    if let Err(e) = fs::create_dir_all(&new_dir) {
        return MigrationResult::Failed(format!(
            "Failed to create directory {}: {}",
            new_dir.display(),
            e
        ));
    }

    // Copy config file (not move - user can clean up old manually)
    if let Err(e) = fs::copy(&old_config, &new_config) {
        return MigrationResult::Failed(format!(
            "Failed to copy config from {} to {}: {}",
            old_config.display(),
            new_config.display(),
            e
        ));
    }

    info!(
        "Migrated config from {} to {}",
        old_config.display(),
        new_config.display()
    );

    MigrationResult::Migrated {
        from: old_config,
        to: new_config,
    }
}

/// Represents the full CLI configuration stored on disk.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
    #[serde(default)]
    pub default_profile: Option<String>,
    #[serde(default)]
    pub profiles: IndexMap<String, Profile>,
}

impl Config {
    /// Load configuration from the provided path or the default config file.
    pub fn load<P: AsRef<Path>>(path: Option<P>) -> Result<Self> {
        let path = path
            .map(|p| p.as_ref().to_path_buf())
            .unwrap_or_else(Config::default_path);

        if !path.exists() {
            return Ok(Config::default());
        }

        let raw = fs::read_to_string(&path)
            .with_context(|| format!("Unable to read config file at {}", path.display()))?;

        serde_yaml::from_str(&raw)
            .with_context(|| format!("Malformed YAML in config file {}", path.display()))
    }

    /// Persist the configuration to disk, creating parent directories if needed.
    pub fn save<P: AsRef<Path>>(&self, path: Option<P>) -> Result<()> {
        let path = path
            .map(|p| p.as_ref().to_path_buf())
            .unwrap_or_else(Config::default_path);

        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).with_context(|| {
                format!("Unable to create config directory {}", parent.display())
            })?;
        }

        let serialized = serde_yaml::to_string(self)?;
        fs::write(&path, serialized)
            .with_context(|| format!("Unable to write config file {}", path.display()))?;

        Ok(())
    }

    /// Convenience helper to retrieve a profile by name.
    pub fn profile(&self, name: &str) -> Option<&Profile> {
        self.profiles.get(name)
    }

    /// Returns either the requested profile or falls back to the default one.
    pub fn resolve_profile<'a>(
        &'a self,
        requested: Option<&'a str>,
    ) -> Option<(&'a str, &'a Profile)> {
        if let Some(name) = requested {
            self.profiles.get(name).map(|profile| (name, profile))
        } else if let Some(default_name) = self.default_profile.as_deref() {
            self.profiles
                .get(default_name)
                .map(|profile| (default_name, profile))
        } else if let Some((name, profile)) = self.profiles.iter().next() {
            Some((name.as_str(), profile))
        } else {
            None
        }
    }

    fn default_path() -> PathBuf {
        let mut path = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
        path.push(".atlassian-cli");
        path.push("config.yaml");
        path
    }
}

/// Minimal representation of a profile. Values are optional to support
/// partially configured setups (e.g., when storing tokens in the keyring).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Profile {
    pub base_url: Option<String>,
    pub email: Option<String>,
    pub api_token: Option<String>,
    /// Bitbucket workspace slug (optional, can be inferred from base_url).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace: Option<String>,
    /// OpsGenie API key (optional, separate from Atlassian token).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub opsgenie_api_key: Option<String>,
    /// OpsGenie region: "us" or "eu" (defaults to "us").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub opsgenie_region: Option<String>,
    /// Bamboo base URL (optional, if different from main base_url).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bamboo_base_url: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert!(config.default_profile.is_none());
        assert!(config.profiles.is_empty());
    }

    #[test]
    fn test_load_missing_file() {
        let result = Config::load(Some("/nonexistent/config.yaml"));
        assert!(result.is_ok());
        let config = result.unwrap();
        assert!(config.profiles.is_empty());
    }

    #[test]
    fn test_save_and_load() {
        let mut config = Config {
            default_profile: Some("work".to_string()),
            ..Default::default()
        };

        let profile = Profile {
            base_url: Some("https://test.atlassian.net".to_string()),
            email: Some("test@example.com".to_string()),
            ..Default::default()
        };

        config.profiles.insert("work".to_string(), profile);

        let temp_file = NamedTempFile::new().unwrap();
        let temp_path = temp_file.path();

        config.save(Some(temp_path)).unwrap();
        let loaded = Config::load(Some(temp_path)).unwrap();

        assert_eq!(loaded.default_profile, Some("work".to_string()));
        assert_eq!(loaded.profiles.len(), 1);

        let work_profile = loaded.profiles.get("work").unwrap();
        assert_eq!(
            work_profile.base_url,
            Some("https://test.atlassian.net".to_string())
        );
        assert_eq!(work_profile.email, Some("test@example.com".to_string()));
    }

    #[test]
    fn test_load_malformed_yaml() {
        let mut temp_file = NamedTempFile::new().unwrap();
        write!(temp_file, "invalid: yaml: [unclosed").unwrap();

        let result = Config::load(Some(temp_file.path()));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Malformed YAML"));
    }

    #[test]
    fn test_profile_retrieval() {
        let mut config = Config::default();
        let profile = Profile {
            base_url: Some("https://test.atlassian.net".to_string()),
            ..Default::default()
        };

        config.profiles.insert("test".to_string(), profile);

        assert!(config.profile("test").is_some());
        assert!(config.profile("nonexistent").is_none());
    }

    #[test]
    fn test_resolve_profile_requested() {
        let mut config = Config {
            default_profile: Some("default".to_string()),
            ..Default::default()
        };

        let default_profile = Profile {
            base_url: Some("https://default.atlassian.net".to_string()),
            ..Default::default()
        };
        config
            .profiles
            .insert("default".to_string(), default_profile);

        let work_profile = Profile {
            base_url: Some("https://work.atlassian.net".to_string()),
            ..Default::default()
        };
        config.profiles.insert("work".to_string(), work_profile);

        let (name, profile) = config.resolve_profile(Some("work")).unwrap();
        assert_eq!(name, "work");
        assert_eq!(
            profile.base_url,
            Some("https://work.atlassian.net".to_string())
        );
    }

    #[test]
    fn test_resolve_profile_default() {
        let mut config = Config {
            default_profile: Some("default".to_string()),
            ..Default::default()
        };

        let default_profile = Profile {
            base_url: Some("https://default.atlassian.net".to_string()),
            ..Default::default()
        };
        config
            .profiles
            .insert("default".to_string(), default_profile);

        let (name, profile) = config.resolve_profile(None).unwrap();
        assert_eq!(name, "default");
        assert_eq!(
            profile.base_url,
            Some("https://default.atlassian.net".to_string())
        );
    }

    #[test]
    fn test_resolve_profile_first_available() {
        let mut config = Config::default();

        let profile = Profile {
            base_url: Some("https://only.atlassian.net".to_string()),
            ..Default::default()
        };
        config.profiles.insert("only".to_string(), profile);

        let result = config.resolve_profile(None);
        assert!(result.is_some());
        let (name, profile) = result.unwrap();
        assert_eq!(name, "only");
        assert_eq!(
            profile.base_url,
            Some("https://only.atlassian.net".to_string())
        );
    }

    #[test]
    fn test_resolve_profile_none_available() {
        let config = Config::default();
        assert!(config.resolve_profile(None).is_none());
    }

    #[test]
    fn test_resolve_profile_nonexistent_requested() {
        let mut config = Config::default();

        let profile = Profile {
            base_url: Some("https://test.atlassian.net".to_string()),
            ..Default::default()
        };
        config.profiles.insert("test".to_string(), profile);

        assert!(config.resolve_profile(Some("nonexistent")).is_none());
    }

    #[test]
    fn test_profile_default() {
        let profile = Profile::default();
        assert!(profile.base_url.is_none());
        assert!(profile.email.is_none());
        assert!(profile.api_token.is_none());
    }

    #[test]
    fn test_indexmap_preserves_insertion_order() {
        let mut config = Config::default();

        // Insert profiles in specific order
        let profile1 = Profile {
            base_url: Some("https://first.atlassian.net".to_string()),
            ..Default::default()
        };
        config.profiles.insert("first".to_string(), profile1);

        let profile2 = Profile {
            base_url: Some("https://second.atlassian.net".to_string()),
            ..Default::default()
        };
        config.profiles.insert("second".to_string(), profile2);

        let profile3 = Profile {
            base_url: Some("https://third.atlassian.net".to_string()),
            ..Default::default()
        };
        config.profiles.insert("third".to_string(), profile3);

        // Verify iteration order matches insertion order
        let names: Vec<_> = config.profiles.keys().map(|s| s.as_str()).collect();
        assert_eq!(names, vec!["first", "second", "third"]);
    }

    #[test]
    fn test_resolve_profile_first_available_is_deterministic() {
        // When no default is set, resolve_profile should return the first profile
        // consistently (not randomly based on HashMap iteration)
        let mut config = Config::default();

        // Add multiple profiles
        config.profiles.insert(
            "alpha".to_string(),
            Profile {
                base_url: Some("https://alpha.atlassian.net".to_string()),
                ..Default::default()
            },
        );
        config.profiles.insert(
            "beta".to_string(),
            Profile {
                base_url: Some("https://beta.atlassian.net".to_string()),
                ..Default::default()
            },
        );
        config.profiles.insert(
            "gamma".to_string(),
            Profile {
                base_url: Some("https://gamma.atlassian.net".to_string()),
                ..Default::default()
            },
        );

        // Resolve multiple times and verify we always get the same (first inserted) profile
        for _ in 0..10 {
            let (name, _) = config.resolve_profile(None).unwrap();
            assert_eq!(
                name, "alpha",
                "First profile should always be selected deterministically"
            );
        }
    }

    #[test]
    fn test_shift_remove_preserves_order() {
        let mut config = Config::default();

        config.profiles.insert("a".to_string(), Profile::default());
        config.profiles.insert("b".to_string(), Profile::default());
        config.profiles.insert("c".to_string(), Profile::default());

        // Remove middle element
        config.profiles.shift_remove("b");

        let names: Vec<_> = config.profiles.keys().map(|s| s.as_str()).collect();
        assert_eq!(
            names,
            vec!["a", "c"],
            "Order should be preserved after removal"
        );
    }

    #[test]
    fn test_yaml_serialization() {
        let mut config = Config {
            default_profile: Some("prod".to_string()),
            ..Default::default()
        };

        let profile = Profile {
            base_url: Some("https://prod.atlassian.net".to_string()),
            email: Some("admin@example.com".to_string()),
            api_token: Some("secret-token-123".to_string()),
            ..Default::default()
        };

        config.profiles.insert("prod".to_string(), profile);

        let yaml = serde_yaml::to_string(&config).unwrap();

        assert!(yaml.contains("default_profile: prod"));
        assert!(yaml.contains("https://prod.atlassian.net"));
        assert!(yaml.contains("admin@example.com"));
        assert!(yaml.contains("secret-token-123"));

        let deserialized: Config = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(deserialized.default_profile, config.default_profile);
        assert_eq!(deserialized.profiles.len(), 1);
    }
}