helm-schema-gen 0.0.6

Generate an accurate JSON schema for any helm chart
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
use std::collections::{BTreeMap, BTreeSet};

use serde_json::Value;
use serde_yaml::Value as YamlValue;

use crate::merge::merge_schema_list;
use crate::schema_model::{empty_schema, is_empty_schema};
use crate::schema_node::SchemaNode;

pub(crate) fn apply_values_default_sources(
    doc: &mut YamlValue,
    sources: &BTreeSet<helm_schema_core::ValuesDefaultSource>,
) {
    let mut by_target: BTreeMap<&str, Vec<&helm_schema_core::ValuesDefaultSource>> =
        BTreeMap::new();
    for source in sources {
        by_target
            .entry(&source.target_path)
            .or_default()
            .push(source);
    }
    for sources in by_target.values() {
        // Multiple mutations of one target are order-sensitive. The signal
        // bundle intentionally carries no guessed lexical order, so only a
        // unique source is safe to apply.
        let [source] = sources.as_slice() else {
            continue;
        };
        let Some(defaults) = yaml_value_at_path(doc, &source.source_path).cloned() else {
            continue;
        };
        let target_segments = crate::split_value_path(&source.target_path);
        let Some(target) = yaml_value_at_segments_mut(doc, &target_segments) else {
            continue;
        };
        merge_missing_yaml_values(target, defaults);
    }
}

/// Copy each unique root-merge default from `source_doc` into `target_doc`
/// at its target path, creating intermediate mappings: the
/// absence-semantics document needs these render-time defaults even when
/// nothing else declares the subtree.
pub(crate) fn copy_values_default_sources(
    target_doc: &mut YamlValue,
    source_doc: &YamlValue,
    sources: &BTreeSet<helm_schema_core::ValuesDefaultSource>,
) {
    let mut by_target: BTreeMap<&str, Vec<&helm_schema_core::ValuesDefaultSource>> =
        BTreeMap::new();
    for source in sources {
        by_target
            .entry(&source.target_path)
            .or_default()
            .push(source);
    }
    for sources in by_target.values() {
        // Only a unique source per target is safe to apply; see
        // `apply_values_default_sources`.
        let [source] = sources.as_slice() else {
            continue;
        };
        let Some(defaults) = yaml_value_at_path(source_doc, &source.source_path).cloned() else {
            continue;
        };
        if !matches!(target_doc, YamlValue::Mapping(_)) {
            *target_doc = YamlValue::Mapping(serde_yaml::Mapping::default());
        }
        let target_segments = crate::split_value_path(&source.target_path);
        let mut current = &mut *target_doc;
        for segment in &target_segments {
            let YamlValue::Mapping(mapping) = current else {
                break;
            };
            let key = YamlValue::String(segment.clone());
            current = mapping
                .entry(key)
                .or_insert_with(|| YamlValue::Mapping(serde_yaml::Mapping::default()));
        }
        merge_missing_yaml_values(current, defaults);
    }
}

fn yaml_value_at_segments_mut<'a>(
    doc: &'a mut YamlValue,
    path_segments: &[String],
) -> Option<&'a mut YamlValue> {
    let mut current = doc;
    for segment in path_segments {
        let YamlValue::Mapping(mapping) = current else {
            return None;
        };
        current = mapping.get_mut(YamlValue::String(segment.clone()))?;
    }
    Some(current)
}

fn merge_missing_yaml_values(target: &mut YamlValue, defaults: YamlValue) {
    let (YamlValue::Mapping(target), YamlValue::Mapping(defaults)) = (target, defaults) else {
        return;
    };
    for (key, default) in defaults {
        if let Some(existing) = target.get_mut(&key) {
            merge_missing_yaml_values(existing, default);
        } else {
            target.insert(key, default);
        }
    }
}

