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#[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 pub fn load_from(path: &Path) -> Result<Self> {
23 Self::read(path)
24 }
25
26 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 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 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 pub fn profile(&self, name: &str) -> Option<&Profile> {
71 self.profiles.get(name)
72 }
73
74 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub workspace: Option<String>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub bitbucket_token_type: Option<String>,
107 #[serde(default, skip_serializing_if = "Option::is_none")]
109 pub opsgenie_api_key: Option<String>,
110 #[serde(default, skip_serializing_if = "Option::is_none")]
112 pub opsgenie_region: Option<String>,
113 #[serde(default, skip_serializing_if = "Option::is_none")]
115 pub bamboo_base_url: Option<String>,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub bitbucket_remote: Option<String>,
119}
120
121const WIKI_SUFFIX: &str = "/wiki";
123
124pub 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 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 #[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 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 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 let mut config = Config::default();
399
400 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 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 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 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 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 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 #[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 #[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 #[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 #[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 #[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 assert_eq!(site_base_url("https://x/päge"), "https://x/päge");
640 }
641
642 #[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 #[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}