clapfig 0.21.2

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
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
//! 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.
///
/// When `kebab` is `true`, snake_case field names in the template's keys and
/// section headers are rewritten to kebab-case (`pool_size` → `pool-size`)
/// so the template matches what users will actually type when
/// [`.normalize_keys(true)`](crate::ClapfigBuilder::normalize_keys) is in
/// effect. Doc comments and values are never touched.
///
/// The static path delegates to confique's `toml::template`; Phase 2's
/// runtime path will walk a [`SchemaRef`](crate::spec::SchemaRef) and emit
/// its own template.
pub fn generate_template<C: Config>(kebab: bool) -> String {
    let raw = confique::toml::template::<C>(confique::toml::FormatOptions::default());
    if kebab {
        rewrite_keys_to_kebab(&raw)
    } else {
        raw
    }
}

/// Rewrite snake_case keys to kebab-case in a confique TOML template.
///
/// Walks the template line by line and rewrites:
/// - `[section]` / `[parent.section]` / `[[array]]` headers
/// - `key = value` lines
/// - `#key = value` commented-default lines (single or multi-hash prefix)
///
/// Doc-comment lines (a `#` followed by a space or end-of-line) and the
/// value portion of any line are left untouched. The disambiguation between
/// a doc comment and a commented-default line is the same convention
/// confique itself uses: `# <text>` is documentation, `#key = ...` (no
/// space after the hashes) is a commented key.
fn rewrite_keys_to_kebab(template: &str) -> String {
    let mut out = String::with_capacity(template.len());
    let ends_with_newline = template.ends_with('\n');

    for (i, line) in template.lines().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        out.push_str(&rewrite_template_line(line));
    }
    if ends_with_newline {
        out.push('\n');
    }
    out
}

fn rewrite_template_line(line: &str) -> String {
    let indent_len = line.len() - line.trim_start().len();
    let indent = &line[..indent_len];
    let stripped = &line[indent_len..];

    // [[array.of.tables]] — must be checked before [section] since the
    // shorter prefix `[` is a substring of `[[`.
    if let Some(rest) = stripped.strip_prefix("[[")
        && let Some(end) = rest.find("]]")
    {
        let name = rest[..end].trim();
        let tail = &rest[end + 2..];
        return format!("{indent}[[{}]]{tail}", swap_underscores_to_dashes(name));
    }

    // [section] / [parent.section]
    if let Some(rest) = stripped.strip_prefix('[')
        && let Some(end) = rest.find(']')
    {
        let name = rest[..end].trim();
        let tail = &rest[end + 1..];
        return format!("{indent}[{}]{tail}", swap_underscores_to_dashes(name));
    }

    // Commented-out key (#key = ...) vs. doc comment (# <text>).
    let (hashes, body) = if stripped.starts_with('#') {
        let count = stripped.bytes().take_while(|&b| b == b'#').count();
        let after = &stripped[count..];
        // confique's convention: hashes + whitespace (or EOL) = doc comment;
        // hashes + bareword = commented-out default. Only rewrite the latter.
        if after.is_empty() || after.starts_with(|c: char| c.is_whitespace()) {
            return line.to_string();
        }
        (&stripped[..count], after)
    } else {
        ("", stripped)
    };

    // Plain or commented "key = value" line.
    if let Some(eq_idx) = body.find('=') {
        let key_part = &body[..eq_idx];
        let key_trimmed = key_part.trim();
        if is_bareword_dotted_key(key_trimmed) {
            // Preserve whitespace around the key exactly.
            let leading_ws_in_key = &key_part[..key_part.len() - key_part.trim_start().len()];
            let trailing_ws_in_key = &key_part[leading_ws_in_key.len() + key_trimmed.len()..];
            let rest = &body[eq_idx..];
            return format!(
                "{indent}{hashes}{leading_ws_in_key}{}{trailing_ws_in_key}{rest}",
                swap_underscores_to_dashes(key_trimmed),
            );
        }
    }

    line.to_string()
}

fn is_bareword_dotted_key(s: &str) -> bool {
    !s.is_empty()
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
}

fn swap_underscores_to_dashes(dotted: &str) -> String {
    if !dotted.contains('_') {
        return dotted.to_string();
    }
    dotted.replace('_', "-")
}

/// Generate a JSON Schema document (pretty-printed) describing the config struct.
///
/// Walks the schema via [`crate::schema::generate_schema_from_ref`] 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 schema = crate::spec::SchemaRef::from_meta(&C::META);
    let value = crate::schema::generate_schema_from_ref(schema);
    serde_json::to_string_pretty(&value).expect("serde_json::Value serialization is infallible")
}

