clapfig 0.21.4

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
//! JSON Schema generation from a config schema.
//!
//! Entry point is [`generate_schema::<C>()`](generate_schema): it walks the
//! compile-time `confique::meta::Meta` tree and produces a JSON Schema
//! document. Useful for auto-generating UI editors, external validation
//! tools, or IDE integrations.
//!
//! Internally the walker consumes a crate-private `SchemaRef` view so the
//! same generator will serve runtime-supplied schemas (issue #36) without
//! a separate code path.
//!
//! # What is in the schema
//!
//! - **Structure**: every nested config struct becomes a JSON `object` with
//!   `properties`; non-`Option<T>` fields are listed in `required`.
//! - **Docs**: struct and field `///` doc comments become `description`.
//! - **Types**: inferred from each field's `#[config(default = ...)]`
//!   expression. String → `"string"`, integer → `"integer"`, float →
//!   `"number"`, bool → `"boolean"`, array → `"array"`, map → `"object"`.
//! - **Defaults**: the literal default value (when present) is emitted as
//!   `default` on the property.
//! - **Env vars**: when a field maps to an env var, the name is attached as
//!   the non-standard `x-env` extension.
//!
//! # Limitation: types without defaults
//!
//! Confique's `Meta` tree does not carry Rust type information directly — it
//! only records the default-value *expression*. A field without a default and
//! without an explicit type hint therefore gets no `type` key in the schema
//! (i.e. any JSON value is accepted). This is acceptable for UI generation:
//! a form generator will still see the field and its docs, and users supply
//! values anyway.
//!
//! # Example
//!
//! ```ignore
//! use clapfig::schema;
//!
//! let value = schema::generate_schema::<MyConfig>();
//! println!("{}", serde_json::to_string_pretty(&value).unwrap());
//! ```

use confique::Config;
use confique::meta::{Expr, MapEntry, MapKey};
use serde_json::{Map, Value, json};

use crate::runtime::LeafType;
use crate::spec::{DocSource, FieldKindRef, FieldRef, LeafDefault, LeafRef, SchemaRef};

/// JSON Schema dialect emitted in the root `$schema` field.
const SCHEMA_DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";

/// Generate a JSON Schema document from a confique config type.
///
/// Returns a `serde_json::Value` — the caller serializes it to a string,
/// writes it to a file, or embeds it wherever needed.
pub fn generate_schema<C: Config>() -> Value {
    generate_schema_from_ref(SchemaRef::from_meta(&C::META))
}

/// Internal entry point. Walks any `SchemaRef`-backed schema and emits the
/// JSON Schema document. Phase 2's runtime adapter calls this directly with
/// its own `SchemaRef` variant.
pub(crate) fn generate_schema_from_ref(schema: SchemaRef<'_>) -> Value {
    let mut root = schema_to_object(schema);
    if let Value::Object(map) = &mut root {
        map.insert("$schema".into(), Value::String(SCHEMA_DIALECT.into()));
    }
    root
}

/// Convert a schema node into a JSON Schema object.
fn schema_to_object(schema: SchemaRef<'_>) -> Value {
    let mut obj = Map::new();
    obj.insert("type".into(), Value::String("object".into()));
    obj.insert("title".into(), Value::String(schema.name().into()));
    let schema_doc = schema.doc();
    if !schema_doc.is_empty() {
        obj.insert("description".into(), Value::String(join_doc(schema_doc)));
    }

    let mut properties = Map::new();
    let mut required = Vec::new();

    for field in schema.fields() {
        let (name, prop, is_required) = field_to_property(field);
        if is_required {
            required.push(Value::String(name.clone()));
        }
        properties.insert(name, prop);
    }

    obj.insert("properties".into(), Value::Object(properties));
    if !required.is_empty() {
        obj.insert("required".into(), Value::Array(required));
    }
    obj.insert("additionalProperties".into(), Value::Bool(false));

    Value::Object(obj)
}

