clapfig 0.16.0

Rich, layered configuration for Rust CLI apps
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
//! Config operations: template generation, key lookup, listing, and result types.
//!
//! Provides the logic behind `config list`, `config gen`, `config get`, and the
//! `ConfigResult` enum that callers use to display results.

use std::fmt;
use std::path::{Path, PathBuf};

use confique::Config;
use serde::Serialize;

use crate::error::ClapfigError;

/// Result of a config operation. Returned to the caller for display.
#[derive(Debug, Clone, PartialEq)]
pub enum ConfigResult {
    /// A generated TOML template string.
    Template(String),
    /// Confirmation that a template was written to a file.
    TemplateWritten { path: PathBuf },
    /// A generated JSON Schema document (already serialized).
    Schema(String),
    /// Confirmation that a JSON Schema document was written to a file.
    SchemaWritten { path: PathBuf },
    /// A key's resolved value and its doc comment.
    KeyValue {
        key: String,
        value: String,
        doc: Vec<String>,
    },
    /// Confirmation that a value was persisted.
    ValueSet { key: String, value: String },
    /// Confirmation that a value was removed.
    ValueUnset { key: String },
    /// All resolved configuration key-value pairs.
    Listing { entries: Vec<(String, String)> },
}

impl fmt::Display for ConfigResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConfigResult::Template(t) => write!(f, "{t}"),
            ConfigResult::TemplateWritten { path } => {
                write!(f, "Config template written to {}", path.display())
            }
            ConfigResult::Schema(s) => write!(f, "{s}"),
            ConfigResult::SchemaWritten { path } => {
                write!(f, "Config schema written to {}", path.display())
            }
            ConfigResult::KeyValue { key, value, doc } => {
                for line in doc {
                    writeln!(f, "# {line}")?;
                }
                write!(f, "{key} = {value}")
            }
            ConfigResult::ValueSet { key, value } => write!(f, "Set {key} = {value}"),
            ConfigResult::ValueUnset { key } => write!(f, "Unset {key}"),
            ConfigResult::Listing { entries } => {
                for (i, (key, value)) in entries.iter().enumerate() {
                    if i > 0 {
                        writeln!(f)?;
                    }
                    write!(f, "{key} = {value}")?;
                }
                Ok(())
            }
        }
    }
}

/// Generate a commented TOML template from the config struct's doc comments.
pub fn generate_template<C: Config>() -> String {
    confique::toml::template::<C>(confique::toml::FormatOptions::default())
}

/// Generate a JSON Schema document (pretty-printed) describing the config struct.
///
/// Delegates to [`crate::schema::generate_schema`] and serializes the result.
/// Serialization of a `serde_json::Value` is infallible for the shapes this
/// module produces, so we propagate any panic rather than masking it with a
/// bogus "{}" payload.
pub fn generate_schema_string<C: Config>() -> String {
    let value = crate::schema::generate_schema::<C>();
    serde_json::to_string_pretty(&value).expect("serde_json::Value serialization is infallible")
}

/// Get a config value by dotted key, including its doc comment.
pub fn get_value<C: Config + Serialize>(
    config: &C,
    key: &str,
) -> Result<ConfigResult, ClapfigError> {
    let toml_value = toml::Value::try_from(config).map_err(|e| ClapfigError::InvalidValue {
        key: key.into(),
        reason: e.to_string(),
    })?;

    let table = toml_value
        .as_table()
        .ok_or_else(|| ClapfigError::InvalidValue {
            key: key.into(),
            reason: "config did not serialize to a table".into(),
        })?;

    let value = table_get(table, key).ok_or_else(|| ClapfigError::KeyNotFound(key.into()))?;

    let value_str = format_value(value);
    let doc = lookup_doc(&C::META, key);

    Ok(ConfigResult::KeyValue {
        key: key.into(),
        value: value_str,
        doc,
    })
}

/// List all resolved config values as flattened dotted key-value pairs.
pub fn list_values<C: Config + Serialize>(config: &C) -> Result<ConfigResult, ClapfigError> {
    let pairs = crate::flatten::flatten(config).map_err(|e| ClapfigError::InvalidValue {
        key: "<list>".into(),
        reason: e.to_string(),
    })?;

    let entries: Vec<(String, String)> = pairs
        .into_iter()
        .map(|(key, value)| {
            let display = match value {
                Some(v) => format_value(&v),
                None => "<not set>".to_string(),
            };
            (key, display)
        })
        .collect();

    Ok(ConfigResult::Listing { entries })
}

