rust-config-tree 0.1.9

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
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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
//! JSON Schema generation and section-schema splitting.
//!
//! `schemars` produces one full schema for the root config type. This module
//! removes constraints that do not fit partial config files, strips internal
//! marker metadata from the emitted JSON, and optionally emits separate schemas
//! for marked nested sections.

use std::{
    collections::BTreeSet,
    path::{Path, PathBuf},
};

use confique::meta::{FieldKind, Meta};
use schemars::{JsonSchema, generate::SchemaSettings};
use serde_json::Value;

use crate::{
    config::{ConfigResult, ConfigSchema},
    config_output::write_template,
    config_util::ensure_single_trailing_newline,
};

const TREE_SPLIT_SCHEMA_EXTENSION: &str = "x-tree-split";
const ENV_ONLY_SCHEMA_EXTENSION: &str = "x-env-only";

/// Generated JSON Schema content for one output path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigSchemaTarget {
    /// Path that should receive the generated schema.
    pub path: PathBuf,
    /// Complete JSON Schema content to write to `path`.
    pub content: String,
}

/// Builds the root Draft 7 schema and adapts it for partial config files.
///
/// # Type Parameters
///
/// - `S`: Config schema type to render with `schemars`.
///
/// # Arguments
///
/// This function has no arguments.
///
/// # Returns
///
/// Returns the root schema as JSON with `required` constraints removed.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
pub(crate) fn root_config_schema<S>() -> ConfigResult<Value>
where
    S: JsonSchema,
{
    let generator = SchemaSettings::draft07().into_generator();
    let schema = generator.into_root_schema_for::<S>();
    let mut schema = serde_json::to_value(schema)?;
    remove_required_recursively(&mut schema);

    Ok(schema)
}

/// Serializes a schema value as stable pretty JSON for generated files.
///
/// # Arguments
///
/// - `schema`: Schema value to serialize.
///
/// # Returns
///
/// Returns pretty JSON with exactly one trailing newline.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn schema_json(schema: &Value) -> ConfigResult<String> {
    let mut json = serde_json::to_string_pretty(schema)?;
    ensure_single_trailing_newline(&mut json);
    Ok(json)
}

/// Removes every JSON Schema `required` list from a schema tree.
///
/// # Arguments
///
/// - `value`: Schema subtree to edit in place.
///
/// # Returns
///
/// Returns no value; `value` is updated directly.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn remove_required_recursively(value: &mut Value) {
    match value {
        Value::Object(object) => {
            object.remove("required");

            for (key, child) in object.iter_mut() {
                if is_schema_map_key(key) {
                    // Schema maps contain child schemas keyed by property or
                    // definition name; the map object itself is not a schema.
                    remove_required_from_schema_map(child);
                } else {
                    remove_required_recursively(child);
                }
            }
        }
        Value::Array(items) => {
            for item in items {
                remove_required_recursively(item);
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
    }
}

/// Returns whether a JSON object key names a map of child schemas.
///
/// # Arguments
///
/// - `key`: JSON object key to classify.
///
/// # Returns
///
/// Returns `true` when `key` names a schema map.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn is_schema_map_key(key: &str) -> bool {
    matches!(
        key,
        "$defs" | "definitions" | "properties" | "patternProperties"
    )
}

/// Removes `required` lists from every schema inside a schema map.
///
/// # Arguments
///
/// - `value`: Schema map value or fallback schema value to edit in place.
///
/// # Returns
///
/// Returns no value; `value` is updated directly.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn remove_required_from_schema_map(value: &mut Value) {
    match value {
        Value::Object(object) => {
            for schema in object.values_mut() {
                remove_required_recursively(schema);
            }
        }
        _ => remove_required_recursively(value),
    }
}

/// 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 mut current = root_schema;

    for section in section_path {
        current = current.get("properties")?.get(*section)?;
        current = resolve_schema_reference(root_schema, current).unwrap_or(current);
    }

    Some(standalone_section_schema(root_schema, current))
}