/// Runtime-path template generator. Walks the runtime [`Schema`] and emits
/// a commented TOML template parallel to confique's `toml::template` output:
///
/// - Top-level `///`-equivalent doc lines render as `# <line>` at file head.
/// - Each leaf field renders its doc lines as `# <line>`, then either
///   `key = <default>` when a default is set, or `#key = <type-hint>` when
///   the field is required / has no default.
/// - Enum leaves get an extra `# Allowed: "a" | "b" | "c"` line so users
///   don't have to look the set up elsewhere.
/// - Nested sections render as `[parent.child]` headers; array-of-objects
///   render as `[[parent.child]]`.
/// - `kebab=true` applies the same key rewriter the static path uses, so
///   the rendered template matches what a `normalize_keys(true)` builder
///   accepts.
///
/// [`Schema`]: crate::runtime::Schema
pub(crate) fn generate_template_from_runtime(
    schema: &crate::runtime::Schema,
    kebab: bool,
) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    for line in &schema.doc {
        let trimmed = line.trim_end();
        if trimmed.is_empty() {
            out.push_str("#\n");
        } else {
            let _ = writeln!(out, "# {trimmed}");
        }
    }
    if !schema.doc.is_empty() {
        out.push('\n');
    }
    emit_schema(&mut out, schema, "");

    if kebab {
        rewrite_keys_to_kebab(&out)
    } else {
        out
    }
}

fn emit_schema(out: &mut String, schema: &crate::runtime::Schema, prefix: &str) {
    use crate::runtime::Field;
    use std::fmt::Write;

    // TOML rule: once a [section] header is emitted, every following key
    // belongs to that section until the next header. Emit local leaves
    // first, then sections — otherwise a sibling leaf declared after a
    // nested field in the schema would land inside the wrong section.
    for nf in &schema.fields {
        let Field::Leaf(leaf) = &nf.field else {
            continue;
        };
        for line in &leaf.doc {
            let trimmed = line.trim_end();
            if trimmed.is_empty() {
                out.push_str("#\n");
            } else {
                let _ = writeln!(out, "# {trimmed}");
            }
        }
        if let crate::runtime::LeafType::Enum { values } = &leaf.ty {
            let listed = values
                .iter()
                .map(format_inline_toml)
                .collect::<Vec<_>>()
                .join(" | ");
            let _ = writeln!(out, "# Allowed: {listed}");
        }
        if matches!(&leaf.ty, crate::runtime::LeafType::Value) {
            let _ = writeln!(out, "# Accepts: any TOML value");
        }
        match &leaf.default {
            Some(value) => {
                let _ = writeln!(out, "{} = {}", nf.name, format_inline_toml(value));
            }
            None => {
                let hint = leaf.ty.template_placeholder();
                let _ = writeln!(out, "#{} = {hint}", nf.name);
            }
        }
        out.push('\n');
    }

    for nf in &schema.fields {
        match &nf.field {
            Field::Leaf(_) => {} // already emitted above
            Field::Nested(child) => {
                let path = if prefix.is_empty() {
                    nf.name.clone()
                } else {
                    format!("{prefix}.{}", nf.name)
                };
                for line in &child.doc {
                    let trimmed = line.trim_end();
                    if trimmed.is_empty() {
                        out.push_str("#\n");
                    } else {
                        let _ = writeln!(out, "# {trimmed}");
                    }
                }
                let _ = writeln!(out, "[{path}]");
                emit_schema(out, child, &path);
            }
            Field::ArrayOf(child) => {
                let path = if prefix.is_empty() {
                    nf.name.clone()
                } else {
                    format!("{prefix}.{}", nf.name)
                };
                for line in &child.doc {
                    let trimmed = line.trim_end();
                    if trimmed.is_empty() {
                        out.push_str("#\n");
                    } else {
                        let _ = writeln!(out, "# {trimmed}");
                    }
                }
                // Array-of-objects is rendered commented — clapfig can't
                // know how many entries the user wants; show one example.
                let _ = writeln!(out, "#[[{path}]]");
                let mut buf = String::new();
                emit_schema(&mut buf, child, &path);
                for line in buf.lines() {
                    if line.is_empty() {
                        out.push('\n');
                    } else {
                        let _ = writeln!(out, "#{line}");
                    }
                }
            }
        }
    }
}

/// Format a `toml::Value` as it would appear inline in a TOML file (no
/// surrounding whitespace, no trailing newline).
fn format_inline_toml(value: &toml::Value) -> String {
    // toml::to_string handles inline encoding for primitives correctly;
    // for arrays/tables it produces a TOML fragment we trim.
    toml::to_string(&toml::Value::Table({
        let mut t = toml::Table::new();
        t.insert("v".into(), value.clone());
        t
    }))
    .map(|s| {
        // Output looks like `v = <inline>\n`. Strip the `v = ` prefix.
        let trimmed = s.trim_end();
        trimmed
            .strip_prefix("v = ")
            .map(|s| s.to_string())
            .unwrap_or_else(|| trimmed.to_string())
    })
    .unwrap_or_else(|_| format!("{value:?}"))
}