/// List entries from a single scope's config file (raw file content, not merged).
///
/// If the file does not exist, returns an empty listing.
pub fn list_scope_file(file_path: &Path) -> Result<ConfigResult, ClapfigError> {
    let content = match std::fs::read_to_string(file_path) {
        Ok(c) => c,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Ok(ConfigResult::Listing {
                entries: Vec::new(),
            });
        }
        Err(e) => {
            return Err(ClapfigError::IoError {
                path: file_path.to_path_buf(),
                source: e,
            });
        }
    };

    let table: toml::Table =
        content
            .parse()
            .map_err(|e: toml::de::Error| ClapfigError::ParseError {
                path: file_path.to_path_buf(),
                source: Box::new(e),
                source_text: Some(std::sync::Arc::from(content.as_str())),
            })?;

    let mut entries = Vec::new();
    flatten_toml_table(&table, "", &mut entries);

    Ok(ConfigResult::Listing { entries })
}

/// Get a value from a single scope's config file by dotted key.
///
/// Returns the raw value from the file, plus doc comments from the config struct's
/// metadata. Returns `KeyNotFound` if the key is not present in the file.
pub fn get_scope_value<C: Config>(
    file_path: &Path,
    key: &str,
) -> Result<ConfigResult, ClapfigError> {
    let content = match std::fs::read_to_string(file_path) {
        Ok(c) => c,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(ClapfigError::KeyNotFound(key.into()));
        }
        Err(e) => {
            return Err(ClapfigError::IoError {
                path: file_path.to_path_buf(),
                source: e,
            });
        }
    };

    let table: toml::Table =
        content
            .parse()
            .map_err(|e: toml::de::Error| ClapfigError::ParseError {
                path: file_path.to_path_buf(),
                source: Box::new(e),
                source_text: Some(std::sync::Arc::from(content.as_str())),
            })?;

    let value = table_get(&table, key).ok_or_else(|| ClapfigError::KeyNotFound(key.into()))?;
    let value_str = format_value(value);
    let doc = lookup_doc(&C::META, key);

    Ok(ConfigResult::KeyValue {
        key: key.into(),
        value: value_str,
        doc,
    })
}

/// Recursively flatten a TOML table into dotted key-value pairs.
fn flatten_toml_table(table: &toml::Table, prefix: &str, entries: &mut Vec<(String, String)>) {
    for (key, value) in table {
        let full_key = if prefix.is_empty() {
            key.clone()
        } else {
            format!("{prefix}.{key}")
        };
        match value {
            toml::Value::Table(t) => flatten_toml_table(t, &full_key, entries),
            _ => entries.push((full_key, format_value(value))),
        }
    }
}

/// Navigate a `toml::Table` by dotted key path (e.g. `"database.url"`).
pub fn table_get<'a>(table: &'a toml::Table, dotted_key: &str) -> Option<&'a toml::Value> {
    let (path, leaf) = match dotted_key.rsplit_once('.') {
        Some((p, l)) => (Some(p), l),
        None => (None, dotted_key),
    };

    let tbl = match path {
        Some(path) => {
            let mut current = table;
            for segment in path.split('.') {
                current = current.get(segment)?.as_table()?;
            }
            current
        }
        None => table,
    };

    tbl.get(leaf)
}

/// Format a TOML value for display.
fn format_value(value: &toml::Value) -> String {
    match value {
        toml::Value::String(s) => s.clone(),
        toml::Value::Integer(i) => i.to_string(),
        toml::Value::Float(f) => f.to_string(),
        toml::Value::Boolean(b) => b.to_string(),
        toml::Value::Array(a) => toml::to_string(&a).unwrap_or_else(|_| format!("{a:?}")),
        toml::Value::Table(t) => toml::to_string(&t).unwrap_or_else(|_| format!("{t:?}")),
        _ => format!("{value:?}"),
    }
}

/// Walk confique's `Meta` tree to find the doc comment for a dotted key path.
fn lookup_doc(meta: &confique::meta::Meta, dotted_key: &str) -> Vec<String> {
    let segments: Vec<&str> = dotted_key.split('.').collect();
    lookup_doc_recursive(meta, &segments)
}