/// Resolves the local schema reference shape emitted by `schemars`.
///
/// # Arguments
///
/// - `root_schema`: Full root schema that owns referenced definitions.
/// - `schema`: Schema value that may contain a local `$ref`.
///
/// # Returns
///
/// Returns the referenced schema when `schema` contains a supported reference.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn resolve_schema_reference<'a>(root_schema: &'a Value, schema: &'a Value) -> Option<&'a Value> {
    if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
        return resolve_json_pointer_ref(root_schema, reference);
    }

    schema
        .get("allOf")
        .and_then(Value::as_array)
        .and_then(|schemas| schemas.first())
        .and_then(|schema| schema.get("$ref"))
        .and_then(Value::as_str)
        .and_then(|reference| resolve_json_pointer_ref(root_schema, reference))
}

/// Resolves a local JSON Pointer `$ref` against the root schema.
///
/// # Arguments
///
/// - `root_schema`: Full schema to query with the JSON Pointer.
/// - `reference`: `$ref` string that must start with `#`.
///
/// # Returns
///
/// Returns the referenced schema value when the pointer resolves.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn resolve_json_pointer_ref<'a>(root_schema: &'a Value, reference: &str) -> Option<&'a Value> {
    let pointer = reference.strip_prefix('#')?;
    root_schema.pointer(pointer)
}

/// 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
}

/// Resolves the output path for a split section schema.
///
/// # Arguments
///
/// - `root_schema_path`: Output path for the root schema.
/// - `section_path`: Nested section field path.
///
/// # Returns
///
/// Returns the generated schema path for `section_path`.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
pub(crate) fn schema_path_for_section(root_schema_path: &Path, section_path: &[&str]) -> PathBuf {
    let Some((last, parents)) = section_path.split_last() else {
        return root_schema_path.to_path_buf();
    };

    let mut path = root_schema_path
        .parent()
        .unwrap_or_else(|| Path::new("."))
        .to_path_buf();

    for parent in parents {
        path.push(*parent);
    }

    path.push(format!("{}.schema.json", *last));
    path
}

/// 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 _ = ();
/// ```
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 _ = ();
/// ```
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 _ = ();
/// ```
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 _ = ();
/// ```
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);
}

/// Expands the reference set with references used by already retained schemas.
///
/// # Arguments
///
/// - `schema`: Root schema containing schema maps to inspect.
/// - `definitions`: Referenced `definitions` names to expand in place.
/// - `defs`: Referenced `$defs` names to expand in place.
///
/// # Returns
///
/// Returns no value; `definitions` and `defs` are updated directly.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn collect_transitive_schema_refs(
    schema: &Value,
    definitions: &mut BTreeSet<String>,
    defs: &mut BTreeSet<String>,
) {
    let current_definitions = definitions.clone();
    let current_defs = defs.clone();
    let mut referenced_definitions = BTreeSet::new();
    let mut referenced_defs = BTreeSet::new();

    if let Some(schema_map) = schema.get("definitions").and_then(Value::as_object) {
        for name in &current_definitions {
            if let Some(schema) = schema_map.get(name) {
                collect_schema_refs(
                    schema,
                    true,
                    &mut referenced_definitions,
                    &mut referenced_defs,
                );
            }
        }
    }

    if let Some(schema_map) = schema.get("$defs").and_then(Value::as_object) {
        for name in &current_defs {
            if let Some(schema) = schema_map.get(name) {
                collect_schema_refs(
                    schema,
                    true,
                    &mut referenced_definitions,
                    &mut referenced_defs,
                );
            }
        }
    }

    definitions.extend(referenced_definitions);
    defs.extend(referenced_defs);
}

