cli-engine 0.3.3

Rust CLI framework for consistent command modules
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
//! First-class environment definitions and layered resolution.
//!
//! An [`Environments`] value holds compiled-in environment definitions and,
//! optionally, an `environments.toml` file plus `<ENV>_*` env-var overrides.
//! Resolving a name merges those layers (later wins) into an [`Environment`].

use std::collections::BTreeMap;

use serde::Deserialize;

use crate::{Result, error::CliCoreError};

/// Standard OAuth slice of an environment, consumed by `PkceAuthProvider`.
///
/// `auth_url`, `token_url`, and `scopes` may be empty when a layer set only
/// `client_id`. Consumers should treat empty endpoint strings as "fall back to
/// the provider's default base endpoints".
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct OAuthConfig {
    /// OAuth client id.
    pub client_id: String,
    /// Authorization endpoint.
    pub auth_url: String,
    /// Token endpoint.
    pub token_url: String,
    /// Default scopes.
    pub scopes: Vec<String>,
}

/// A fully-resolved environment.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Environment {
    /// Environment name (e.g. `prod`).
    pub name: String,
    /// OAuth configuration, present when the environment participates in OAuth.
    pub oauth: Option<OAuthConfig>,
    /// App-specific fields (for example `api_url`).
    pub extra: BTreeMap<String, String>,
}

/// An unresolved per-environment declaration (one layer of configuration).
///
/// Fields are optional so layers can override individual values during
/// resolution. The same shape parses the `environments.toml` file.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct EnvironmentDef {
    #[serde(default)]
    client_id: Option<String>,
    #[serde(default)]
    auth_url: Option<String>,
    #[serde(default)]
    token_url: Option<String>,
    #[serde(default)]
    scopes: Option<Vec<String>>,
    /// Everything not recognised above is captured here (app-specific fields).
    #[serde(flatten, default)]
    extra: BTreeMap<String, String>,
}

impl EnvironmentDef {
    /// Creates an empty declaration; every field falls back to lower layers.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the OAuth client id.
    #[must_use]
    pub fn with_client_id(mut self, value: impl Into<String>) -> Self {
        self.client_id = Some(value.into());
        self
    }

    /// Sets the authorization endpoint.
    #[must_use]
    pub fn with_auth_url(mut self, value: impl Into<String>) -> Self {
        self.auth_url = Some(value.into());
        self
    }

    /// Sets the token endpoint.
    #[must_use]
    pub fn with_token_url(mut self, value: impl Into<String>) -> Self {
        self.token_url = Some(value.into());
        self
    }

    /// Sets the default scopes.
    #[must_use]
    pub fn with_scopes(mut self, scopes: &[impl AsRef<str>]) -> Self {
        self.scopes = Some(scopes.iter().map(|s| s.as_ref().to_owned()).collect());
        self
    }

    /// Sets an app-specific bag field.
    #[must_use]
    pub fn with_field(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra.insert(key.into(), value.into());
        self
    }
}

/// Engine-owned environment system: definitions + resolution + active-env state.
#[derive(Clone, Debug)]
pub struct Environments {
    default: String,
    defs: BTreeMap<String, EnvironmentDef>,
    use_config_file: bool,
    app_id: String,
    file_path_override: Option<std::path::PathBuf>,
}

impl Environments {
    /// Creates an environment system with the given default environment name.
    #[must_use]
    pub fn new(default_env: impl Into<String>) -> Self {
        Self {
            default: default_env.into(),
            defs: BTreeMap::new(),
            use_config_file: false,
            app_id: String::new(),
            file_path_override: None,
        }
    }

    /// Registers (or replaces) a compiled-in environment definition.
    #[must_use]
    pub fn with_environment(mut self, name: impl Into<String>, def: EnvironmentDef) -> Self {
        self.defs.insert(name.into(), def);
        self
    }

    /// Enables loading `<config-dir>/<app_id>/environments.toml` during resolution.
    #[must_use]
    pub fn with_config_file(mut self, enabled: bool) -> Self {
        self.use_config_file = enabled;
        self
    }

