figue 4.0.3

Type-safe CLI arguments, config files, and environment variables powered by Facet reflection
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
//! Tests for unknown configuration key handling.
//!
//! These tests verify that:
//! 1. Unknown keys produce helpful error messages (showing valid keys)
//! 2. --help works even when there are unknown keys in config/env
//! 3. `--config /path/to/file` is NOT silently ignored
//!
//! Bug report scenario:
//! - User has env vars like APP__AUTH__EMAIL_FROM set
//! - User runs `myapp --help`
//! - Expected: help text
//! - Actual: "Error: unknown configuration key: auth.email_from" (x8)

use facet::Facet;
use figue::{self as args, Driver, FigueBuiltins, MockEnv, builder};

/// Server configuration for testing unknown keys.
#[derive(Facet, Debug)]
struct Args {
    /// Server configuration (from file/env)
    #[facet(args::config, args::env_prefix = "APP")]
    config: ServerConfig,

    /// Standard CLI options
    #[facet(flatten)]
    builtins: FigueBuiltins,
}

/// Server configuration loaded from config file or environment.
#[derive(Facet, Debug)]
struct ServerConfig {
    /// The host to bind to
    #[facet(default = "localhost")]
    host: String,

    /// The port to listen on
    #[facet(default = 8080)]
    port: u16,

    /// Magic link URL for auth
    #[facet(default)]
    magic_link: Option<String>,
}

// ============================================================================
// Bug #2: --help should work even with unknown keys (env strict mode)
// This is the exact scenario from the bug report
// ============================================================================

#[test]
fn test_help_works_with_unknown_env_keys_strict() {
    // User has unknown env vars set AND passes --help
    // This is the exact scenario from the bug report:
    // - env vars like APP__AUTH__EMAIL_FROM are set (unknown keys)
    // - user runs `reef --help`
    // - expected: help text
    // - actual (bug): wall of "Error: unknown configuration key" messages
    let env = MockEnv::from_pairs([
        ("APP__AUTH__EMAIL_FROM", "noreply@example.com"),
        ("APP__AUTH__MAGIC_LINK_BASE_URL", "https://example.com"),
        ("APP__AUTH__RP_ID", "example.com"),
        ("APP__AUTH__RP_NAME", "Example"),
        ("APP__AUTH__RP_ORIGIN", "https://example.com"),
        ("APP__AUTH__SMTP_HOST", "smtp.example.com"),
        ("APP__AUTH__SMTP_PASSWORD", "secret"),
        ("APP__AUTH__SMTP_USERNAME", "user"),
    ]);

    let config = builder::<Args>()
        .unwrap()
        .cli(|cli| cli.args(["--help"]).strict())
        .env(|e| e.source(env).strict())
        .build();

    let driver = Driver::new(config);
    let result = driver.run();

    // Bug #2: This should return Help, not Failed
    assert!(
        result.is_err(),
        "should be an error (Help is returned as error)"
    );
    let err = result.unwrap_err();
    assert!(
        err.is_help(),
        "should be a Help error, not a parsing error. Got: {}",
        err
    );

    let help = err.help_text().expect("should have help text");
    assert!(
        help.contains("--[no-]help"),
        "help text should contain --[no-]help"
    );
}

#[test]
fn test_help_short_flag_works_with_unknown_env_keys_strict() {
    // Same test but with -h instead of --help
    let env = MockEnv::from_pairs([("APP__UNKNOWN_FIELD", "value")]);

    let config = builder::<Args>()
        .unwrap()
        .cli(|cli| cli.args(["-h"]).strict())
        .env(|e| e.source(env).strict())
        .build();

    let driver = Driver::new(config);
    let result = driver.run();

    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        err.is_help(),
        "should be a Help error with -h flag. Got: {}",
        err
    );
}

#[test]
fn test_help_works_with_unknown_file_keys_strict() {
    // Config file has unknown keys AND user passes --help
    let config_json = r#"{
        "config": {
            "auth": {
                "email_from": "noreply@example.com"
            }
        }
    }"#;

    let config = builder::<Args>()
        .unwrap()
        .cli(|cli| cli.args(["--help"]).strict())
        .file(|f| f.content(config_json, "config.json").strict())
        .build();

    let driver = Driver::new(config);
    let result = driver.run();

    // Bug #2: This should return Help, not Failed
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        err.is_help(),
        "should be a Help error, not a parsing error. Got: {}",
        err
    );
}

// ============================================================================
// Bug #1: Unknown keys should produce helpful error messages
// ============================================================================