/// Convert a [`FieldRef`] into a `(name, schema, required)` triple.
///
/// `required` is `true` for non-optional leaves and for all nested structs
/// (a nested struct has its own internal required list).
fn field_to_property(field: FieldRef<'_>) -> (String, Value, bool) {
    match field.kind {
        FieldKindRef::Nested { schema: nested } => {
            let mut schema = schema_to_object(nested);
            if !field.doc.is_empty()
                && let Value::Object(map) = &mut schema
            {
                map.insert("description".into(), Value::String(join_doc(field.doc)));
            }
            (field.name.into(), schema, true)
        }
        FieldKindRef::ArrayOf { schema: item } => {
            // JSON Schema for a TOML `[[name]]` array of items: `type: array`
            // with `items: <item schema>`. Each runtime array entry is itself
            // typed against `item`, so the per-item schema is the natural
            // place to declare structure.
            //
            // Not marked required: `DynamicSpec::finalize` treats an absent
            // array-of as the empty list (no entries), so a JSON Schema
            // requiring the property would reject configs clapfig accepts.
            let mut prop = Map::new();
            if !field.doc.is_empty() {
                prop.insert("description".into(), Value::String(join_doc(field.doc)));
            }
            prop.insert("type".into(), Value::String("array".into()));
            prop.insert("items".into(), schema_to_object(item));
            (field.name.into(), Value::Object(prop), false)
        }
        FieldKindRef::MapOf { schema: item } => {
            // TOML `[name.<key>]` with arbitrary entry keys. JSON Schema
            // models this as `type: object` with `additionalProperties:
            // <entry schema>` — entry keys are user-supplied so there are
            // no fixed properties, but each value must satisfy the item
            // schema.
            //
            // Not marked required: `DynamicSpec::finalize` treats an
            // absent map-of as the empty map (no entries).
            let mut prop = Map::new();
            if !field.doc.is_empty() {
                prop.insert("description".into(), Value::String(join_doc(field.doc)));
            }
            prop.insert("type".into(), Value::String("object".into()));
            prop.insert("additionalProperties".into(), schema_to_object(item));
            (field.name.into(), Value::Object(prop), false)
        }
        FieldKindRef::Leaf(leaf) => {
            let mut prop = Map::new();
            if !field.doc.is_empty() {
                prop.insert("description".into(), Value::String(join_doc(field.doc)));
            }
            populate_leaf(&mut prop, leaf);
            (field.name.into(), Value::Object(prop), !leaf.optional)
        }
    }
}

/// Apply a leaf's declared type, default, env hint, and allowed-value set
/// onto its JSON Schema object.
fn populate_leaf(prop: &mut Map<String, Value>, leaf: LeafRef<'_>) {
    // Phase 2 runtime path supplies an explicit `LeafType`; emit a faithful
    // JSON Schema `type` from it without depending on whether a default
    // happens to be present.
    if let Some(ty) = leaf.ty
        && let Some(name) = leaf_type_json_name(ty)
    {
        prop.insert("type".into(), Value::String(name.into()));
        if let LeafType::Array(item) = ty
            && let Some(item_name) = leaf_type_json_name(item)
        {
            let mut items = Map::new();
            items.insert("type".into(), Value::String(item_name.into()));
            prop.insert("items".into(), Value::Object(items));
        }
    }

    if let Some(default) = leaf.default {
        match default {
            LeafDefault::Expr(expr) => {
                // Confique's `Meta` doesn't carry an explicit type; infer
                // from the default expression if a `LeafType` wasn't already
                // emitted above.
                if leaf.ty.is_none()
                    && let Some(ty) = infer_type(expr)
                {
                    prop.insert("type".into(), Value::String(ty.into()));
                }
                if let Some(default_value) = expr_to_json(expr) {
                    prop.insert("default".into(), default_value);
                }
            }
            LeafDefault::Toml(value) => {
                if let Some(default_value) = toml_value_to_json(value) {
                    prop.insert("default".into(), default_value);
                }
            }
        }
    }

    if let Some(env_name) = leaf.env {
        prop.insert("x-env".into(), Value::String(env_name.into()));
    }

    if let Some(values) = leaf.allowed_values {
        let enum_array: Vec<Value> = values.iter().filter_map(toml_value_to_json).collect();
        if !enum_array.is_empty() {
            prop.insert("enum".into(), Value::Array(enum_array));
        }
    }
}