    /// Sets the application id used to locate the config file.
    ///
    /// The consumer must set this to the same `app_id` passed to
    /// [`CliConfig::new`](crate::CliConfig::new) before sharing the
    /// [`Environments`] with both
    /// [`CliConfig::with_environments`](crate::CliConfig::with_environments) and
    /// `PkceAuthProvider::with_environments` (with the `pkce-auth` feature),
    /// or [`config_file_path`](Self::config_file_path) returns `None` and the
    /// `environments.toml` file layer silently resolves empty.
    #[must_use]
    pub fn with_app_id(mut self, app_id: impl Into<String>) -> Self {
        self.app_id = app_id.into();
        self
    }

    /// Test/advanced seam: force the environments file path.
    #[must_use]
    pub fn with_config_file_path_override(mut self, path: std::path::PathBuf) -> Self {
        self.file_path_override = Some(path);
        self.use_config_file = true;
        self
    }

    /// The default environment name.
    #[must_use]
    pub fn default_env(&self) -> &str {
        &self.default
    }

    /// Enumerable environment names (compiled-in + file-defined), sorted.
    ///
    /// Any error from reading or parsing the environments file (missing file,
    /// permission/read error, or malformed TOML) is silently swallowed and only
    /// the compiled-in names are returned. Use [`resolve`](Self::resolve) when
    /// you need those errors surfaced; a fallible listing variant can be added
    /// later if needed.
    ///
    /// # Blocking
    ///
    /// When the config-file layer is enabled, this performs synchronous
    /// filesystem I/O to read and parse `environments.toml` (like
    /// [`resolve`](Self::resolve)). Avoid calling it repeatedly on a
    /// latency-sensitive async path.
    #[must_use]
    pub fn list(&self) -> Vec<String> {
        let mut names: std::collections::BTreeSet<String> = self.defs.keys().cloned().collect();
        if let Ok(file) = self.file_defs() {
            names.extend(file.into_keys());
        }
        names.into_iter().collect()
    }

    /// Resolves `name` by merging compiled defaults, the config file,
    /// and `<ENV>_*` env-var overrides (later wins) into an [`Environment`].
    ///
    /// When only `client_id` was set on the matching layer(s), the returned
    /// [`Environment`]'s `oauth.auth_url` / `oauth.token_url` will be empty
    /// strings. Consumers should treat empty endpoint strings as "fall back to
    /// the provider's default base endpoints".
    ///
    /// # Blocking
    ///
    /// When the config-file layer is enabled (via
    /// [`with_config_file`](Self::with_config_file)), this performs synchronous
    /// filesystem I/O to read and parse `environments.toml`. Resolve the
    /// environment once at startup (or off the latency-sensitive path) rather
    /// than calling it per request inside an async handler.
    ///
    /// # Errors
    ///
    /// Returns an error when `name` is not known to any layer or when the
    /// environments file exists but cannot be read or parsed.
    pub fn resolve(&self, name: &str) -> Result<Environment> {
        let compiled = self.defs.get(name);
        // Parse the file once; reuse for both membership check and merge.
        let mut all_file_defs = self.file_defs()?;
        let file = all_file_defs.remove(name);
        if compiled.is_none() && file.is_none() {
            let mut known: std::collections::BTreeSet<String> = self.defs.keys().cloned().collect();
            known.extend(all_file_defs.into_keys());
            let known_list: Vec<String> = known.into_iter().collect();
            let known_display = if known_list.is_empty() {
                "(none defined)".to_owned()
            } else {
                known_list.join(", ")
            };
            return Err(CliCoreError::message(format!(
                "unknown environment {name:?}; known: {known_display}"
            )));
        }
        let mut merged = EnvironmentDef::default();
        if let Some(def) = compiled {
            merge_into(&mut merged, def);
        }
        if let Some(def) = &file {
            merge_into(&mut merged, def);
        }
        apply_env_vars(name, &mut merged);
        Ok(finalize(name, merged))
    }

    /// Path to `environments.toml` next to the engine config file, or `None`
    /// when the file layer is disabled or the config dir cannot be determined.
    #[must_use]
    pub fn config_file_path(&self) -> Option<std::path::PathBuf> {
        if !self.use_config_file {
            return None;
        }
        let config = crate::config::config_file_path(&self.app_id)?;
        Some(config.with_file_name("environments.toml"))
    }