/// Walks a schema value and collects local references to schema maps.
///
/// # Arguments
///
/// - `value`: Schema subtree to inspect.
/// - `include_schema_maps`: Whether nested `definitions` and `$defs` maps
///   should also be traversed.
/// - `definitions`: Output set of referenced `definitions` names.
/// - `defs`: Output set of referenced `$defs` names.
///
/// # Returns
///
/// Returns no value; output sets are updated directly.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn collect_schema_refs(
    value: &Value,
    include_schema_maps: bool,
    definitions: &mut BTreeSet<String>,
    defs: &mut BTreeSet<String>,
) {
    match value {
        Value::Object(object) => {
            if let Some(reference) = object.get("$ref").and_then(Value::as_str) {
                collect_schema_ref(reference, definitions, defs);
            }

            for (key, child) in object {
                if !include_schema_maps && matches!(key.as_str(), "definitions" | "$defs") {
                    continue;
                }

                collect_schema_refs(child, include_schema_maps, definitions, defs);
            }
        }
        Value::Array(items) => {
            for item in items {
                collect_schema_refs(item, include_schema_maps, definitions, defs);
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
    }
}

/// Records one local `$ref` if it points at `definitions` or `$defs`.
///
/// # Arguments
///
/// - `reference`: `$ref` string to inspect.
/// - `definitions`: Output set of referenced `definitions` names.
/// - `defs`: Output set of referenced `$defs` names.
///
/// # Returns
///
/// Returns no value; matching references are inserted into the output sets.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn collect_schema_ref(
    reference: &str,
    definitions: &mut BTreeSet<String>,
    defs: &mut BTreeSet<String>,
) {
    if let Some(name) = schema_ref_name(reference, "#/definitions/") {
        definitions.insert(name);
    } else if let Some(name) = schema_ref_name(reference, "#/$defs/") {
        defs.insert(name);
    }
}

/// Extracts and JSON-Pointer-decodes a schema-map entry name from a `$ref`.
///
/// # Arguments
///
/// - `reference`: `$ref` string to parse.
/// - `prefix`: Schema-map pointer prefix to strip.
///
/// # Returns
///
/// Returns the decoded schema-map entry name when the reference matches.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn schema_ref_name(reference: &str, prefix: &str) -> Option<String> {
    let name = reference.strip_prefix(prefix)?.split('/').next()?;
    Some(decode_json_pointer_token(name))
}

/// Decodes the escaping used by one JSON Pointer path token.
///
/// # Arguments
///
/// - `token`: Encoded JSON Pointer path token.
///
/// # Returns
///
/// Returns `token` with `~1` and `~0` escapes decoded.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn decode_json_pointer_token(token: &str) -> String {
    token.replace("~1", "/").replace("~0", "~")
}

/// Retains only referenced entries in a root schema map.
///
/// # Arguments
///
/// - `schema`: Root schema containing the schema map.
/// - `key`: Schema-map key, such as `definitions` or `$defs`.
/// - `used_names`: Entry names that should remain in the map.
///
/// # Returns
///
/// Returns no value; the map is pruned in place.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn retain_schema_map(schema: &mut Value, key: &str, used_names: &BTreeSet<String>) {
    let Some(object) = schema.as_object_mut() else {
        return;
    };

    let Some(schema_map) = object.get_mut(key).and_then(Value::as_object_mut) else {
        return;
    };

    schema_map.retain(|name, _| used_names.contains(name));

    if schema_map.is_empty() {
        object.remove(key);
    }
}