fn lookup_doc_recursive(meta: &confique::meta::Meta, segments: &[&str]) -> Vec<String> {
    if segments.is_empty() {
        return vec![];
    }

    for field in meta.fields {
        if field.name == segments[0] {
            if segments.len() == 1 {
                return field.doc.iter().map(|s| s.to_string()).collect();
            }
            if let confique::meta::FieldKind::Nested { meta: nested, .. } = &field.kind {
                return lookup_doc_recursive(nested, &segments[1..]);
            }
        }
    }
    vec![]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fixtures::test::TestConfig;

    fn test_config() -> TestConfig {
        TestConfig::builder().load().unwrap()
    }

    #[test]
    fn generate_template_contains_keys() {
        let template = generate_template::<TestConfig>();
        assert!(template.contains("host"));
        assert!(template.contains("port"));
        assert!(template.contains("database"));
        assert!(template.contains("pool_size"));
    }

    #[test]
    fn generate_template_contains_doc_comments() {
        let template = generate_template::<TestConfig>();
        assert!(template.contains("application host"));
        assert!(template.contains("port number"));
    }

    #[test]
    fn get_flat_key() {
        let config = test_config();
        let result = get_value::<TestConfig>(&config, "port").unwrap();
        match result {
            ConfigResult::KeyValue { value, .. } => assert_eq!(value, "8080"),
            other => panic!("Expected KeyValue, got {other:?}"),
        }
    }

    #[test]
    fn get_nested_key() {
        let config = test_config();
        let result = get_value::<TestConfig>(&config, "database.pool_size").unwrap();
        match result {
            ConfigResult::KeyValue { value, .. } => assert_eq!(value, "5"),
            other => panic!("Expected KeyValue, got {other:?}"),
        }
    }

    #[test]
    fn get_nonexistent_key() {
        let config = test_config();
        let result = get_value::<TestConfig>(&config, "nonexistent");
        assert!(matches!(result, Err(ClapfigError::KeyNotFound(_))));
    }

    #[test]
    fn get_includes_doc() {
        let config = test_config();
        let result = get_value::<TestConfig>(&config, "host").unwrap();
        match result {
            ConfigResult::KeyValue { doc, .. } => {
                let doc_text = doc.join(" ");
                assert!(
                    doc_text.contains("host"),
                    "doc should mention host: {doc_text}"
                );
            }
            other => panic!("Expected KeyValue, got {other:?}"),
        }
    }

    #[test]
    fn get_nested_doc() {
        let config = test_config();
        let result = get_value::<TestConfig>(&config, "database.pool_size").unwrap();
        match result {
            ConfigResult::KeyValue { doc, .. } => {
                let doc_text = doc.join(" ");
                assert!(
                    doc_text.contains("pool size") || doc_text.contains("Connection pool"),
                    "doc should mention pool: {doc_text}"
                );
            }
            other => panic!("Expected KeyValue, got {other:?}"),
        }
    }

    #[test]
    fn table_get_flat() {
        let table: toml::Table = toml::from_str("port = 8080").unwrap();
        let val = table_get(&table, "port").unwrap();
        assert_eq!(val.as_integer().unwrap(), 8080);
    }

    #[test]
    fn table_get_nested() {
        let table: toml::Table = toml::from_str("[database]\npool_size = 5").unwrap();
        let val = table_get(&table, "database.pool_size").unwrap();
        assert_eq!(val.as_integer().unwrap(), 5);
    }

    #[test]
    fn table_get_missing() {
        let table: toml::Table = toml::from_str("port = 8080").unwrap();
        assert!(table_get(&table, "nope").is_none());
    }

    #[test]
    fn list_values_includes_all_keys() {
        let config = test_config();
        let result = list_values::<TestConfig>(&config).unwrap();
        match result {
            ConfigResult::Listing { entries } => {
                let keys: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).collect();
                assert!(keys.contains(&"host"));
                assert!(keys.contains(&"port"));
                assert!(keys.contains(&"debug"));
                assert!(keys.contains(&"database.url"));
                assert!(keys.contains(&"database.pool_size"));
                assert_eq!(entries.len(), 5);
            }
            other => panic!("Expected Listing, got {other:?}"),
        }
    }

    #[test]
    fn list_values_shows_not_set_for_none() {
        let config = test_config();
        let result = list_values::<TestConfig>(&config).unwrap();
        match result {
            ConfigResult::Listing { entries } => {
                let db_url = entries.iter().find(|(k, _)| k == "database.url").unwrap();
                assert_eq!(db_url.1, "<not set>");
            }
            other => panic!("Expected Listing, got {other:?}"),
        }
    }

    #[test]
    fn list_values_formats_correctly() {
        let config = test_config();
        let result = list_values::<TestConfig>(&config).unwrap();
        match result {
            ConfigResult::Listing { entries } => {
                let port = entries.iter().find(|(k, _)| k == "port").unwrap();
                assert_eq!(port.1, "8080");
                let host = entries.iter().find(|(k, _)| k == "host").unwrap();
                assert_eq!(host.1, "localhost");
            }
            other => panic!("Expected Listing, got {other:?}"),
        }
    }

    #[test]
    fn listing_display_format() {
        let result = ConfigResult::Listing {
            entries: vec![
                ("host".into(), "localhost".into()),
                ("port".into(), "8080".into()),
            ],
        };
        let display = format!("{result}");
        assert_eq!(display, "host = localhost\nport = 8080");
    }

    // --- scope file operations ---

    #[test]
    fn list_scope_file_returns_entries() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "port = 3000\nhost = \"localhost\"\n").unwrap();

        let result = list_scope_file(&path).unwrap();
        match result {
            ConfigResult::Listing { entries } => {
                assert_eq!(entries.len(), 2);
                assert!(entries.contains(&("host".into(), "localhost".into())));
                assert!(entries.contains(&("port".into(), "3000".into())));
            }
            other => panic!("Expected Listing, got {other:?}"),
        }
    }

    #[test]
    fn list_scope_file_nested() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[database]\npool_size = 10\nurl = \"pg://\"\n").unwrap();

        let result = list_scope_file(&path).unwrap();
        match result {
            ConfigResult::Listing { entries } => {
                assert!(entries.contains(&("database.pool_size".into(), "10".into())));
                assert!(entries.contains(&("database.url".into(), "pg://".into())));
            }
            other => panic!("Expected Listing, got {other:?}"),
        }
    }

    #[test]
    fn list_scope_file_missing_returns_empty() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("nonexistent.toml");

        let result = list_scope_file(&path).unwrap();
        match result {
            ConfigResult::Listing { entries } => assert!(entries.is_empty()),
            other => panic!("Expected empty Listing, got {other:?}"),
        }
    }

    #[test]
    fn get_scope_value_found() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "port = 3000\n").unwrap();

        let result = get_scope_value::<TestConfig>(&path, "port").unwrap();
        match result {
            ConfigResult::KeyValue { value, .. } => assert_eq!(value, "3000"),
            other => panic!("Expected KeyValue, got {other:?}"),
        }
    }

    #[test]
    fn get_scope_value_nested() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[database]\npool_size = 20\n").unwrap();

        let result = get_scope_value::<TestConfig>(&path, "database.pool_size").unwrap();
        match result {
            ConfigResult::KeyValue { value, .. } => assert_eq!(value, "20"),
            other => panic!("Expected KeyValue, got {other:?}"),
        }
    }

    #[test]
    fn get_scope_value_not_found() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "port = 3000\n").unwrap();

        let result = get_scope_value::<TestConfig>(&path, "missing");
        assert!(matches!(result, Err(ClapfigError::KeyNotFound(_))));
    }

    #[test]
    fn get_scope_value_missing_file() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("nonexistent.toml");

        let result = get_scope_value::<TestConfig>(&path, "port");
        assert!(matches!(result, Err(ClapfigError::KeyNotFound(_))));
    }

    #[test]
    fn get_scope_value_includes_doc() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "host = \"myhost\"\n").unwrap();

        let result = get_scope_value::<TestConfig>(&path, "host").unwrap();
        match result {
            ConfigResult::KeyValue { doc, .. } => {
                let doc_text = doc.join(" ");
                assert!(
                    doc_text.contains("host"),
                    "doc should mention host: {doc_text}"
                );
            }
            other => panic!("Expected KeyValue, got {other:?}"),
        }
    }
}