    fn effective_file_path(&self) -> Option<std::path::PathBuf> {
        if let Some(path) = &self.file_path_override {
            return Some(path.clone());
        }
        self.config_file_path()
    }

    /// Parses the environments file into a name -> def map. Missing file = empty.
    fn file_defs(&self) -> Result<BTreeMap<String, EnvironmentDef>> {
        let Some(path) = self.effective_file_path() else {
            return Ok(BTreeMap::new());
        };
        let text = match std::fs::read_to_string(&path) {
            Ok(text) => text,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
            Err(err) => {
                return Err(CliCoreError::message(format!(
                    "reading environments file {path:?}: {err}"
                )));
            }
        };
        toml_edit::de::from_str::<BTreeMap<String, EnvironmentDef>>(&text).map_err(|err| {
            CliCoreError::message(format!("parsing environments file {path:?}: {err}"))
        })
    }

    /// Config-file key under which the sticky active environment is stored.
    pub(crate) const ACTIVE_ENV_KEY: &'static str = "environment.active";

    /// Reads the persisted active environment from a loaded config file.
    #[must_use]
    pub fn active_from_config(config: &crate::config::ConfigFile) -> Option<String> {
        config.get(Self::ACTIVE_ENV_KEY)
    }

    /// Resolves the active environment name with precedence:
    /// explicit `--env` override > persisted active > configured default.
    #[must_use]
    pub fn effective_active(
        &self,
        flag: Option<&str>,
        config: &crate::config::ConfigFile,
    ) -> String {
        flag.map(ToOwned::to_owned)
            .or_else(|| Self::active_from_config(config))
            .unwrap_or_else(|| self.default.clone())
    }

    /// Persists `name` as the active environment (loads, sets, saves a fresh
    /// config file for `app_id`). Validates that `name` resolves first.
    ///
    /// # Errors
    ///
    /// Returns an error when `name` does not resolve to a known environment, or
    /// when the config file cannot be written.
    pub fn persist_active(&self, name: &str) -> Result<()> {
        self.resolve(name)?; // reject unknown names
        // Persisting writes the engine config file, which is keyed by app_id.
        // Validate it up front so a missing/invalid app_id yields a clear,
        // actionable error rather than a misleading "no config path" failure
        // from ConfigFile::save() that points at XDG/HOME.
        if crate::config::config_file_path(&self.app_id).is_none() {
            return Err(CliCoreError::message(format!(
                "cannot persist active environment {name:?}: the environment system has no usable app_id; \
                 set one via Environments::with_app_id (matching the CliConfig app_id)"
            )));
        }
        let mut config = crate::config::ConfigFile::load(&self.app_id);
        config.set(Self::ACTIVE_ENV_KEY, name)?;
        config.save()
    }
}

/// Merges `src` into `dst`, with `src` winning on any field it sets.
fn merge_into(dst: &mut EnvironmentDef, src: &EnvironmentDef) {
    if src.client_id.is_some() {
        dst.client_id = src.client_id.clone();
    }
    if src.auth_url.is_some() {
        dst.auth_url = src.auth_url.clone();
    }
    if src.token_url.is_some() {
        dst.token_url = src.token_url.clone();
    }
    if src.scopes.is_some() {
        dst.scopes = src.scopes.clone();
    }
    for (k, v) in &src.extra {
        dst.extra.insert(k.clone(), v.clone());
    }
}

/// Applies `<ENV>_*` overrides: the three OAuth fields always, and any bag key
/// already present in the merged record (keyed `<ENV>_<KEY>`).
///
/// The prefix is `name.to_uppercase().replace('-', "_")`, so environment names
/// that differ only by `-` vs `_` map to the same prefix and will collide.
///
/// Scopes are intentionally not env-var overridable; set them via the
/// compiled-in layer or the `environments.toml` file.
fn apply_env_vars(name: &str, def: &mut EnvironmentDef) {
    let prefix = name.to_uppercase().replace('-', "_");
    if let Ok(v) = std::env::var(format!("{prefix}_OAUTH_CLIENT_ID")) {
        def.client_id = Some(v);
    }
    if let Ok(v) = std::env::var(format!("{prefix}_OAUTH_AUTH_URL")) {
        def.auth_url = Some(v);
    }
    if let Ok(v) = std::env::var(format!("{prefix}_OAUTH_TOKEN_URL")) {
        def.token_url = Some(v);
    }
    let keys: Vec<String> = def.extra.keys().cloned().collect();
    for key in keys {
        let var = format!("{prefix}_{}", key.to_uppercase().replace('-', "_"));
        if let Ok(v) = std::env::var(&var) {
            def.extra.insert(key, v);
        }
    }
}

