xbp 10.17.1

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! configuration management module
//!
//! handles ssh configuration and yaml config file management
//! provides loading and saving of configuration files
//! supports home directory based config storage

use serde::{Deserialize, Serialize};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone)]
pub struct GlobalXbpPaths {
    pub root_dir: PathBuf,
    pub config_file: PathBuf,
    pub ssh_dir: PathBuf,
    pub cache_dir: PathBuf,
    pub logs_dir: PathBuf,
    pub versioning_files_file: PathBuf,
    pub package_name_files_file: PathBuf,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SshConfig {
    pub password: Option<String>,
    pub username: Option<String>,
    pub host: Option<String>,
    pub project_dir: Option<String>,
    pub openrouter_api_key: Option<String>,
    pub github_oauth2_key: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecretProvider {
    OpenRouter,
    Github,
}

impl SecretProvider {
    pub fn from_key(key: &str) -> Option<Self> {
        match key.trim().to_ascii_lowercase().as_str() {
            "openrouter" => Some(Self::OpenRouter),
            "github" => Some(Self::Github),
            _ => None,
        }
    }

    pub fn as_key(&self) -> &'static str {
        match self {
            SecretProvider::OpenRouter => "openrouter",
            SecretProvider::Github => "github",
        }
    }

    pub fn config_field(&self) -> &'static str {
        match self {
            SecretProvider::OpenRouter => "openrouter_api_key",
            SecretProvider::Github => "github_oauth2_key",
        }
    }
}

impl Default for SshConfig {
    fn default() -> Self {
        Self::new()
    }
}

impl SshConfig {
    pub fn new() -> Self {
        SshConfig {
            password: None,
            username: None,
            host: None,
            project_dir: None,
            openrouter_api_key: None,
            github_oauth2_key: None,
        }
    }

    pub fn get_secret(&self, provider: SecretProvider) -> Option<&str> {
        match provider {
            SecretProvider::OpenRouter => self.openrouter_api_key.as_deref(),
            SecretProvider::Github => self.github_oauth2_key.as_deref(),
        }
    }

    pub fn set_secret(&mut self, provider: SecretProvider, value: Option<String>) {
        match provider {
            SecretProvider::OpenRouter => self.openrouter_api_key = value,
            SecretProvider::Github => self.github_oauth2_key = value,
        }
    }

    pub fn load() -> Result<Self, String> {
        let config_path = get_config_path();
        let legacy_path = legacy_config_path();
        let path_to_read = if config_path.exists() {
            config_path
        } else if legacy_path.exists() {
            legacy_path
        } else {
            return Ok(SshConfig::new());
        };

        let content = fs::read_to_string(&path_to_read)
            .map_err(|e| format!("Failed to read config file: {}", e))?;
        serde_yaml::from_str(&content).map_err(|e| format!("Failed to parse config file: {}", e))
    }

