rust-config-tree 0.2.5

Recursive include tree utilities for layered configuration files.
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
//! Schema adaptation for split sections, env-only fields, and public output.

use std::collections::BTreeSet;

use serde_json::Value;

use crate::config::ConfigResult;

use super::{
    marker::{
        ENV_ONLY_SCHEMA_EXTENSION, TREE_INNER_FIELD_EXTENSION, TREE_SPLIT_SCHEMA_EXTENSION,
        TREE_TRANSPARENT_ARRAY_EXTENSION,
    },
    paths::{direct_child_split_section_paths, inner_field_for_section},
    reference::{
        collect_schema_refs, collect_transitive_schema_refs, resolve_schema_reference,
        retain_schema_map,
    },
};

/// Extracts a nested section schema and wraps it as a standalone schema.
///
/// # Arguments
///
/// - `root_schema`: Full root schema used for traversal and reference lookup.
/// - `section_path`: Nested section field path to extract.
///
/// # Returns
///
/// Returns a standalone section schema when the path exists.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn section_schema_for_path(root_schema: &Value, section_path: &[&str]) -> Option<Value> {
    let property = property_schema_for_path(root_schema, section_path)?;
    let resolved = resolve_schema_reference(root_schema, property).unwrap_or(property);

    if section_has_transparent_array_marker(root_schema, section_path) {
        return transparent_array_section_schema(root_schema, section_path, resolved);
    }

    Some(standalone_section_schema(root_schema, resolved))
}

/// Returns the property schema for one nested section path.
fn property_schema_for_path<'a>(root_schema: &'a Value, path: &[&str]) -> Option<&'a Value> {
    let mut current = root_schema;

    for (index, section) in path.iter().enumerate() {
        let property = current.get("properties")?.get(*section)?;
        if index + 1 == path.len() {
            return Some(property);
        }

        current = resolve_schema_reference(root_schema, property).unwrap_or(property);
    }

    None
}

/// Returns whether one section path uses transparent array serialization.
fn section_has_transparent_array_marker(root_schema: &Value, section_path: &[&str]) -> bool {
    property_schema_for_path(root_schema, section_path)
        .and_then(|schema| schema.get(TREE_TRANSPARENT_ARRAY_EXTENSION))
        .and_then(Value::as_bool)
        .unwrap_or(false)
}

/// Builds a standalone array schema for one transparent array section.
fn transparent_array_section_schema(
    root_schema: &Value,
    section_path: &[&str],
    section_schema: &Value,
) -> Option<Value> {
    let inner_field = inner_field_for_section(root_schema, section_path);
    let resolved = resolve_schema_reference(root_schema, section_schema).unwrap_or(section_schema);
    let inner_schema = resolved
        .get("properties")
        .and_then(|properties| properties.get(inner_field))
        .or_else(|| resolved.get("items"))?;
    let inner_schema = resolve_schema_reference(root_schema, inner_schema).unwrap_or(inner_schema);

    Some(standalone_section_schema(
        root_schema,
        &serde_json::json!({
            "type": "array",
            "items": inner_schema.clone(),
        }),
    ))
}
/// Copies root-level schema metadata needed by an extracted section schema.
///
/// # Arguments
///
/// - `root_schema`: Full root schema that owns `$schema`, `definitions`, and
///   `$defs`.
/// - `section_schema`: Extracted section schema to make standalone.
///
/// # Returns
///
/// Returns a cloned section schema with necessary root metadata attached.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn standalone_section_schema(root_schema: &Value, section_schema: &Value) -> Value {
    let mut section_schema = section_schema.clone();
    let Some(object) = section_schema.as_object_mut() else {
        return section_schema;
    };

    if let Some(schema_uri) = root_schema.get("$schema") {
        object
            .entry("$schema".to_owned())
            .or_insert_with(|| schema_uri.clone());
    }

    if let Some(definitions) = root_schema.get("definitions") {
        object
            .entry("definitions".to_owned())
            .or_insert_with(|| definitions.clone());
    }

    if let Some(defs) = root_schema.get("$defs") {
        object
            .entry("$defs".to_owned())
            .or_insert_with(|| defs.clone());
    }

    section_schema
}
/// Builds the schema content for either the root output or one split section.
///
/// # Arguments
///
/// - `full_schema`: Full root schema generated by `schemars`.
/// - `section_path`: Empty for the root schema, or the split section path.
/// - `split_paths`: All split section paths used to prune child sections.
///
/// # Returns
///
/// Returns the generated schema value for one output file.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
pub fn schema_for_output_path(
    full_schema: &Value,
    section_path: &[&'static str],
    split_paths: &[Vec<&'static str>],
) -> ConfigResult<Value> {
    let mut schema = if section_path.is_empty() {
        full_schema.clone()
    } else {
        section_schema_for_path(full_schema, section_path).ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "failed to extract JSON Schema for config section {}",
                    section_path.join(".")
                ),
            )
        })?
    };

    // Each generated file owns only its direct fields. Split child sections are
    // completed by their own schema files, so remove them from the parent.
    remove_child_section_properties(&mut schema, section_path, split_paths);
    remove_env_only_properties(&mut schema);
    remove_empty_object_properties(&mut schema);
    prune_unused_schema_maps(&mut schema);
    remove_schema_extensions(&mut schema);

    Ok(schema)
}