pub(crate) struct ValuesYamlPathInfo {
    pub(crate) schema: Value,
    pub(crate) declared_defaults: Vec<Value>,
    pub(crate) is_explicit_null: bool,
    pub(crate) is_empty_string: bool,
    pub(crate) is_empty_map: bool,
    pub(crate) is_mapping: bool,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct ValuesYamlPathFacts {
    pub(crate) has_no_schema_evidence: bool,
    pub(crate) is_explicit_null: bool,
    pub(crate) is_empty_string: bool,
    pub(crate) is_empty_map: bool,
    pub(crate) is_mapping: bool,
    pub(crate) has_dependency_default: bool,
}

impl ValuesYamlPathFacts {
    pub(crate) fn absent() -> Self {
        Self {
            has_no_schema_evidence: true,
            ..Self::default()
        }
    }
}

impl ValuesYamlPathInfo {
    pub(crate) fn facts(&self) -> ValuesYamlPathFacts {
        ValuesYamlPathFacts {
            has_no_schema_evidence: is_empty_schema(&self.schema),
            is_explicit_null: self.is_explicit_null,
            is_empty_string: self.is_empty_string,
            is_empty_map: self.is_empty_map,
            is_mapping: self.is_mapping,
            has_dependency_default: false,
        }
    }
}

#[tracing::instrument(skip_all)]
pub(crate) fn build_values_yaml_path_info(
    values_yaml_doc: &YamlValue,
    referenced_value_paths: &BTreeSet<String>,
    pruned_parent_value_paths: &BTreeSet<String>,
    unconditionally_omitted_value_paths: &BTreeSet<String>,
    direct_ranged_value_paths: &BTreeSet<String>,
) -> BTreeMap<String, ValuesYamlPathInfo> {
    referenced_value_paths
        .iter()
        .filter_map(|path| {
            let segments = crate::split_value_path(path);
            lookup_values_yaml_path_info(values_yaml_doc, &segments)
                .map(|mut path_info| {
                    if pruned_parent_value_paths.contains(path) {
                        prune_referenced_descendant_schemas(
                            &mut path_info.schema,
                            path,
                            referenced_value_paths,
                        );
                    } else {
                        // Even under fragment parents (whose subtree
                        // schemas otherwise stay whole), a directly
                        // ranged member's declared shape must yield to
                        // its own resolution: the runtime iterable
                        // domain is wider than any declared default.
                        prune_referenced_descendant_schemas(
                            &mut path_info.schema,
                            path,
                            direct_ranged_value_paths,
                        );
                        // A member removed before every provider sink has no
                        // parent-level input contract. Its own path evidence
                        // decides whether the declared default remains
                        // meaningful.
                        prune_referenced_descendant_schemas(
                            &mut path_info.schema,
                            path,
                            unconditionally_omitted_value_paths,
                        );
                    }
                    path_info
                })
                .map(|path_info| (path.clone(), path_info))
        })
        .collect()
}

fn lookup_values_yaml_path_info(
    doc: &YamlValue,
    path_segments: &[String],
) -> Option<ValuesYamlPathInfo> {
    if path_segments.is_empty() {
        return None;
    }

    let values = lookup_values_yaml_values(doc, path_segments)?;
    if values.is_empty() {
        return None;
    }

    let schema = merge_schema_list(values.iter().copied().map(schema_from_yaml_value).collect());
    let declared_defaults = values
        .iter()
        .filter_map(|value| serde_json::to_value(value).ok())
        .collect();
    let is_explicit_null = matches!(values.as_slice(), [YamlValue::Null]);
    let is_empty_string = values
        .iter()
        .any(|value| matches!(value, YamlValue::String(value) if value.is_empty()));
    let is_empty_map = values
        .iter()
        .all(|value| matches!(value, YamlValue::Mapping(map) if map.is_empty()));
    let is_mapping = values
        .iter()
        .all(|value| matches!(value, YamlValue::Mapping(_)));
    Some(ValuesYamlPathInfo {
        schema,
        declared_defaults,
        is_explicit_null,
        is_empty_string,
        is_empty_map,
        is_mapping,
    })
}

pub(crate) fn yaml_value_at_segments<'a>(
    doc: &'a YamlValue,
    path_segments: &[String],
) -> Option<&'a YamlValue> {
    let mut current = doc;
    for segment in path_segments {
        let YamlValue::Mapping(mapping) = current else {
            return None;
        };
        current = mapping.get(YamlValue::String(segment.clone()))?;
    }
    Some(current)
}

pub(crate) fn yaml_value_at_path<'a>(
    doc: &'a YamlValue,
    value_path: &str,
) -> Option<&'a YamlValue> {
    yaml_value_at_segments(doc, &crate::split_value_path(value_path))
}

pub(crate) fn remove_values_paths(doc: &mut YamlValue, paths: &BTreeSet<String>) {
    for path in paths {
        remove_value_at_segments(doc, &crate::split_value_path(path));
    }
}

fn remove_value_at_segments(doc: &mut YamlValue, path: &[String]) {
    let Some((last, parents)) = path.split_last() else {
        return;
    };
    let mut current = doc;
    for segment in parents {
        let YamlValue::Mapping(mapping) = current else {
            return;
        };
        let Some(next) = mapping.get_mut(YamlValue::String(segment.clone())) else {
            return;
        };
        current = next;
    }
    let YamlValue::Mapping(mapping) = current else {
        return;
    };
    mapping.remove(YamlValue::String(last.clone()));
}

fn lookup_values_yaml_values<'a>(
    doc: &'a YamlValue,
    path_segments: &[String],
) -> Option<Vec<&'a YamlValue>> {
    if path_segments.is_empty() {
        return Some(vec![doc]);
    }

    let (head, tail) = path_segments.split_first()?;
    let head = head.as_str();

    match doc {
        YamlValue::Mapping(map) => {
            let key = YamlValue::String(head.to_string());
            let next = map.get(&key)?;
            lookup_values_yaml_values(next, tail)
        }
        YamlValue::Sequence(sequence) if head == "*" => {
            let mut out: Vec<&'a YamlValue> = Vec::new();
            for item in sequence {
                if let Some(mut child) = lookup_values_yaml_values(item, tail) {
                    out.append(&mut child);
                }
            }
            if out.is_empty() { None } else { Some(out) }
        }
        _ => None,
    }
}