#[test]
fn test_unknown_key_in_env_strict_mode_shows_valid_fields() {
    // User sets an unknown env var (APP__AUTH__EMAIL_FROM doesn't exist)
    // Error should tell them what fields ARE valid, not just say "unknown key"
    let env = MockEnv::from_pairs([
        ("APP__AUTH__EMAIL_FROM", "noreply@example.com"),
        ("APP__AUTH__SMTP_HOST", "smtp.example.com"),
    ]);

    let config = builder::<Args>()
        .unwrap()
        .cli(|cli| cli.args::<[&str; 0], _>([]).strict())
        .env(|e| e.source(env).strict())
        .build();

    let driver = Driver::new(config);
    let err = driver.run().unwrap_err();
    let err_str = err.to_string();

    // The error should mention the unknown key
    assert!(
        err_str.contains("auth.email_from")
            || err_str.contains("AUTH__EMAIL_FROM")
            || err_str.contains("unknown"),
        "error should mention the unknown key, got: {}",
        err_str
    );

    // Bug #1: The error should show what fields ARE valid
    // Currently it just says "unknown configuration key: auth.email_from"
    // It should list valid fields like: host, port, magic_link
    // OR at minimum show the user they can run --help for more info
    assert!(
        err_str.contains("host")
            || err_str.contains("port")
            || err_str.contains("magic_link")
            || err_str.contains("--help")
            || err_str.contains("Valid"),
        "error should show valid fields or suggest --help, got: {}",
        err_str
    );
}

#[test]
fn test_unknown_key_in_file_strict_mode_shows_valid_fields() {
    // Config file has unknown keys
    let config_json = r#"{
        "config": {
            "auth": {
                "email_from": "noreply@example.com",
                "rp_id": "example.com"
            }
        }
    }"#;

    let config = builder::<Args>()
        .unwrap()
        .cli(|cli| cli.args::<[&str; 0], _>([]).strict())
        .file(|f| f.content(config_json, "config.json").strict())
        .build();

    let driver = Driver::new(config);
    let err = driver.run().unwrap_err();
    let err_str = err.to_string();

    // Error should show valid fields via dump, suggest --help
    assert!(
        err_str.contains("host")
            || err_str.contains("port")
            || err_str.contains("magic_link")
            || err_str.contains("--help")
            || err_str.contains("Valid"),
        "error should show valid fields or suggest --help, got: {}",
        err_str
    );
}

// ============================================================================
// Bug #3: --<config-field-name> <path> should not be silently ignored
//
// The CLI flag name comes from the effective name of the field with args::config.
// - Field named `config` -> `--config <path>`
// - Field named `settings` -> `--settings <path>`
// - Field with `#[facet(rename = "cfg")]` -> `--cfg <path>`
// ============================================================================

/// Args with a config field named "config" -> expects --config <path>
#[derive(Facet, Debug)]
struct ArgsWithConfigField {
    #[facet(args::config, args::env_prefix = "APP")]
    config: ServerConfig,

    #[facet(flatten)]
    builtins: FigueBuiltins,
}

/// Args with a config field named "settings" -> expects --settings <path>
#[derive(Facet, Debug)]
struct ArgsWithSettingsField {
    #[facet(args::config, args::env_prefix = "APP")]
    settings: ServerConfig,

    #[facet(flatten)]
    builtins: FigueBuiltins,
}

/// Args with a renamed config field -> expects --cfg <path>
#[derive(Facet, Debug)]
struct ArgsWithRenamedConfigField {
    #[facet(args::config, args::env_prefix = "APP", rename = "cfg")]
    config: ServerConfig,

    #[facet(flatten)]
    builtins: FigueBuiltins,
}

/// Args with a config root flattened into the top-level CLI namespace.
#[derive(Facet, Debug)]
struct ArgsWithFlattenedConfigRoot {
    #[facet(args::config, args::env_prefix = "APP_RUN")]
    #[facet(flatten)]
    run: RunConfig,

    #[facet(flatten)]
    builtins: FigueBuiltins,
}

#[derive(Facet, Debug)]
struct RunConfig {
    #[facet(default = "default-model")]
    model: String,

    #[facet(default)]
    tui: bool,
}