/// JSON Schema `type` name for a runtime [`LeafType`]. `Enum` returns the
/// underlying primitive type implied by the first allowed value (callers
/// also emit `enum: [...]` separately).
fn leaf_type_json_name(ty: &LeafType) -> Option<&'static str> {
    match ty {
        LeafType::String => Some("string"),
        LeafType::Integer => Some("integer"),
        LeafType::Float => Some("number"),
        LeafType::Bool => Some("boolean"),
        LeafType::DateTime => Some("string"),
        LeafType::Array(_) => Some("array"),
        LeafType::Map(_) => Some("object"),
        LeafType::Enum { values } => values.first().and_then(toml_value_json_type),
        // Unconstrained: JSON Schema convention is to omit `type` entirely,
        // signalling that any value is acceptable. Callers reading the
        // schema are expected to validate the value themselves.
        LeafType::Value => None,
    }
}

/// Map a `toml::Value` to its JSON Schema `type` name.
fn toml_value_json_type(value: &toml::Value) -> Option<&'static str> {
    match value {
        toml::Value::String(_) => Some("string"),
        toml::Value::Integer(_) => Some("integer"),
        toml::Value::Float(_) => Some("number"),
        toml::Value::Boolean(_) => Some("boolean"),
        _ => None,
    }
}

/// Infer a JSON Schema `type` string from a confique default expression.
fn infer_type(expr: &Expr) -> Option<&'static str> {
    match expr {
        Expr::Str(_) => Some("string"),
        Expr::Integer(_) => Some("integer"),
        Expr::Float(_) => Some("number"),
        Expr::Bool(_) => Some("boolean"),
        Expr::Array(_) => Some("array"),
        Expr::Map(_) => Some("object"),
        _ => None,
    }
}

/// Convert a confique `Expr` (default value) into a JSON value.
///
/// Returns `None` for variants we can't faithfully represent (confique's
/// `Expr` is `#[non_exhaustive]`), so the caller can omit the `default` key
/// entirely rather than emitting a misleading `null`.
fn expr_to_json(expr: &Expr) -> Option<Value> {
    match expr {
        Expr::Str(s) => Some(Value::String((*s).into())),
        Expr::Integer(i) => Some(json!(i)),
        Expr::Float(f) => Some(json!(f)),
        Expr::Bool(b) => Some(Value::Bool(*b)),
        Expr::Array(items) => Some(Value::Array(
            items.iter().filter_map(expr_to_json).collect(),
        )),
        Expr::Map(entries) => {
            let mut obj = Map::new();
            for MapEntry { key, value } in *entries {
                let Some(key_str) = map_key_to_string(key) else {
                    continue;
                };
                let Some(val) = expr_to_json(value) else {
                    continue;
                };
                obj.insert(key_str, val);
            }
            Some(Value::Object(obj))
        }
        _ => None,
    }
}

/// Render a `MapKey` as a JSON object key. Returns `None` for variants we
/// can't faithfully represent, so the caller can skip the entry rather than
/// collapsing distinct keys onto an empty string.
fn map_key_to_string(key: &MapKey) -> Option<String> {
    match key {
        MapKey::Str(s) => Some((*s).into()),
        MapKey::Integer(i) => Some(i.to_string()),
        MapKey::Float(f) => Some(f.to_string()),
        MapKey::Bool(b) => Some(b.to_string()),
        _ => None,
    }
}

/// Convert a `toml::Value` into a JSON value for the `enum` slot.
///
/// Currently only used by the (Phase-1-dormant) `allowed_values` path on
/// `LeafRef`. The static spec never populates it; Phase 2 will.
///
/// Complex variants (`Array`, `Table`, `Datetime`) are dropped today. The
/// runtime enum surface in Phase 2 is scalar-only (`Field::enum_of(...)`
/// over TOML primitives — log levels, modes, format names), so this is the
/// faithful set for v1. Revisit if Phase 2 widens `enum_of` to accept
/// container values.
fn toml_value_to_json(value: &toml::Value) -> Option<Value> {
    match value {
        toml::Value::String(s) => Some(Value::String(s.clone())),
        toml::Value::Integer(i) => Some(json!(i)),
        toml::Value::Float(f) => Some(json!(f)),
        toml::Value::Boolean(b) => Some(Value::Bool(*b)),
        _ => None,
    }
}