fn prune_referenced_descendant_schemas(
    schema: &mut Value,
    value_path: &str,
    referenced_value_paths: &BTreeSet<String>,
) {
    let descendant_prefix = format!("{value_path}.");
    let mut relative_paths_to_prune = BTreeSet::new();
    for descendant in referenced_value_paths {
        let Some(relative_path) = descendant.strip_prefix(&descendant_prefix) else {
            continue;
        };
        let relative_segments = crate::split_value_path(relative_path);
        if relative_segments.is_empty() {
            continue;
        }
        relative_paths_to_prune.insert(shortest_referenced_relative_path(
            value_path,
            &relative_segments,
            referenced_value_paths,
        ));
    }

    for relative_segments in relative_paths_to_prune {
        let relative_segments: Vec<&str> = relative_segments
            .iter()
            .map(std::string::String::as_str)
            .collect();
        prune_schema_at_relative_path(schema, &relative_segments);
    }
}

fn shortest_referenced_relative_path(
    value_path: &str,
    relative_segments: &[String],
    referenced_value_paths: &BTreeSet<String>,
) -> Vec<String> {
    let mut prefix = Vec::new();
    for segment in relative_segments {
        prefix.push(segment.clone());
        let mut candidate_segments = crate::split_value_path(value_path);
        candidate_segments.extend(prefix.iter().cloned());
        let candidate_path = helm_schema_core::join_value_path(candidate_segments);
        if referenced_value_paths.contains(&candidate_path) {
            return prefix;
        }
    }
    relative_segments.to_vec()
}

fn prune_schema_at_relative_path(schema: &mut Value, relative_segments: &[&str]) {
    let Some((head, tail)) = relative_segments.split_first() else {
        return;
    };
    let Value::Object(object) = schema else {
        return;
    };

    if *head == "*" {
        if let Some(items) = object.get_mut("items") {
            if tail.is_empty() {
                *items = empty_schema();
            } else {
                prune_schema_at_relative_path(items, tail);
            }
        }
        return;
    }

    let Some(properties) = object.get_mut("properties").and_then(Value::as_object_mut) else {
        return;
    };
    if tail.is_empty() {
        properties.remove(*head);
        return;
    }

    if let Some(child) = properties.get_mut(*head) {
        prune_schema_at_relative_path(child, tail);
    }
}

fn schema_from_yaml_value(value: &YamlValue) -> Value {
    schema_node_from_yaml_value_with_skips(value, &[], &BTreeSet::new())
        .unwrap_or_else(SchemaNode::empty)
        .into_value()
}

pub(crate) fn schema_node_from_yaml_value_with_skips(
    value: &YamlValue,
    current_path: &[String],
    skip_paths: &BTreeSet<Vec<String>>,
) -> Option<SchemaNode> {
    if skip_paths.contains(current_path) {
        return None;
    }

    match value {
        YamlValue::Null | YamlValue::Tagged(_) => Some(SchemaNode::empty()),
        YamlValue::Bool(_) => Some(SchemaNode::type_named("boolean")),
        YamlValue::Number(number) => {
            let schema = if number.as_i64().is_some() || number.as_u64().is_some() {
                SchemaNode::type_named("integer")
            } else {
                SchemaNode::type_named("number")
            };
            Some(schema)
        }
        YamlValue::String(_) => Some(SchemaNode::type_named("string")),
        YamlValue::Sequence(sequence) => {
            let items = if sequence.is_empty() {
                empty_schema()
            } else {
                merge_schema_list(
                    sequence
                        .iter()
                        .filter_map(|item| {
                            schema_node_from_yaml_value_with_skips(item, current_path, skip_paths)
                        })
                        .map(SchemaNode::into_value)
                        .collect(),
                )
            };
            Some(SchemaNode::array().items(SchemaNode::foreign(items)))
        }
        YamlValue::Mapping(mapping) => {
            if mapping.is_empty() {
                return Some(SchemaNode::unknown_object());
            }
            // Declared defaults DOCUMENT keys, they do not bound them: a
            // chart's config mappings are routinely extended by users and
            // serialized wholesale, so the declared shape must stay open.
            // Closure is only ever justified by exhaustive structural
            // evidence (provider schemas, exact-empty off-states).
            let mut schema = SchemaNode::unknown_object();
            let mut inserted = false;
            for (key, value) in mapping {
                let Some(key) = key.as_str() else {
                    continue;
                };
                let child_path = child_value_path(current_path, key);
                let child_schema = if skip_paths.contains(&child_path) {
                    SchemaNode::empty()
                } else {
                    schema_node_from_yaml_value_with_skips(value, &child_path, skip_paths)?
                };
                inserted = true;
                schema = schema.property(key.to_string(), child_schema);
            }
            inserted.then_some(schema)
        }
    }
}

pub(crate) fn child_value_path(parent: &[String], child: &str) -> Vec<String> {
    let mut path = parent.to_vec();
    path.push(child.to_string());
    path
}