Skip to main content

atlassian_cli_config/
lib.rs

1use std::{fs, path::Path};
2
3use indexmap::IndexMap;
4
5pub mod paths;
6pub use paths::{ConfigDirSource, ConfigPaths, PathEnv};
7
8use anyhow::{Context, Result};
9use serde::{Deserialize, Serialize};
10
11/// Represents the full CLI configuration stored on disk.
12#[derive(Debug, Clone, Serialize, Deserialize, Default)]
13pub struct Config {
14    #[serde(default)]
15    pub default_profile: Option<String>,
16    #[serde(default)]
17    pub profiles: IndexMap<String, Profile>,
18}
19
20impl Config {
21    /// Load configuration from an explicit path.
22    pub fn load_from(path: &Path) -> Result<Self> {
23        Self::read(path)
24    }
25
26    /// Load configuration from the provided path or the resolved config file.
27    pub fn load<P: AsRef<Path>>(path: Option<P>) -> Result<Self> {
28        let path = match path {
29            Some(p) => p.as_ref().to_path_buf(),
30            None => ConfigPaths::resolve()?.config_file(),
31        };
32        Self::read(&path)
33    }
34
35    fn read(path: &Path) -> Result<Self> {
36        if !path.exists() {
37            return Ok(Config::default());
38        }
39
40        let raw = fs::read_to_string(path)
41            .with_context(|| format!("Unable to read config file at {}", path.display()))?;
42
43        yaml_serde::from_str(&raw)
44            .with_context(|| format!("Malformed YAML in config file {}", path.display()))
45    }
46
47    /// Persist the configuration to an explicit path.
48    ///
49    /// Written owner-only: a profile can carry a plaintext `api_token`, and this
50    /// used to land with whatever the umask allowed.
51    pub fn save_to(&self, path: &Path) -> Result<()> {
52        if let Some(parent) = path.parent() {
53            paths::create_private_dir(parent)?;
54        }
55
56        let serialized = yaml_serde::to_string(self)?;
57        paths::write_private(path, serialized.as_bytes())
58    }
59
60    /// Persist the configuration to the provided path or the resolved config file.
61    pub fn save<P: AsRef<Path>>(&self, path: Option<P>) -> Result<()> {
62        let path = match path {
63            Some(p) => p.as_ref().to_path_buf(),
64            None => ConfigPaths::resolve()?.config_file(),
65        };
66        self.save_to(&path)
67    }
68
69    /// Convenience helper to retrieve a profile by name.
70    pub fn profile(&self, name: &str) -> Option<&Profile> {
71        self.profiles.get(name)
72    }
73
74    /// Returns either the requested profile or falls back to the default one.
75    pub fn resolve_profile<'a>(
76        &'a self,
77        requested: Option<&'a str>,
78    ) -> Option<(&'a str, &'a Profile)> {
79        if let Some(name) = requested {
80            self.profiles.get(name).map(|profile| (name, profile))
81        } else if let Some(default_name) = self.default_profile.as_deref() {
82            self.profiles
83                .get(default_name)
84                .map(|profile| (default_name, profile))
85        } else if let Some((name, profile)) = self.profiles.iter().next() {
86            Some((name.as_str(), profile))
87        } else {
88            None
89        }
90    }
91}
92
93/// Minimal representation of a profile. Values are optional to support
94/// partially configured setups (e.g., when storing tokens in encrypted credential files).
95#[derive(Debug, Clone, Serialize, Deserialize, Default)]
96pub struct Profile {
97    pub base_url: Option<String>,
98    pub email: Option<String>,
99    pub api_token: Option<String>,
100    /// Bitbucket workspace slug (optional, can be inferred from base_url).
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub workspace: Option<String>,
103    /// Bitbucket token authentication type: "basic" (default) or "bearer".
104    /// Bearer is used for repository/workspace/project access tokens.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub bitbucket_token_type: Option<String>,
107    /// OpsGenie API key (optional, separate from Atlassian token).
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub opsgenie_api_key: Option<String>,
110    /// OpsGenie region: "us" or "eu" (defaults to "us").
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub opsgenie_region: Option<String>,
113    /// Bamboo base URL (optional, if different from main base_url).
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub bamboo_base_url: Option<String>,
116    /// Preferred git remote name for Bitbucket auto-detection (default: tries origin, then first Bitbucket remote).
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub bitbucket_remote: Option<String>,
119}
120
121/// The Confluence prefix, which belongs to the request path and not to the base.
122const WIKI_SUFFIX: &str = "/wiki";
123
124/// A site base URL with a trailing `/wiki` removed.
125///
126/// The API client appends request paths to the base rather than replacing the
127/// base's path, and every Confluence command spells `/wiki` itself while every
128/// Jira command spells `/rest/api/3`. So a profile stored as
129/// `https://site.atlassian.net/wiki` asked for `/wiki/wiki/api/v2/pages` and
130/// `/wiki/rest/api/3/issue/KEY`, and both 404. Writing `/wiki` into the base is
131/// an easy mistake to make, because it is how the Confluence REST documentation
132/// spells the full URL.
133///
134/// One `/wiki` segment is removed, not every repetition: a `/wiki/wiki` typo
135/// should lose one and stay visibly odd rather than silently becoming the site
136/// root. Trailing slashes are all removed first, so `/wiki//` is handled like
137/// `/wiki` instead of slipping through the suffix check.
138///
139/// The comparison ignores case, matching the product detection in
140/// `commands/auth.rs`, which lowercases before looking for the same segment.
141/// The two disagreeing would mean a `/WIKI` base detected as Confluence but not
142/// normalised, which is the doubling all over again.
143///
144/// Only for Jira, Confluence and JSM. Bamboo is a Server product where a context
145/// path in the base is legitimate, and it resolves its own base URL.
146pub fn site_base_url(base_url: &str) -> &str {
147    let trimmed = base_url.trim_end_matches('/');
148
149    let split = trimmed.len().saturating_sub(WIKI_SUFFIX.len());
150    if trimmed.len() >= WIKI_SUFFIX.len()
151        && trimmed.is_char_boundary(split)
152        && trimmed[split..].eq_ignore_ascii_case(WIKI_SUFFIX)
153    {
154        return &trimmed[..split];
155    }
156
157    trimmed
158}
159
160impl Profile {
161    /// `base_url` as the site root, for building a Jira, Confluence or JSM client.
162    ///
163    /// Callers that need to tell the two products apart must read `base_url`
164    /// itself: a trailing `/wiki` is the only hint a Confluence-only profile
165    /// gives, and this strips it.
166    pub fn site_base_url(&self) -> Option<&str> {
167        self.base_url.as_deref().map(site_base_url)
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    /// The shipped example config parses with the YAML crate in use. Guards the
176    /// serde_yaml to yaml_serde swap and any later one: comments, blank lines,
177    /// unquoted URLs and emails, nested maps.
178    #[test]
179    fn example_config_file_parses() {
180        let path = concat!(
181            env!("CARGO_MANIFEST_DIR"),
182            "/../../configs/config.example.yaml"
183        );
184        let raw = std::fs::read_to_string(path).expect("configs/config.example.yaml exists");
185        let config: Config = yaml_serde::from_str(&raw).expect("example config parses");
186        assert_eq!(config.default_profile.as_deref(), Some("personal"));
187        let personal = config.profiles.get("personal").expect("personal profile");
188        assert_eq!(
189            personal.base_url.as_deref(),
190            Some("https://example.atlassian.net")
191        );
192    }
193    use std::io::Write;
194    use tempfile::NamedTempFile;
195
196    #[test]
197    fn test_config_default() {
198        let config = Config::default();
199        assert!(config.default_profile.is_none());
200        assert!(config.profiles.is_empty());
201    }
202
203    #[test]
204    fn test_load_missing_file() {
205        let result = Config::load(Some("/nonexistent/config.yaml"));
206        assert!(result.is_ok());
207        let config = result.unwrap();
208        assert!(config.profiles.is_empty());
209    }
210
211    #[test]
212    fn test_save_and_load() {
213        let mut config = Config {
214            default_profile: Some("work".to_string()),
215            ..Default::default()
216        };
217
218        let profile = Profile {
219            base_url: Some("https://test.atlassian.net".to_string()),
220            email: Some("test@example.com".to_string()),
221            ..Default::default()
222        };
223
224        config.profiles.insert("work".to_string(), profile);
225
226        let temp_file = NamedTempFile::new().unwrap();
227        let temp_path = temp_file.path();
228
229        config.save(Some(temp_path)).unwrap();
230        let loaded = Config::load(Some(temp_path)).unwrap();
231
232        assert_eq!(loaded.default_profile, Some("work".to_string()));
233        assert_eq!(loaded.profiles.len(), 1);
234
235        let work_profile = loaded.profiles.get("work").unwrap();
236        assert_eq!(
237            work_profile.base_url,
238            Some("https://test.atlassian.net".to_string())
239        );
240        assert_eq!(work_profile.email, Some("test@example.com".to_string()));
241    }
242
243    #[test]
244    fn test_load_malformed_yaml() {
245        let mut temp_file = NamedTempFile::new().unwrap();
246        write!(temp_file, "invalid: yaml: [unclosed").unwrap();
247
248        let result = Config::load(Some(temp_file.path()));
249        assert!(result.is_err());
250        assert!(result.unwrap_err().to_string().contains("Malformed YAML"));
251    }
252
253    #[test]
254    fn test_profile_retrieval() {
255        let mut config = Config::default();
256        let profile = Profile {
257            base_url: Some("https://test.atlassian.net".to_string()),
258            ..Default::default()
259        };
260
261        config.profiles.insert("test".to_string(), profile);
262
263        assert!(config.profile("test").is_some());
264        assert!(config.profile("nonexistent").is_none());
265    }
266
267    #[test]
268    fn test_resolve_profile_requested() {
269        let mut config = Config {
270            default_profile: Some("default".to_string()),
271            ..Default::default()
272        };
273
274        let default_profile = Profile {
275            base_url: Some("https://default.atlassian.net".to_string()),
276            ..Default::default()
277        };
278        config
279            .profiles
280            .insert("default".to_string(), default_profile);
281
282        let work_profile = Profile {
283            base_url: Some("https://work.atlassian.net".to_string()),
284            ..Default::default()
285        };
286        config.profiles.insert("work".to_string(), work_profile);
287
288        let (name, profile) = config.resolve_profile(Some("work")).unwrap();
289        assert_eq!(name, "work");
290        assert_eq!(
291            profile.base_url,
292            Some("https://work.atlassian.net".to_string())
293        );
294    }
295
296    #[test]
297    fn test_resolve_profile_default() {
298        let mut config = Config {
299            default_profile: Some("default".to_string()),
300            ..Default::default()
301        };
302
303        let default_profile = Profile {
304            base_url: Some("https://default.atlassian.net".to_string()),
305            ..Default::default()
306        };
307        config
308            .profiles
309            .insert("default".to_string(), default_profile);
310
311        let (name, profile) = config.resolve_profile(None).unwrap();
312        assert_eq!(name, "default");
313        assert_eq!(
314            profile.base_url,
315            Some("https://default.atlassian.net".to_string())
316        );
317    }
318
319    #[test]
320    fn test_resolve_profile_first_available() {
321        let mut config = Config::default();
322
323        let profile = Profile {
324            base_url: Some("https://only.atlassian.net".to_string()),
325            ..Default::default()
326        };
327        config.profiles.insert("only".to_string(), profile);
328
329        let result = config.resolve_profile(None);
330        assert!(result.is_some());
331        let (name, profile) = result.unwrap();
332        assert_eq!(name, "only");
333        assert_eq!(
334            profile.base_url,
335            Some("https://only.atlassian.net".to_string())
336        );
337    }
338
339    #[test]
340    fn test_resolve_profile_none_available() {
341        let config = Config::default();
342        assert!(config.resolve_profile(None).is_none());
343    }
344
345    #[test]
346    fn test_resolve_profile_nonexistent_requested() {
347        let mut config = Config::default();
348
349        let profile = Profile {
350            base_url: Some("https://test.atlassian.net".to_string()),
351            ..Default::default()
352        };
353        config.profiles.insert("test".to_string(), profile);
354
355        assert!(config.resolve_profile(Some("nonexistent")).is_none());
356    }
357
358    #[test]
359    fn test_profile_default() {
360        let profile = Profile::default();
361        assert!(profile.base_url.is_none());
362        assert!(profile.email.is_none());
363        assert!(profile.api_token.is_none());
364    }
365
366    #[test]
367    fn test_indexmap_preserves_insertion_order() {
368        let mut config = Config::default();
369
370        // Insert profiles in specific order
371        let profile1 = Profile {
372            base_url: Some("https://first.atlassian.net".to_string()),
373            ..Default::default()
374        };
375        config.profiles.insert("first".to_string(), profile1);
376
377        let profile2 = Profile {
378            base_url: Some("https://second.atlassian.net".to_string()),
379            ..Default::default()
380        };
381        config.profiles.insert("second".to_string(), profile2);
382
383        let profile3 = Profile {
384            base_url: Some("https://third.atlassian.net".to_string()),
385            ..Default::default()
386        };
387        config.profiles.insert("third".to_string(), profile3);
388
389        // Verify iteration order matches insertion order
390        let names: Vec<_> = config.profiles.keys().map(|s| s.as_str()).collect();
391        assert_eq!(names, vec!["first", "second", "third"]);
392    }
393
394    #[test]
395    fn test_resolve_profile_first_available_is_deterministic() {
396        // When no default is set, resolve_profile should return the first profile
397        // consistently (not randomly based on HashMap iteration)
398        let mut config = Config::default();
399
400        // Add multiple profiles
401        config.profiles.insert(
402            "alpha".to_string(),
403            Profile {
404                base_url: Some("https://alpha.atlassian.net".to_string()),
405                ..Default::default()
406            },
407        );
408        config.profiles.insert(
409            "beta".to_string(),
410            Profile {
411                base_url: Some("https://beta.atlassian.net".to_string()),
412                ..Default::default()
413            },
414        );
415        config.profiles.insert(
416            "gamma".to_string(),
417            Profile {
418                base_url: Some("https://gamma.atlassian.net".to_string()),
419                ..Default::default()
420            },
421        );
422
423        // Resolve multiple times and verify we always get the same (first inserted) profile
424        for _ in 0..10 {
425            let (name, _) = config.resolve_profile(None).unwrap();
426            assert_eq!(
427                name, "alpha",
428                "First profile should always be selected deterministically"
429            );
430        }
431    }
432
433    #[test]
434    fn test_shift_remove_preserves_order() {
435        let mut config = Config::default();
436
437        config.profiles.insert("a".to_string(), Profile::default());
438        config.profiles.insert("b".to_string(), Profile::default());
439        config.profiles.insert("c".to_string(), Profile::default());
440
441        // Remove middle element
442        config.profiles.shift_remove("b");
443
444        let names: Vec<_> = config.profiles.keys().map(|s| s.as_str()).collect();
445        assert_eq!(
446            names,
447            vec!["a", "c"],
448            "Order should be preserved after removal"
449        );
450    }
451
452    #[test]
453    fn test_yaml_serialization() {
454        let mut config = Config {
455            default_profile: Some("prod".to_string()),
456            ..Default::default()
457        };
458
459        let profile = Profile {
460            base_url: Some("https://prod.atlassian.net".to_string()),
461            email: Some("admin@example.com".to_string()),
462            api_token: Some("secret-token-123".to_string()),
463            ..Default::default()
464        };
465
466        config.profiles.insert("prod".to_string(), profile);
467
468        let yaml = yaml_serde::to_string(&config).unwrap();
469
470        assert!(yaml.contains("default_profile: prod"));
471        assert!(yaml.contains("https://prod.atlassian.net"));
472        assert!(yaml.contains("admin@example.com"));
473        assert!(yaml.contains("secret-token-123"));
474
475        let deserialized: Config = yaml_serde::from_str(&yaml).unwrap();
476        assert_eq!(deserialized.default_profile, config.default_profile);
477        assert_eq!(deserialized.profiles.len(), 1);
478    }
479
480    #[test]
481    fn test_profile_bitbucket_token_type_default_none() {
482        let profile = Profile::default();
483        assert!(profile.bitbucket_token_type.is_none());
484    }
485
486    #[test]
487    fn test_profile_bitbucket_token_type_bearer() {
488        let profile = Profile {
489            bitbucket_token_type: Some("bearer".to_string()),
490            ..Default::default()
491        };
492        assert_eq!(profile.bitbucket_token_type.as_deref(), Some("bearer"));
493    }
494
495    #[test]
496    fn test_profile_bitbucket_token_type_skipped_when_none() {
497        // bitbucket_token_type should not appear in YAML when None
498        let profile = Profile {
499            email: Some("test@example.com".to_string()),
500            ..Default::default()
501        };
502        let yaml = yaml_serde::to_string(&profile).unwrap();
503        assert!(!yaml.contains("bitbucket_token_type"));
504    }
505
506    #[test]
507    fn test_profile_bitbucket_token_type_serialized_when_set() {
508        let profile = Profile {
509            email: Some("test@example.com".to_string()),
510            bitbucket_token_type: Some("bearer".to_string()),
511            ..Default::default()
512        };
513        let yaml = yaml_serde::to_string(&profile).unwrap();
514        assert!(yaml.contains("bitbucket_token_type: bearer"));
515    }
516
517    #[test]
518    fn test_profile_backwards_compat_missing_token_type() {
519        // Old config files without bitbucket_token_type should deserialize fine
520        let yaml = "email: test@example.com\nworkspace: myteam\n";
521        let profile: Profile = yaml_serde::from_str(yaml).unwrap();
522        assert!(profile.bitbucket_token_type.is_none());
523        assert_eq!(profile.email.as_deref(), Some("test@example.com"));
524        assert_eq!(profile.workspace.as_deref(), Some("myteam"));
525    }
526
527    #[test]
528    fn test_config_with_bearer_profile_roundtrip() {
529        let mut config = Config {
530            default_profile: Some("ci".to_string()),
531            ..Default::default()
532        };
533
534        let profile = Profile {
535            workspace: Some("myteam".to_string()),
536            bitbucket_token_type: Some("bearer".to_string()),
537            ..Default::default()
538        };
539        config.profiles.insert("ci".to_string(), profile);
540
541        let temp_file = NamedTempFile::new().unwrap();
542        config.save(Some(temp_file.path())).unwrap();
543        let loaded = Config::load(Some(temp_file.path())).unwrap();
544
545        let ci_profile = loaded.profiles.get("ci").unwrap();
546        assert_eq!(ci_profile.bitbucket_token_type.as_deref(), Some("bearer"));
547        assert_eq!(ci_profile.workspace.as_deref(), Some("myteam"));
548        // No email required for bearer profiles
549        assert!(ci_profile.email.is_none());
550    }
551
552    #[test]
553    fn a_trailing_wiki_is_stripped_from_a_site_base_url() {
554        assert_eq!(
555            site_base_url("https://site.atlassian.net/wiki"),
556            "https://site.atlassian.net"
557        );
558        assert_eq!(
559            site_base_url("https://site.atlassian.net/wiki/"),
560            "https://site.atlassian.net"
561        );
562    }
563
564    #[test]
565    fn a_site_root_is_left_alone() {
566        assert_eq!(
567            site_base_url("https://site.atlassian.net"),
568            "https://site.atlassian.net"
569        );
570        assert_eq!(
571            site_base_url("https://site.atlassian.net/"),
572            "https://site.atlassian.net"
573        );
574    }
575
576    /// The reason for `strip_suffix` over `trim_end_matches`: a word merely
577    /// ending in "wiki" is not the Confluence prefix.
578    #[test]
579    fn a_path_that_merely_ends_in_wiki_is_left_alone() {
580        assert_eq!(
581            site_base_url("https://example.com/mywiki"),
582            "https://example.com/mywiki"
583        );
584        assert_eq!(
585            site_base_url("https://wiki.example.com"),
586            "https://wiki.example.com"
587        );
588    }
589
590    /// One segment, not all of them, so a doubled typo stays visible rather
591    /// than silently resolving to the site root.
592    #[test]
593    fn only_one_wiki_segment_is_removed() {
594        assert_eq!(
595            site_base_url("https://site.atlassian.net/wiki/wiki"),
596            "https://site.atlassian.net/wiki"
597        );
598    }
599
600    /// Every trailing slash goes before the suffix is looked for. Stripping
601    /// only one left `/wiki//` unnormalised, so it still doubled while
602    /// `auth login` told the user the URL was fine.
603    #[test]
604    fn repeated_trailing_slashes_do_not_hide_the_suffix() {
605        assert_eq!(
606            site_base_url("https://site.atlassian.net/wiki//"),
607            "https://site.atlassian.net"
608        );
609        assert_eq!(
610            site_base_url("https://site.atlassian.net//"),
611            "https://site.atlassian.net"
612        );
613    }
614
615    /// Product detection lowercases before looking for the same segment. If
616    /// this did not, a `/WIKI` base would be called Confluence and left
617    /// unnormalised, which is the doubling again.
618    #[test]
619    fn the_suffix_match_ignores_case() {
620        assert_eq!(
621            site_base_url("https://site.atlassian.net/WIKI"),
622            "https://site.atlassian.net"
623        );
624        assert_eq!(
625            site_base_url("https://site.atlassian.net/Wiki/"),
626            "https://site.atlassian.net"
627        );
628    }
629
630    /// Degenerate input reduces to an empty string rather than panicking on a
631    /// slice boundary; `ApiClient::new` then reports it as an unparseable URL.
632    #[test]
633    fn degenerate_input_does_not_panic() {
634        assert_eq!(site_base_url("/wiki"), "");
635        assert_eq!(site_base_url(""), "");
636        assert_eq!(site_base_url("/"), "");
637        assert_eq!(site_base_url("wiki"), "wiki");
638        // Multi-byte, to prove the boundary guard is doing something.
639        assert_eq!(site_base_url("https://x/päge"), "https://x/päge");
640    }
641
642    /// The OAuth gateway form, which the Confluence REST docs spell with the
643    /// `/wiki` already attached.
644    #[test]
645    fn the_gateway_form_reduces_to_its_cloud_id_root() {
646        assert_eq!(
647            site_base_url("https://api.atlassian.com/ex/confluence/cloud-id/wiki"),
648            "https://api.atlassian.com/ex/confluence/cloud-id"
649        );
650        assert_eq!(
651            site_base_url("https://api.atlassian.com/ex/jira/cloud-id"),
652            "https://api.atlassian.com/ex/jira/cloud-id"
653        );
654    }
655
656    /// Bamboo resolves its own base and never calls this, but a context path
657    /// must survive if it ever does.
658    #[test]
659    fn an_unrelated_context_path_survives() {
660        assert_eq!(
661            site_base_url("https://example.com/bamboo"),
662            "https://example.com/bamboo"
663        );
664    }
665
666    #[test]
667    fn the_profile_accessor_follows_the_same_rule() {
668        let profile = Profile {
669            base_url: Some("https://site.atlassian.net/wiki/".to_string()),
670            ..Default::default()
671        };
672        assert_eq!(profile.site_base_url(), Some("https://site.atlassian.net"));
673
674        assert_eq!(Profile::default().site_base_url(), None);
675    }
676}