/// 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 _ = ();
/// ```
fn remove_schema_extensions(value: &mut Value) {
    match value {
        Value::Object(object) => {
            object.remove(TREE_SPLIT_SCHEMA_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(_) => {}
    }
}

/// Writes a Draft 7 JSON Schema for the root config type.
///
/// The same generated schema can be referenced from TOML, YAML, JSON, and JSON5
/// configuration files. TOML and YAML templates bind it with editor directives.
/// JSON and JSON5 templates bind it with a top-level `$schema` property.
/// Generated schemas omit JSON Schema `required` constraints so editors provide
/// completion without requiring every config field to exist in each partial
/// config file.
///
/// # Type Parameters
///
/// - `S`: Config schema type that derives [`JsonSchema`].
///
/// # Arguments
///
/// - `output_path`: Destination path for the generated JSON Schema.
///
/// # Returns
///
/// Returns `Ok(())` after the schema file has been written.
///
/// # Examples
///
/// ```
/// use confique::Config;
/// use rust_config_tree::{ConfigSchema, write_config_schema};
/// use schemars::JsonSchema;
///
/// #[derive(Config, JsonSchema)]
/// struct AppConfig {
///     #[config(default = [])]
///     include: Vec<std::path::PathBuf>,
///     #[config(default = "demo")]
///     mode: String,
/// }
///
/// impl ConfigSchema for AppConfig {
///     fn include_paths(layer: &<Self as Config>::Layer) -> Vec<std::path::PathBuf> {
///         layer.include.clone().unwrap_or_default()
///     }
/// }
///
/// let path = std::env::temp_dir().join("rust-config-tree-write-schema-doctest.json");
/// write_config_schema::<AppConfig>(&path)?;
///
/// assert!(path.exists());
/// # let _ = std::fs::remove_file(path);
/// # Ok::<(), rust_config_tree::ConfigError>(())
/// ```
pub fn write_config_schema<S>(output_path: impl AsRef<Path>) -> ConfigResult<()>
where
    S: JsonSchema,
{
    let mut schema = root_config_schema::<S>()?;
    remove_env_only_properties(&mut schema);
    remove_empty_object_properties(&mut schema);
    prune_unused_schema_maps(&mut schema);
    remove_schema_extensions(&mut schema);
    let json = schema_json(&schema)?;

    write_template(output_path.as_ref(), &json)
}

/// Collects the root schema and section schemas for a config type.
///
/// The root schema is written to `output_path`. Nested `confique` sections are
/// written next to it as `<section>.schema.json` when the nested field schema
/// has `x-tree-split = true`; deeper split sections are nested in matching
/// directories, for example `schemas/outer/inner.schema.json`. Each generated
/// schema contains only the fields for its own template file; split child
/// section fields are omitted and completed by their own section schemas.
///
/// # Type Parameters
///
/// - `S`: Config schema type that derives [`JsonSchema`] and exposes section
///   metadata through [`ConfigSchema`].
///
/// # Arguments
///
/// - `output_path`: Destination path for the root JSON Schema.
///
/// # Returns
///
/// Returns all generated schema targets in traversal order.
///
/// # Examples
///
/// ```
/// use confique::Config;
/// use rust_config_tree::{ConfigSchema, config_schema_targets_for_path};
/// use schemars::JsonSchema;
///
/// #[derive(Config, JsonSchema)]
/// struct AppConfig {
///     #[config(default = [])]
///     include: Vec<std::path::PathBuf>,
///     #[config(default = "demo")]
///     mode: String,
/// }
///
/// impl ConfigSchema for AppConfig {
///     fn include_paths(layer: &<Self as Config>::Layer) -> Vec<std::path::PathBuf> {
///         layer.include.clone().unwrap_or_default()
///     }
/// }
///
/// let targets = config_schema_targets_for_path::<AppConfig>("schemas/config.schema.json")?;
///
/// assert_eq!(targets.len(), 1);
/// assert!(targets[0].content.contains("\"mode\""));
/// # Ok::<(), rust_config_tree::ConfigError>(())
/// ```
pub fn config_schema_targets_for_path<S>(
    output_path: impl AsRef<Path>,
) -> ConfigResult<Vec<ConfigSchemaTarget>>
where
    S: ConfigSchema + JsonSchema,
{
    let output_path = output_path.as_ref();
    let full_schema = root_config_schema::<S>()?;
    let split_paths = split_section_paths::<S>(&full_schema);
    let root_schema = schema_for_output_path(&full_schema, &[], &split_paths)?;
    let mut targets = vec![ConfigSchemaTarget {
        path: output_path.to_path_buf(),
        content: schema_json(&root_schema)?,
    }];

    for section_path in &split_paths {
        let schema_path = schema_path_for_section(output_path, section_path);
        let section_schema = schema_for_output_path(&full_schema, section_path, &split_paths)?;

        targets.push(ConfigSchemaTarget {
            path: schema_path,
            content: schema_json(&section_schema)?,
        });
    }

    Ok(targets)
}

/// Writes the root schema and section schemas for a config type.
///
/// Parent directories are created before each schema is written. Generated
/// schemas omit JSON Schema `required` constraints so they can be used for IDE
/// completion against partial config files. The root schema does not complete
/// split nested section fields.
///
/// # Type Parameters
///
/// - `S`: Config schema type that derives [`JsonSchema`] and exposes section
///   metadata through [`ConfigSchema`].
///
/// # Arguments
///
/// - `output_path`: Destination path for the root JSON Schema.
///
/// # Returns
///
/// Returns `Ok(())` after all schema files have been written.
///
/// # Examples
///
/// ```
/// use confique::Config;
/// use rust_config_tree::{ConfigSchema, write_config_schemas};
/// use schemars::JsonSchema;
///
/// #[derive(Config, JsonSchema)]
/// struct AppConfig {
///     #[config(default = [])]
///     include: Vec<std::path::PathBuf>,
///     #[config(default = "demo")]
///     mode: String,
/// }
///
/// impl ConfigSchema for AppConfig {
///     fn include_paths(layer: &<Self as Config>::Layer) -> Vec<std::path::PathBuf> {
///         layer.include.clone().unwrap_or_default()
///     }
/// }
///
/// let path = std::env::temp_dir()
///     .join("rust-config-tree-write-schemas-doctest")
///     .join("config.schema.json");
/// write_config_schemas::<AppConfig>(&path)?;
///
/// assert!(path.exists());
/// # let _ = std::fs::remove_file(&path);
/// # if let Some(parent) = path.parent() { let _ = std::fs::remove_dir_all(parent); }
/// # Ok::<(), rust_config_tree::ConfigError>(())
/// ```
pub fn write_config_schemas<S>(output_path: impl AsRef<Path>) -> ConfigResult<()>
where
    S: ConfigSchema + JsonSchema,
{
    for target in config_schema_targets_for_path::<S>(output_path)? {
        write_template(&target.path, &target.content)?;
    }

    Ok(())
}

/// Collects every nested `confique` section path from schema metadata.
///
/// # Arguments
///
/// - `meta`: Root `confique` metadata to traverse.
///
/// # Returns
///
/// Returns nested section paths in metadata traversal order.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
pub(crate) fn nested_section_paths(meta: &'static Meta) -> Vec<Vec<&'static str>> {
    let mut paths = Vec::new();
    collect_nested_section_paths(meta, &mut Vec::new(), &mut paths);
    paths
}

/// Finds nested sections whose field schema opts into template/schema splitting.
///
/// # Type Parameters
///
/// - `S`: Config schema type whose metadata supplies nested section paths.
///
/// # Arguments
///
/// - `full_schema`: Full root schema containing `x-tree-split` markers.
///
/// # Returns
///
/// Returns nested section paths that should be split.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
pub(crate) fn split_section_paths<S>(full_schema: &Value) -> Vec<Vec<&'static str>>
where
    S: ConfigSchema,
{
    nested_section_paths(&S::META)
        .into_iter()
        .filter(|section_path| section_has_tree_split_marker(full_schema, section_path))
        .collect()
}

/// Finds leaf fields whose schema opts out of template and schema output.
///
/// # Type Parameters
///
/// - `S`: Config schema type whose metadata supplies field paths.
///
/// # Arguments
///
/// - `full_schema`: Full root schema containing `x-env-only` markers.
///
/// # Returns
///
/// Returns leaf field paths marked with `x-env-only = true`.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
pub(crate) fn env_only_field_paths<S>(full_schema: &Value) -> Vec<Vec<&'static str>>
where
    S: ConfigSchema,
{
    let mut paths = Vec::new();
    collect_env_only_field_paths(&S::META, full_schema, &mut Vec::new(), &mut paths);
    paths
}

/// Checks whether a section property carries the split marker extension.
///
/// # Arguments
///
/// - `root_schema`: Full root schema to inspect.
/// - `section_path`: Nested section field path to check.
///
/// # Returns
///
/// Returns `true` when the section schema carries `x-tree-split = true`.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn section_has_tree_split_marker(root_schema: &Value, section_path: &[&str]) -> bool {
    property_schema_for_path(root_schema, section_path)
        .and_then(|schema| schema.get(TREE_SPLIT_SCHEMA_EXTENSION))
        .and_then(Value::as_bool)
        .unwrap_or(false)
}

/// Checks whether a field property carries the env-only marker extension.
///
/// # Arguments
///
/// - `root_schema`: Full root schema to inspect.
/// - `field_path`: Field path to check.
///
/// # Returns
///
/// Returns `true` when the field schema carries `x-env-only = true`.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn field_has_env_only_marker(root_schema: &Value, field_path: &[&str]) -> bool {
    property_schema_for_path(root_schema, field_path)
        .and_then(|schema| schema.get(ENV_ONLY_SCHEMA_EXTENSION))
        .and_then(Value::as_bool)
        .unwrap_or(false)
}

/// Returns the original property schema for a field path.
///
/// # Arguments
///
/// - `root_schema`: Full root schema to traverse.
/// - `path`: Field path to locate.
///
/// # Returns
///
/// Returns the original property schema when the section path exists.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
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
}