    pub fn save(&self) -> Result<(), String> {
        let config_path = get_config_path();
        let config_dir = config_path.parent().ok_or("Invalid config path")?;
        fs::create_dir_all(config_dir)
            .map_err(|e| format!("Failed to create config directory: {}", e))?;

        let content = serde_yaml::to_string(self)
            .map_err(|e| format!("Failed to serialize config: {}", e))?;
        fs::write(&config_path, content).map_err(|e| format!("Failed to write config file: {}", e))
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VersioningFilesConfig {
    #[serde(default = "default_versioning_files")]
    pub files: Vec<String>,
}

impl Default for VersioningFilesConfig {
    fn default() -> Self {
        Self {
            files: default_versioning_files(),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct PackageNameLookup {
    pub file: String,
    pub format: String,
    pub key: String,
    pub registry: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PackageNameFilesConfig {
    #[serde(default = "default_package_name_lookups")]
    pub lookups: Vec<PackageNameLookup>,
}

impl Default for PackageNameFilesConfig {
    fn default() -> Self {
        Self {
            lookups: default_package_name_lookups(),
        }
    }
}

pub fn ensure_global_xbp_paths() -> Result<GlobalXbpPaths, String> {
    let root_dir = preferred_global_root_dir();

    let paths = GlobalXbpPaths {
        config_file: root_dir.join("config.yaml"),
        ssh_dir: root_dir.join("ssh"),
        cache_dir: root_dir.join("cache"),
        logs_dir: root_dir.join("logs"),
        versioning_files_file: root_dir.join("versioning-files.yaml"),
        package_name_files_file: root_dir.join("package-name-files.yaml"),
        root_dir,
    };

    for dir in [
        &paths.root_dir,
        &paths.ssh_dir,
        &paths.cache_dir,
        &paths.logs_dir,
    ] {
        fs::create_dir_all(dir)
            .map_err(|e| format!("Failed to create XBP directory {}: {}", dir.display(), e))?;
    }

    maybe_migrate_legacy_windows_files(&paths)?;

    if !paths.config_file.exists() {
        fs::write(
            &paths.config_file,
            "password: null\nusername: null\nhost: null\nproject_dir: null\nopenrouter_api_key: null\ngithub_oauth2_key: null\n",
        )
        .map_err(|e| {
            format!(
                "Failed to initialize config file {}: {}",
                paths.config_file.display(),
                e
            )
        })?;
    }

    sync_versioning_files_registry_at(&paths.versioning_files_file)?;
    sync_package_name_files_registry_at(&paths.package_name_files_file)?;

    Ok(paths)
}

pub fn resolve_openrouter_api_key() -> Option<String> {
    env::var("OPENROUTER_API_KEY")
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
        .or_else(|| {
            SshConfig::load()
                .ok()
                .and_then(|cfg| {
                    cfg.get_secret(SecretProvider::OpenRouter)
                        .map(str::to_string)
                })
                .map(|value| value.trim().to_string())
                .filter(|value| !value.is_empty())
        })
}

pub fn resolve_github_oauth2_key() -> Option<String> {
    for env_var in [
        "GITHUB_TOKEN",
        "GITHUB_OAUTH2_KEY",
        "GITHUB_OAUTH2_TOKEN",
        "GITHUB_OAUTH_TOKEN",
    ] {
        if let Ok(value) = env::var(env_var) {
            let token = value.trim();
            if !token.is_empty() {
                return Some(token.to_string());
            }
        }
    }

    SshConfig::load()
        .ok()
        .and_then(|cfg| cfg.get_secret(SecretProvider::Github).map(str::to_string))
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

pub fn global_xbp_paths() -> Result<GlobalXbpPaths, String> {
    ensure_global_xbp_paths()
}

pub fn get_config_path() -> PathBuf {
    ensure_global_xbp_paths()
        .map(|paths| paths.config_file)
        .unwrap_or_else(|_| legacy_config_path())
}

#[cfg(target_os = "windows")]
fn legacy_config_path() -> PathBuf {
    dirs::config_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("xbp")
        .join("config.yaml")
}

#[cfg(not(target_os = "windows"))]
fn legacy_config_path() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".xbp")
        .join("config.yaml")
}

#[cfg(target_os = "windows")]
fn preferred_global_root_dir() -> PathBuf {
    let fallback = dirs::config_dir()
        .or_else(|| dirs::home_dir().map(|home| home.join(".config")))
        .unwrap_or_else(|| PathBuf::from("."))
        .join("xbp");

    let Some(home_dir) = resolve_windows_home_dir() else {
        return fallback;
    };
    let c_drive = Path::new(r"C:\");

    // Prefer C:\...\.xbp when that profile path is valid; otherwise use the real profile path.
    if c_drive.exists() {
        if windows_drive_letter(&home_dir) == Some('C') {
            return home_dir.join(".xbp");
        }

        if let Some(relative_profile_path) = windows_path_without_drive(&home_dir) {
            let c_profile_candidate = c_drive.join(relative_profile_path);
            if c_profile_candidate.exists() {
                return c_profile_candidate.join(".xbp");
            }
        }
    }

    home_dir.join(".xbp")
}

#[cfg(not(target_os = "windows"))]
fn preferred_global_root_dir() -> PathBuf {
    dirs::config_dir()
        .or_else(|| dirs::home_dir().map(|home| home.join(".config")))
        .unwrap_or_else(|| PathBuf::from("."))
        .join("xbp")
}

#[cfg(target_os = "windows")]
fn resolve_windows_home_dir() -> Option<PathBuf> {
    dirs::home_dir()
        .or_else(|| env::var_os("USERPROFILE").map(PathBuf::from))
        .or_else(|| {
            let drive = env::var_os("HOMEDRIVE")?;
            let path = env::var_os("HOMEPATH")?;
            Some(PathBuf::from(drive).join(path))
        })
}

#[cfg(target_os = "windows")]
fn windows_drive_letter(path: &Path) -> Option<char> {
    let normalized = path.to_string_lossy().replace('/', "\\");
    let bytes = normalized.as_bytes();
    if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
        Some((bytes[0] as char).to_ascii_uppercase())
    } else {
        None
    }
}

#[cfg(target_os = "windows")]
fn windows_path_without_drive(path: &Path) -> Option<PathBuf> {
    let normalized = path.to_string_lossy().replace('/', "\\");
    let bytes = normalized.as_bytes();
    if bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'\\' {
        let tail = &normalized[3..];
        if tail.is_empty() {
            Some(PathBuf::new())
        } else {
            Some(PathBuf::from(tail))
        }
    } else {
        None
    }
}

#[cfg(target_os = "windows")]
fn maybe_migrate_legacy_windows_files(paths: &GlobalXbpPaths) -> Result<(), String> {
    let Some(legacy_root) = dirs::config_dir().map(|dir| dir.join("xbp")) else {
        return Ok(());
    };

    migrate_legacy_windows_file_if_missing(&legacy_root.join("config.yaml"), &paths.config_file)?;
    migrate_legacy_windows_file_if_missing(
        &legacy_root.join("versioning-files.yaml"),
        &paths.versioning_files_file,
    )?;
    migrate_legacy_windows_file_if_missing(
        &legacy_root.join("package-name-files.yaml"),
        &paths.package_name_files_file,
    )?;

    Ok(())
}

#[cfg(not(target_os = "windows"))]
fn maybe_migrate_legacy_windows_files(_paths: &GlobalXbpPaths) -> Result<(), String> {
    Ok(())
}

#[cfg(target_os = "windows")]
fn migrate_legacy_windows_file_if_missing(from: &Path, to: &Path) -> Result<(), String> {
    if to.exists() || !from.exists() {
        return Ok(());
    }

    if let Some(parent) = to.parent() {
        fs::create_dir_all(parent).map_err(|e| {
            format!(
                "Failed to create directory for migrated file {}: {}",
                parent.display(),
                e
            )
        })?;
    }

    fs::copy(from, to).map_err(|e| {
        format!(
            "Failed to migrate legacy config file {} -> {}: {}",
            from.display(),
            to.display(),
            e
        )
    })?;

    Ok(())
}

pub fn describe_global_xbp_paths() -> Result<Vec<(String, PathBuf)>, String> {
    let paths = global_xbp_paths()?;
    Ok(vec![
        ("root".to_string(), paths.root_dir),
        ("config".to_string(), paths.config_file),
        ("ssh".to_string(), paths.ssh_dir),
        ("cache".to_string(), paths.cache_dir),
        ("logs".to_string(), paths.logs_dir),
        ("versioning".to_string(), paths.versioning_files_file),
        ("package-names".to_string(), paths.package_name_files_file),
    ])
}

pub fn sync_versioning_files_registry() -> Result<PathBuf, String> {
    let paths = ensure_global_xbp_paths()?;
    Ok(paths.versioning_files_file)
}

pub fn load_versioning_files_registry() -> Result<Vec<String>, String> {
    let registry_path = sync_versioning_files_registry()?;
    let content = fs::read_to_string(&registry_path).map_err(|e| {
        format!(
            "Failed to read versioning registry {}: {}",
            registry_path.display(),
            e
        )
    })?;

    let config: VersioningFilesConfig = serde_yaml::from_str(&content)
        .map_err(|e| format!("Failed to parse versioning registry: {}", e))?;

    Ok(config.files)
}

pub fn sync_package_name_files_registry() -> Result<PathBuf, String> {
    let paths = ensure_global_xbp_paths()?;
    Ok(paths.package_name_files_file)
}

pub fn load_package_name_files_registry() -> Result<Vec<PackageNameLookup>, String> {
    let registry_path = sync_package_name_files_registry()?;
    let content = fs::read_to_string(&registry_path).map_err(|e| {
        format!(
            "Failed to read package-name registry {}: {}",
            registry_path.display(),
            e
        )
    })?;

    let config: PackageNameFilesConfig = serde_yaml::from_str(&content)
        .map_err(|e| format!("Failed to parse package-name registry: {}", e))?;

    Ok(config.lookups)
}

fn sync_versioning_files_registry_at(path: &PathBuf) -> Result<(), String> {
    let mut config = if path.exists() {
        let content = fs::read_to_string(path).map_err(|e| {
            format!(
                "Failed to read versioning registry {}: {}",
                path.display(),
                e
            )
        })?;
        serde_yaml::from_str::<VersioningFilesConfig>(&content)
            .unwrap_or_else(|_| VersioningFilesConfig::default())
    } else {
        VersioningFilesConfig::default()
    };

    let mut changed = false;
    for default_file in default_versioning_files() {
        if !config
            .files
            .iter()
            .any(|existing| existing == &default_file)
        {
            config.files.push(default_file);
            changed = true;
        }
    }

    if changed || !path.exists() {
        let content = serde_yaml::to_string(&config)
            .map_err(|e| format!("Failed to serialize versioning registry: {}", e))?;
        fs::write(path, content).map_err(|e| {
            format!(
                "Failed to write versioning registry {}: {}",
                path.display(),
                e
            )
        })?;
    }

    Ok(())
}

fn sync_package_name_files_registry_at(path: &PathBuf) -> Result<(), String> {
    let mut config = if path.exists() {
        let content = fs::read_to_string(path).map_err(|e| {
            format!(
                "Failed to read package-name registry {}: {}",
                path.display(),
                e
            )
        })?;
        serde_yaml::from_str::<PackageNameFilesConfig>(&content)
            .unwrap_or_else(|_| PackageNameFilesConfig::default())
    } else {
        PackageNameFilesConfig::default()
    };

    let mut changed = false;
    for default_lookup in default_package_name_lookups() {
        if !config
            .lookups
            .iter()
            .any(|existing| existing == &default_lookup)
        {
            config.lookups.push(default_lookup);
            changed = true;
        }
    }

    if changed || !path.exists() {
        let content = serde_yaml::to_string(&config)
            .map_err(|e| format!("Failed to serialize package-name registry: {}", e))?;
        fs::write(path, content).map_err(|e| {
            format!(
                "Failed to write package-name registry {}: {}",
                path.display(),
                e
            )
        })?;
    }

    Ok(())
}

fn default_versioning_files() -> Vec<String> {
    vec![
        "README.md".to_string(),
        "openapi.yaml".to_string(),
        "openapi.yml".to_string(),
        "package.json".to_string(),
        "package-lock.json".to_string(),
        "Cargo.toml".to_string(),
        "Cargo.lock".to_string(),
        "pyproject.toml".to_string(),
        "composer.json".to_string(),
        "deno.json".to_string(),
        "deno.jsonc".to_string(),
        "Chart.yaml".to_string(),
        "app.json".to_string(),
        "manifest.json".to_string(),
        "pom.xml".to_string(),
        "build.gradle".to_string(),
        "build.gradle.kts".to_string(),
        "mix.exs".to_string(),
        "xbp.yaml".to_string(),
        "xbp.yml".to_string(),
        "xbp.json".to_string(),
        ".xbp/xbp.json".to_string(),
        ".xbp/xbp.yaml".to_string(),
        ".xbp/xbp.yml".to_string(),
    ]
}

fn default_package_name_lookups() -> Vec<PackageNameLookup> {
    vec![
        PackageNameLookup {
            file: "package.json".to_string(),
            format: "json".to_string(),
            key: "name".to_string(),
            registry: "npm".to_string(),
        },
        PackageNameLookup {
            file: "Cargo.toml".to_string(),
            format: "toml".to_string(),
            key: "package.name".to_string(),
            registry: "crates.io".to_string(),
        },
    ]
}

const DEFAULT_API_XBP_URL: &str = "https://api.xbp.app";

/// Simple API configuration for the XBP version endpoints.
#[derive(Debug, Clone)]
pub struct ApiConfig {
    base_url: String,
}

impl ApiConfig {
    /// Load the API configuration from API_XBP_URL, falling back to the default.
    pub fn load() -> Self {
        let raw_url = env::var("API_XBP_URL").unwrap_or_else(|_| DEFAULT_API_XBP_URL.to_string());
        let base_url = Self::normalize_base_url(&raw_url);
        ApiConfig { base_url }
    }

    /// Return the normalized base URL that downstream callers should use.
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Build the version query endpoint.
    pub fn version_endpoint(&self, project_name: &str) -> String {
        format!("{}/version?project_name={}", self.base_url, project_name)
    }

    /// Build the endpoint that increments a version.
    pub fn increment_endpoint(&self) -> String {
        format!("{}/version/increment", self.base_url)
    }

    fn normalize_base_url(raw: &str) -> String {
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            return DEFAULT_API_XBP_URL.to_string();
        }

        let trimmed = trimmed.trim_end_matches('/');
        if trimmed.is_empty() {
            return DEFAULT_API_XBP_URL.to_string();
        }

        trimmed.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::{
        default_package_name_lookups, default_versioning_files, resolve_github_oauth2_key,
        resolve_openrouter_api_key, sync_package_name_files_registry_at,
        sync_versioning_files_registry_at, ApiConfig, PackageNameFilesConfig, SecretProvider,
        SshConfig, VersioningFilesConfig,
    };
    use std::fs;
    use std::path::PathBuf;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_path(label: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos();
        std::env::temp_dir().join(format!("xbp-config-{}-{}.yaml", label, nanos))
    }

    #[test]
    fn versioning_registry_defaults_include_core_files() {
        let defaults = default_versioning_files();
        assert!(defaults.contains(&"README.md".to_string()));
        assert!(defaults.contains(&"Cargo.toml".to_string()));
        assert!(defaults.contains(&".xbp/xbp.yaml".to_string()));
    }

    #[test]
    fn versioning_registry_default_config_populates_files() {
        let config = VersioningFilesConfig::default();
        assert!(!config.files.is_empty());
    }

    #[test]
    fn versioning_registry_defaults_do_not_contain_duplicates() {
        let defaults = default_versioning_files();
        let mut deduped = defaults.clone();
        deduped.sort();
        deduped.dedup();
        assert_eq!(defaults.len(), deduped.len());
    }

    #[test]
    fn syncing_registry_creates_file_with_defaults() {
        let path = temp_path("defaults");
        sync_versioning_files_registry_at(&path).expect("sync");

        let content = fs::read_to_string(&path).expect("read");
        assert!(content.contains("README.md"));
        assert!(content.contains("Cargo.toml"));

        let _ = fs::remove_file(path);
    }

    #[test]
    fn syncing_registry_preserves_user_added_entries() {
        let path = temp_path("preserve");
        fs::write(&path, "files:\n  - custom.file\n").expect("write registry");

        sync_versioning_files_registry_at(&path).expect("sync");

        let content = fs::read_to_string(&path).expect("read");
        assert!(content.contains("custom.file"));
        assert!(content.contains("README.md"));

        let _ = fs::remove_file(path);
    }

    #[test]
    fn api_config_normalizes_trailing_slashes() {
        assert_eq!(
            ApiConfig::normalize_base_url("https://api.xbp.app///"),
            "https://api.xbp.app".to_string()
        );
    }

    #[test]
    fn api_config_uses_default_for_blank_values() {
        assert_eq!(
            ApiConfig::normalize_base_url("   "),
            "https://api.xbp.app".to_string()
        );
    }

    #[test]
    fn api_config_builds_version_endpoints() {
        let config = ApiConfig {
            base_url: "https://api.test.xbp".to_string(),
        };
        let endpoint = config.version_endpoint("demo");
        let increment = config.increment_endpoint();

        assert_eq!(endpoint, "https://api.test.xbp/version?project_name=demo");
        assert_eq!(increment, "https://api.test.xbp/version/increment");
    }

    #[test]
    fn package_lookup_defaults_include_npm_and_crates() {
        let defaults = default_package_name_lookups();
        assert!(defaults.iter().any(|entry| {
            entry.file == "package.json" && entry.registry == "npm" && entry.key == "name"
        }));
        assert!(defaults.iter().any(|entry| {
            entry.file == "Cargo.toml"
                && entry.registry == "crates.io"
                && entry.key == "package.name"
        }));
    }

    #[test]
    fn package_lookup_default_config_populates_entries() {
        let config = PackageNameFilesConfig::default();
        assert!(!config.lookups.is_empty());
    }

    #[test]
    fn syncing_package_lookup_registry_creates_defaults() {
        let path = temp_path("package-lookup-defaults");
        sync_package_name_files_registry_at(&path).expect("sync");

        let content = fs::read_to_string(&path).expect("read");
        assert!(content.contains("package.json"));
        assert!(content.contains("Cargo.toml"));

        let _ = fs::remove_file(path);
    }

    #[test]
    fn syncing_package_lookup_registry_preserves_custom_entries() {
        let path = temp_path("package-lookup-custom");
        fs::write(
            &path,
            "lookups:\n  - file: custom.yaml\n    format: yaml\n    key: app.name\n    registry: npm\n",
        )
        .expect("write package lookup registry");

        sync_package_name_files_registry_at(&path).expect("sync");
        let content = fs::read_to_string(&path).expect("read");
        assert!(content.contains("custom.yaml"));
        assert!(content.contains("package.json"));

        let _ = fs::remove_file(path);
    }

    #[test]
    fn secret_provider_parses_supported_keys() {
        assert_eq!(
            SecretProvider::from_key("openrouter"),
            Some(SecretProvider::OpenRouter)
        );
        assert_eq!(
            SecretProvider::from_key("github"),
            Some(SecretProvider::Github)
        );
        assert_eq!(SecretProvider::from_key("unknown"), None);
    }

    #[test]
    fn ssh_config_secret_get_set_roundtrip() {
        let mut cfg = SshConfig::new();
        cfg.set_secret(SecretProvider::OpenRouter, Some("or-test-123".to_string()));
        cfg.set_secret(SecretProvider::Github, Some("gho_test_456".to_string()));

        assert_eq!(
            cfg.get_secret(SecretProvider::OpenRouter),
            Some("or-test-123")
        );
        assert_eq!(cfg.get_secret(SecretProvider::Github), Some("gho_test_456"));
    }

    #[test]
    fn resolve_secret_prefers_environment_value() {
        std::env::set_var("OPENROUTER_API_KEY", "env-openrouter");
        std::env::set_var("GITHUB_TOKEN", "env-github");

        assert_eq!(
            resolve_openrouter_api_key(),
            Some("env-openrouter".to_string())
        );
        assert_eq!(resolve_github_oauth2_key(), Some("env-github".to_string()));

        std::env::remove_var("OPENROUTER_API_KEY");
        std::env::remove_var("GITHUB_TOKEN");
    }
}