/// Turns a fully-merged declaration into a resolved [`Environment`]. OAuth is
/// present when a client id was set by any layer.
fn finalize(name: &str, def: EnvironmentDef) -> Environment {
    let EnvironmentDef {
        client_id,
        auth_url,
        token_url,
        scopes,
        extra,
    } = def;
    let oauth = client_id.map(|id| OAuthConfig {
        client_id: id,
        auth_url: auth_url.unwrap_or_default(),
        token_url: token_url.unwrap_or_default(),
        scopes: scopes.unwrap_or_default(),
    });
    Environment {
        name: name.to_owned(),
        oauth,
        extra,
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, unsafe_code)]
mod tests {
    use super::*;

    use std::sync::Mutex;
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    /// RAII guard that removes an env var on drop, even if a test panics.
    struct EnvGuard(&'static str);
    impl Drop for EnvGuard {
        fn drop(&mut self) {
            // SAFETY: test holds ENV_LOCK; clean up on any exit including panic.
            unsafe { std::env::remove_var(self.0) }
        }
    }

    fn sample() -> Environments {
        Environments::new("prod")
            .with_environment(
                "prod",
                EnvironmentDef::new()
                    .with_client_id("prod-client")
                    .with_auth_url("https://api.example.com/authorize")
                    .with_token_url("https://api.example.com/token")
                    .with_scopes(&["openid"])
                    .with_field("api_url", "https://api.example.com"),
            )
            .with_environment("dev", EnvironmentDef::new().with_client_id("dev-client"))
    }

    #[test]
    fn oauth_config_defaults_are_empty() {
        let c = OAuthConfig::default();
        assert!(c.client_id.is_empty() && c.scopes.is_empty());
    }

    /// With no environments defined at all, the unknown-env error renders a
    /// readable placeholder instead of a dangling `known: `.
    #[test]
    fn resolve_unknown_env_with_no_defs_uses_placeholder() {
        let err = Environments::new("prod")
            .resolve("prod")
            .expect_err("nothing defined should fail");
        let message = err.to_string();
        assert!(
            message.contains("(none defined)"),
            "expected placeholder, got: {message}"
        );
    }

    /// `persist_active` without an `app_id` returns a clear, actionable error
    /// (mentioning `app_id`) rather than a misleading config-path failure.
    #[test]
    fn persist_active_without_app_id_errors_clearly() {
        let err = sample()
            .persist_active("prod")
            .expect_err("persist without app_id should fail");
        let message = err.to_string();
        assert!(
            message.contains("app_id"),
            "error should mention app_id, got: {message}"
        );
    }

    #[test]
    fn builder_registers_compiled_environment() {
        let envs = Environments::new("prod").with_environment(
            "prod",
            EnvironmentDef::new()
                .with_client_id("prod-client")
                .with_auth_url("https://api.example.com/authorize")
                .with_token_url("https://api.example.com/token")
                .with_scopes(&["openid"])
                .with_field("api_url", "https://api.example.com"),
        );
        assert_eq!(envs.default_env(), "prod");
        assert_eq!(envs.list(), vec!["prod".to_owned()]);
    }

    #[test]
    fn resolve_returns_compiled_record() {
        let _g = ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let env = sample().resolve("prod").expect("prod resolves");
        let oauth = env.oauth.expect("oauth present");
        assert_eq!(oauth.client_id, "prod-client");
        assert_eq!(oauth.scopes, vec!["openid".to_owned()]);
        assert_eq!(
            env.extra.get("api_url").map(String::as_str),
            Some("https://api.example.com")
        );
    }

    #[test]
    fn resolve_unknown_env_errors_with_known_names() {
        let _g = ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let err = sample().resolve("nope").unwrap_err().to_string();
        assert!(err.contains("nope"));
        assert!(err.contains("prod") && err.contains("dev"));
    }

    #[test]
    fn resolve_with_only_client_id_yields_partial_oauth() {
        let _g = ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let envs = Environments::new("dev")
            .with_environment("dev", EnvironmentDef::new().with_client_id("dev-only"));
        let env = envs.resolve("dev").expect("dev resolves");
        let oauth = env.oauth.expect("oauth present when client_id is set");
        assert_eq!(oauth.client_id, "dev-only");
        assert!(
            oauth.auth_url.is_empty(),
            "auth_url should be empty (fall back to provider default)"
        );
        assert!(
            oauth.token_url.is_empty(),
            "token_url should be empty (fall back to provider default)"
        );
        assert!(oauth.scopes.is_empty());
    }

    #[test]
    fn env_var_layer_overrides_oauth_and_known_bag_keys() {
        let _g = ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        // SAFETY: serialized by ENV_LOCK; guards remove vars on any exit incl. panic.
        unsafe { std::env::set_var("PROD_OAUTH_CLIENT_ID", "override-client") };
        let _g1 = EnvGuard("PROD_OAUTH_CLIENT_ID");
        unsafe { std::env::set_var("PROD_API_URL", "https://api.override.example.com") };
        let _g2 = EnvGuard("PROD_API_URL");

        let env = sample().resolve("prod").expect("prod resolves");
        assert_eq!(env.oauth.unwrap().client_id, "override-client");
        assert_eq!(
            env.extra.get("api_url").map(String::as_str),
            Some("https://api.override.example.com")
        );
    }

    #[test]
    fn environments_file_path_sits_next_to_config() {
        let envs = sample().with_app_id("gddy").with_config_file(true);
        let path = envs.config_file_path().expect("path resolves with app id");
        assert!(path.ends_with("gddy/environments.toml"), "got {path:?}");
    }

    #[test]
    fn file_layer_overrides_compiled_and_adds_custom_env() {
        let _g = ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let dir = tempfile::tempdir().expect("tempdir");
        let file = dir.path().join("environments.toml");
        std::fs::write(
            &file,
            r#"
[prod]
client_id = "file-client"

[custom]
client_id = "custom-client"
api_url = "https://api.custom.example.com"
"#,
        )
        .expect("write file");

        let envs = sample()
            .with_config_file(true)
            .with_config_file_path_override(file);

        // File overrides the compiled prod client id, keeps compiled api_url.
        let prod = envs.resolve("prod").expect("prod");
        assert_eq!(prod.oauth.unwrap().client_id, "file-client");
        assert_eq!(
            prod.extra.get("api_url").map(String::as_str),
            Some("https://api.example.com")
        );

        // Custom env exists only in the file.
        let custom = envs.resolve("custom").expect("custom");
        assert_eq!(custom.oauth.unwrap().client_id, "custom-client");
        assert!(envs.list().contains(&"custom".to_owned()));
    }

    const ACTIVE_KEY: &str = "environment.active";

    #[test]
    fn active_env_round_trips_through_config_file() {
        use crate::config::ConfigFile;
        let mut cfg = ConfigFile::default();
        assert_eq!(Environments::active_from_config(&cfg), None);

        cfg.set(ACTIVE_KEY, "ote").expect("set");
        assert_eq!(
            Environments::active_from_config(&cfg).as_deref(),
            Some("ote")
        );
    }

    #[test]
    fn effective_active_prefers_override_then_config_then_default() {
        use crate::config::ConfigFile;
        let envs = sample();
        let mut cfg = ConfigFile::default();
        cfg.set(ACTIVE_KEY, "dev").expect("set");

        assert_eq!(envs.effective_active(Some("prod"), &cfg), "prod"); // explicit wins
        assert_eq!(envs.effective_active(None, &cfg), "dev"); // config next
        let empty = ConfigFile::default();
        assert_eq!(envs.effective_active(None, &empty), "prod"); // default last
    }
}