fn join_doc(source: DocSource<'_>) -> String {
    source
        .iter()
        .map(|l| l.trim())
        .collect::<Vec<_>>()
        .join(" ")
        .trim()
        .to_string()
}

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

    fn schema() -> Value {
        generate_schema::<TestConfig>()
    }

    #[test]
    fn root_has_schema_dialect_and_type_object() {
        let s = schema();
        assert_eq!(s["$schema"], SCHEMA_DIALECT);
        assert_eq!(s["type"], "object");
        assert_eq!(s["title"], "TestConfig");
    }

    #[test]
    fn root_lists_top_level_properties() {
        let s = schema();
        let props = s["properties"].as_object().unwrap();
        assert!(props.contains_key("host"));
        assert!(props.contains_key("port"));
        assert!(props.contains_key("debug"));
        assert!(props.contains_key("database"));
    }

    #[test]
    fn types_inferred_from_defaults() {
        let s = schema();
        let props = &s["properties"];
        assert_eq!(props["host"]["type"], "string");
        assert_eq!(props["port"]["type"], "integer");
        assert_eq!(props["debug"]["type"], "boolean");
    }

    #[test]
    fn defaults_emitted_on_properties() {
        let s = schema();
        let props = &s["properties"];
        assert_eq!(props["host"]["default"], "localhost");
        assert_eq!(props["port"]["default"], 8080);
        assert_eq!(props["debug"]["default"], false);
    }

    #[test]
    fn doc_comments_become_descriptions() {
        let s = schema();
        let props = &s["properties"];
        assert!(
            props["host"]["description"]
                .as_str()
                .unwrap()
                .contains("host")
        );
        assert!(
            props["port"]["description"]
                .as_str()
                .unwrap()
                .contains("port")
        );
    }

    #[test]
    fn nested_struct_becomes_object_with_own_properties() {
        let s = schema();
        let db = &s["properties"]["database"];
        assert_eq!(db["type"], "object");
        assert_eq!(db["title"], "TestDbConfig");
        let db_props = db["properties"].as_object().unwrap();
        assert!(db_props.contains_key("url"));
        assert!(db_props.contains_key("pool_size"));
        assert_eq!(db_props["pool_size"]["type"], "integer");
        assert_eq!(db_props["pool_size"]["default"], 5);
    }

    #[test]
    fn required_array_excludes_optional_fields() {
        let s = schema();
        let root_required: Vec<&str> = s["required"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(root_required.contains(&"host"));
        assert!(root_required.contains(&"port"));
        assert!(root_required.contains(&"debug"));
        assert!(root_required.contains(&"database"));

        let db_required: Vec<&str> = s["properties"]["database"]["required"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(db_required.contains(&"pool_size"));
        // url is Option<String> — must NOT be required.
        assert!(!db_required.contains(&"url"));
    }

    #[test]
    fn optional_field_still_appears_in_properties() {
        let s = schema();
        let db_props = s["properties"]["database"]["properties"]
            .as_object()
            .unwrap();
        assert!(db_props.contains_key("url"));
        // No default and Option<T>, so no `type` and no `default`.
        assert!(!db_props["url"].as_object().unwrap().contains_key("type"));
        assert!(!db_props["url"].as_object().unwrap().contains_key("default"));
    }

    #[test]
    fn additional_properties_false_on_objects() {
        let s = schema();
        assert_eq!(s["additionalProperties"], false);
        assert_eq!(s["properties"]["database"]["additionalProperties"], false);
    }

    #[test]
    fn optional_field_has_no_null_default_key() {
        // Regression guard: expr_to_json must not fabricate a `default: null`
        // for fields that have no default (Option<T> / unrepresentable Expr).
        let s = schema();
        let url = &s["properties"]["database"]["properties"]["url"];
        let url_obj = url.as_object().unwrap();
        assert!(
            !url_obj.contains_key("default"),
            "optional field must not have a default key: {url}"
        );
    }

    #[test]
    fn schema_serializes_to_valid_json() {
        let s = schema();
        let json_text = serde_json::to_string_pretty(&s).unwrap();
        let reparsed: Value = serde_json::from_str(&json_text).unwrap();
        assert_eq!(reparsed, s);
    }
}