#[test]
fn test_config_path_flag_not_silently_ignored() {
    // User passes --config /path/to/file.json
    // This should NOT be silently ignored - it should either:
    // 1. Load the file and use it as config, OR
    // 2. Report an error (unknown flag, file not found, etc.)
    //
    // Currently it's silently ignored, which is the bug.
    let config = builder::<ArgsWithConfigField>()
        .unwrap()
        .cli(|cli| cli.args(["--config", "/etc/app/config.json"]).strict())
        .build();

    let driver = Driver::new(config);
    let result = driver.run();

    // The result should NOT silently succeed with defaults
    // It should either use the file or error
    match result.into_result() {
        Ok(output) => {
            // If it succeeds, it means the file was loaded (or all fields have defaults)
            // For this test, we want to verify the flag wasn't ignored
            // Since we didn't set up a file layer, this is actually a bug
            panic!(
                "--config flag was silently ignored! Got success with defaults: {:?}",
                output.value
            );
        }
        Err(err) => {
            // An error is acceptable - it means the flag was recognized
            // (e.g., "file not found" or "unknown flag" would both be fine)
            let err_str = err.to_string();
            // But it should NOT be "unknown flag: --config" in strict mode
            // because --config should be a recognized flag for the config field
            assert!(
                !err_str.contains("unknown flag: --config"),
                "--config should be recognized as the config file path flag, got: {}",
                err_str
            );
        }
    }
}

#[test]
fn test_settings_path_flag_not_silently_ignored() {
    // Same test but with field named "settings" -> --settings <path>
    let config = builder::<ArgsWithSettingsField>()
        .unwrap()
        .cli(|cli| cli.args(["--settings", "/etc/app/settings.json"]).strict())
        .build();

    let driver = Driver::new(config);
    let result = driver.run();

    match result.into_result() {
        Ok(output) => {
            panic!(
                "--settings flag was silently ignored! Got success with defaults: {:?}",
                output.value
            );
        }
        Err(err) => {
            let err_str = err.to_string();
            assert!(
                !err_str.contains("unknown flag: --settings"),
                "--settings should be recognized as the config file path flag, got: {}",
                err_str
            );
        }
    }
}

#[test]
fn test_renamed_config_path_flag_not_silently_ignored() {
    // Same test but with renamed field -> --cfg <path>
    let config = builder::<ArgsWithRenamedConfigField>()
        .unwrap()
        .cli(|cli| cli.args(["--cfg", "/etc/app/config.json"]).strict())
        .build();

    let driver = Driver::new(config);
    let result = driver.run();

    match result.into_result() {
        Ok(output) => {
            panic!(
                "--cfg flag was silently ignored! Got success with defaults: {:?}",
                output.value
            );
        }
        Err(err) => {
            let err_str = err.to_string();
            assert!(
                !err_str.contains("unknown flag: --cfg"),
                "--cfg should be recognized as the config file path flag, got: {}",
                err_str
            );
        }
    }
}

#[test]
fn test_unknown_cli_config_override_errors_without_strict_mode() {
    let config = builder::<ArgsWithRenamedConfigField>()
        .unwrap()
        .cli(|cli| cli.args(["--cfg.does-not-exist", "yolo"]))
        .build();

    let err = Driver::new(config).run().unwrap_err();
    let err_str = err.to_string();

    assert!(
        err_str.contains("unknown flag: --cfg.does-not-exist"),
        "unknown config override should be a CLI parse error, got: {}",
        err_str
    );
}

#[test]
fn test_kebab_case_cli_config_override_is_accepted() {
    let config = builder::<ArgsWithRenamedConfigField>()
        .unwrap()
        .cli(|cli| cli.args(["--cfg.magic-link", "https://example.com/login"]))
        .build();

    let args = Driver::new(config).run().unwrap();

    assert_eq!(
        args.config.magic_link.as_deref(),
        Some("https://example.com/login")
    );
}

#[test]
fn test_unknown_flattened_config_root_flag_errors_without_strict_mode() {
    let config = builder::<ArgsWithFlattenedConfigRoot>()
        .unwrap()
        .cli(|cli| cli.args(["--does-not-exist", "yolo"]))
        .build();

    let err = Driver::new(config).run().unwrap_err();
    let err_str = err.to_string();

    assert!(
        err_str.contains("unknown flag: --does-not-exist"),
        "unknown flattened config root flag should be a CLI parse error, got: {}",
        err_str
    );
}

#[test]
fn test_unknown_namespaced_flattened_config_root_override_errors_without_strict_mode() {
    let config = builder::<ArgsWithFlattenedConfigRoot>()
        .unwrap()
        .cli(|cli| cli.args(["--run.does-not-exist", "yolo"]))
        .build();

    let err = Driver::new(config).run().unwrap_err();
    let err_str = err.to_string();

    assert!(
        err_str.contains("unknown flag: --run.does-not-exist"),
        "unknown namespaced flattened config root override should be a CLI parse error, got: {}",
        err_str
    );
}