/// Removes direct split child sections from the schema owned by this output.
///
/// # Arguments
///
/// - `schema`: Schema value for the current output file.
/// - `section_path`: Section path owned by the current output file.
/// - `split_paths`: All split section paths in the root schema.
///
/// # Returns
///
/// Returns no value; `schema` is updated directly.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn remove_child_section_properties(
    schema: &mut Value,
    section_path: &[&'static str],
    split_paths: &[Vec<&'static str>],
) {
    let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) else {
        return;
    };

    for child_section_path in direct_child_split_section_paths(section_path, split_paths) {
        if let Some(child_name) = child_section_path.last() {
            properties.remove(*child_name);
        }
    }
}

/// Removes properties marked with `x-env-only`.
///
/// # Arguments
///
/// - `value`: Schema subtree to edit in place.
///
/// # Returns
///
/// Returns no value; `value` is updated directly.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
pub fn remove_env_only_properties(value: &mut Value) {
    match value {
        Value::Object(object) => {
            if let Some(properties) = object.get_mut("properties").and_then(Value::as_object_mut) {
                properties.retain(|_, schema| {
                    !schema
                        .get(ENV_ONLY_SCHEMA_EXTENSION)
                        .and_then(Value::as_bool)
                        .unwrap_or(false)
                });

                for schema in properties.values_mut() {
                    remove_env_only_properties(schema);
                }
            }

            for (key, child) in object.iter_mut() {
                if key != "properties" {
                    remove_env_only_properties(child);
                }
            }
        }
        Value::Array(items) => {
            for item in items {
                remove_env_only_properties(item);
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
    }
}

/// Removes object properties whose schema became empty after env-only pruning.
///
/// # Arguments
///
/// - `schema`: Schema subtree to edit in place.
///
/// # Returns
///
/// Returns no value; `schema` is updated directly.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
pub fn remove_empty_object_properties(schema: &mut Value) {
    loop {
        let root_schema = schema.clone();
        if !remove_empty_object_properties_with_root(schema, &root_schema) {
            break;
        }
    }
}

/// Removes empty object properties using `root_schema` for local `$ref` lookup.
///
/// # Arguments
///
/// - `value`: Schema subtree to edit in place.
/// - `root_schema`: Root schema used to resolve local references.
///
/// # Returns
///
/// Returns `true` when at least one property was removed.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn remove_empty_object_properties_with_root(value: &mut Value, root_schema: &Value) -> bool {
    let mut changed = false;

    match value {
        Value::Object(object) => {
            if let Some(properties) = object.get_mut("properties").and_then(Value::as_object_mut) {
                let before_len = properties.len();
                properties.retain(|_, schema| !is_empty_object_schema(root_schema, schema));
                changed |= properties.len() != before_len;

                for schema in properties.values_mut() {
                    changed |= remove_empty_object_properties_with_root(schema, root_schema);
                }
            }

            for (key, child) in object.iter_mut() {
                if key != "properties" {
                    changed |= remove_empty_object_properties_with_root(child, root_schema);
                }
            }
        }
        Value::Array(items) => {
            for item in items {
                changed |= remove_empty_object_properties_with_root(item, root_schema);
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
    }

    changed
}

/// Returns whether a schema resolves to an empty object schema.
///
/// # Arguments
///
/// - `root_schema`: Root schema used to resolve local references.
/// - `schema`: Candidate schema to inspect.
///
/// # Returns
///
/// Returns `true` when the schema is an object with no properties.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn is_empty_object_schema(root_schema: &Value, schema: &Value) -> bool {
    let schema = resolve_schema_reference(root_schema, schema).unwrap_or(schema);
    let Some(object) = schema.as_object() else {
        return false;
    };

    let is_object = object.get("type").and_then(Value::as_str) == Some("object")
        || object.contains_key("properties");
    let has_properties = object
        .get("properties")
        .and_then(Value::as_object)
        .is_some_and(|properties| !properties.is_empty());
    let has_dynamic_properties =
        object.contains_key("additionalProperties") || object.contains_key("patternProperties");

    is_object && !has_properties && !has_dynamic_properties
}

/// Drops unused `definitions` and `$defs` entries after section pruning.
///
/// # Arguments
///
/// - `schema`: Schema value whose schema maps should be pruned.
///
/// # Returns
///
/// Returns no value; `schema` is updated directly.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
pub fn prune_unused_schema_maps(schema: &mut Value) {
    let mut definitions = BTreeSet::new();
    let mut defs = BTreeSet::new();

    collect_schema_refs(schema, false, &mut definitions, &mut defs);

    loop {
        let previous_len = definitions.len() + defs.len();
        collect_transitive_schema_refs(schema, &mut definitions, &mut defs);

        if definitions.len() + defs.len() == previous_len {
            break;
        }
    }

    retain_schema_map(schema, "definitions", &definitions);
    retain_schema_map(schema, "$defs", &defs);
}

/// Removes internal extension markers before writing public schemas.
///
/// # Arguments
///
/// - `value`: Schema subtree to sanitize.
///
/// # Returns
///
/// Returns no value; `value` is updated directly.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
pub fn remove_schema_extensions(value: &mut Value) {
    match value {
        Value::Object(object) => {
            object.remove(TREE_SPLIT_SCHEMA_EXTENSION);
            object.remove(TREE_TRANSPARENT_ARRAY_EXTENSION);
            object.remove(TREE_INNER_FIELD_EXTENSION);
            object.remove(ENV_ONLY_SCHEMA_EXTENSION);

            for child in object.values_mut() {
                remove_schema_extensions(child);
            }
        }
        Value::Array(items) => {
            for item in items {
                remove_schema_extensions(item);
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
    }
}