impl crate::runtime::LeafType {
    /// Single-word placeholder rendered in a commented-out template line
    /// for a leaf without a default. Mirrors what confique emits as a
    /// type-hint comment.
    pub(crate) fn template_placeholder(&self) -> &'static str {
        match self {
            crate::runtime::LeafType::String => "\"\"",
            crate::runtime::LeafType::Integer => "0",
            crate::runtime::LeafType::Float => "0.0",
            crate::runtime::LeafType::Bool => "false",
            crate::runtime::LeafType::DateTime => "1970-01-01T00:00:00Z",
            crate::runtime::LeafType::Array(_) => "[]",
            crate::runtime::LeafType::Map(_) => "{}",
            crate::runtime::LeafType::Enum { .. } => "\"\"",
            crate::runtime::LeafType::Value => "\"\"",
        }
    }
}

/// 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 = crate::meta::doc_for::<C>(key).unwrap_or_default();

    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 = crate::meta::doc_for::<C>(key).unwrap_or_default();

    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:?}"),
    }
}

#[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>(false);
        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>(false);
        assert!(template.contains("application host"));
        assert!(template.contains("port number"));
    }

    #[test]
    fn generate_template_kebab_rewrites_snake_keys() {
        let template = generate_template::<TestConfig>(true);
        // The nested `pool_size` field should be emitted as `pool-size`.
        assert!(
            template.contains("pool-size"),
            "expected kebab key in template:\n{template}"
        );
        assert!(
            !template.contains("pool_size"),
            "expected no snake leak in template:\n{template}"
        );
    }

    #[test]
    fn generate_template_kebab_preserves_doc_comments() {
        // Doc comments that happen to mention the snake form (in prose, not
        // as keys) should not be rewritten. TestConfig's docs include
        // "Connection pool size."—lowercase plain English—but we also want
        // the structural guarantee that `# ` lines pass through verbatim.
        let template = generate_template::<TestConfig>(true);
        assert!(template.contains("Connection pool size."));
    }

    #[test]
    fn generate_template_kebab_off_is_default_behavior() {
        // Sanity: with the flag off, output is byte-identical to the bare
        // confique template (kebab path is opt-in).
        let raw = generate_template::<TestConfig>(false);
        let bare = confique::toml::template::<TestConfig>(confique::toml::FormatOptions::default());
        assert_eq!(raw, bare);
    }

    // -- rewrite_keys_to_kebab unit tests -----------------------------------

    #[test]
    fn rewriter_handles_section_headers() {
        let input = "[my_section]\n[parent.my_child]\n";
        let out = rewrite_keys_to_kebab(input);
        assert!(out.contains("[my-section]"));
        assert!(out.contains("[parent.my-child]"));
    }

    #[test]
    fn rewriter_handles_array_of_tables_headers() {
        let input = "[[my_list]]\n";
        let out = rewrite_keys_to_kebab(input);
        assert_eq!(out, "[[my-list]]\n");
    }

    #[test]
    fn rewriter_handles_commented_default_keys() {
        let input = "#pool_size = 10\n";
        let out = rewrite_keys_to_kebab(input);
        assert_eq!(out, "#pool-size = 10\n");
    }

    #[test]
    fn rewriter_handles_uncommented_keys() {
        let input = "pool_size = 10\n";
        let out = rewrite_keys_to_kebab(input);
        assert_eq!(out, "pool-size = 10\n");
    }

    #[test]
    fn rewriter_skips_doc_comments() {
        // `#` followed by a space is a doc comment in confique's convention —
        // any `_` in prose must survive the rewriter untouched.
        let input = "# Set pool_size to a positive integer.\n";
        let out = rewrite_keys_to_kebab(input);
        assert_eq!(out, input);
    }

    #[test]
    fn rewriter_leaves_value_underscores_alone() {
        // Underscores in the value portion (e.g. inside string defaults)
        // must not be touched — only the key gets rewritten.
        let input = r#"db_url = "postgres://my_user@host""#.to_string() + "\n";
        let out = rewrite_keys_to_kebab(&input);
        assert!(out.contains("db-url = "));
        assert!(out.contains(r#""postgres://my_user@host""#));
    }

    #[test]
    fn rewriter_preserves_blank_lines() {
        let input = "key_one = 1\n\nkey_two = 2\n";
        let out = rewrite_keys_to_kebab(input);
        assert_eq!(out, "key-one = 1\n\nkey-two = 2\n");
    }

    #[test]
    fn rewriter_preserves_trailing_newline_absence() {
        // If the original lacks a trailing newline, the rewritten output
        // shouldn't sprout one.
        let input = "pool_size = 10";
        let out = rewrite_keys_to_kebab(input);
        assert_eq!(out, "pool-size = 10");
    }

    #[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:?}"),
        }
    }
}