/// Recursively appends nested section paths to `paths`.
///
/// # Arguments
///
/// - `meta`: Current `confique` metadata node.
/// - `prefix`: Mutable section path prefix for `meta`.
/// - `paths`: Output list receiving discovered nested section paths.
///
/// # Returns
///
/// Returns no value; `paths` and `prefix` are updated during traversal.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn collect_nested_section_paths(
    meta: &'static Meta,
    prefix: &mut Vec<&'static str>,
    paths: &mut Vec<Vec<&'static str>>,
) {
    for field in meta.fields {
        if let FieldKind::Nested { meta } = field.kind {
            prefix.push(field.name);
            paths.push(prefix.clone());
            collect_nested_section_paths(meta, prefix, paths);
            prefix.pop();
        }
    }
}

/// Recursively appends env-only leaf field paths to `paths`.
///
/// # Arguments
///
/// - `meta`: Current `confique` metadata node.
/// - `root_schema`: Full root schema containing marker extensions.
/// - `prefix`: Mutable field path prefix for `meta`.
/// - `paths`: Output list receiving discovered leaf paths.
///
/// # Returns
///
/// Returns no value; `paths` and `prefix` are updated during traversal.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
fn collect_env_only_field_paths(
    meta: &'static Meta,
    root_schema: &Value,
    prefix: &mut Vec<&'static str>,
    paths: &mut Vec<Vec<&'static str>>,
) {
    for field in meta.fields {
        prefix.push(field.name);

        match field.kind {
            FieldKind::Leaf { .. } => {
                if field_has_env_only_marker(root_schema, prefix) {
                    paths.push(prefix.clone());
                }
            }
            FieldKind::Nested { meta } => {
                collect_env_only_field_paths(meta, root_schema, prefix, paths);
            }
        }

        prefix.pop();
    }
}

/// Returns split sections that are direct children of `section_path`.
///
/// # Arguments
///
/// - `section_path`: Parent section path to match.
/// - `split_paths`: All split section paths.
///
/// # Returns
///
/// Returns split paths whose parent is exactly `section_path`.
///
/// # Examples
///
/// ```no_run
/// let _ = ();
/// ```
pub(crate) fn direct_child_split_section_paths(
    section_path: &[&'static str],
    split_paths: &[Vec<&'static str>],
) -> Vec<Vec<&'static str>> {
    split_paths
        .iter()
        .filter(|path| path.len() == section_path.len() + 1 && path.starts_with(section_path))
        .cloned()
        .collect()
}