helm-schema-core 0.0.4

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
473
474
475
476
477
478
use std::fmt;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Number;

/// Scalar literal used by values-decidable guard comparisons.
///
/// Helm `eq` / `ne` conditions can compare against strings, booleans, numbers,
/// and nil. Keeping the literal typed prevents static analysis from degrading
/// `eq .Values.enabled false` into a misleading truthiness guard.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GuardValue {
    /// UTF-8 string literal.
    String(String),
    /// Boolean literal.
    Bool(bool),
    /// Signed integer literal.
    Int(i64),
    /// Finite floating-point literal stored in canonical textual form.
    Float(String),
    /// Explicit null literal.
    Null,
}

impl GuardValue {
    /// Creates a string guard literal.
    #[must_use]
    pub fn string(value: impl Into<String>) -> Self {
        Self::String(value.into())
    }

    /// Creates a finite floating-point guard literal, rejecting NaN and infinity.
    #[must_use]
    pub fn float(value: f64) -> Option<Self> {
        value.is_finite().then(|| Self::Float(value.to_string()))
    }
}

impl Serialize for GuardValue {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::String(value) => serializer.serialize_str(value),
            Self::Bool(value) => serializer.serialize_bool(*value),
            Self::Int(value) => serializer.serialize_i64(*value),
            Self::Float(value) => {
                let number = value
                    .parse::<f64>()
                    .ok()
                    .and_then(Number::from_f64)
                    .ok_or_else(|| serde::ser::Error::custom("invalid float guard value"))?;
                number.serialize(serializer)
            }
            Self::Null => serializer.serialize_none(),
        }
    }
}

impl<'de> Deserialize<'de> for GuardValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        match value {
            serde_json::Value::String(value) => Ok(Self::String(value)),
            serde_json::Value::Bool(value) => Ok(Self::Bool(value)),
            serde_json::Value::Number(value) => {
                if let Some(value) = value.as_i64() {
                    Ok(Self::Int(value))
                } else {
                    Ok(Self::Float(value.to_string()))
                }
            }
            serde_json::Value::Null => Ok(Self::Null),
            _ => Err(serde::de::Error::custom(
                "guard comparison value must be a scalar literal",
            )),
        }
    }
}

impl fmt::Display for GuardValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::String(value) => value.fmt(f),
            Self::Bool(value) => value.fmt(f),
            Self::Int(value) => value.fmt(f),
            #[expect(
                clippy::match_same_arms,
                reason = "string and float variants require distinct bindings despite identical formatting"
            )]
            Self::Float(value) => value.fmt(f),
            Self::Null => f.write_str("null"),
        }
    }
}

/// A guard condition from an `if`, `with`, or `range` block.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Guard {
    /// Simple truthy check: `if .Values.X`
    Truthy {
        /// Values path tested for truthiness.
        path: String,
    },
    /// Negated truthy check: `if not .Values.X`
    Not {
        /// Values path tested for falsiness.
        path: String,
    },
    /// Equality check: `if eq .Values.X "value"` / `if eq .Values.X false`.
    Eq {
        /// Values path compared with the literal.
        path: String,
        /// Literal required at the path.
        value: GuardValue,
    },
    /// Inequality check: `if ne .Values.X "value"` / `if ne .Values.X false`.
    NotEq {
        /// Values path compared with the literal.
        path: String,
        /// Literal excluded at the path.
        value: GuardValue,
    },
    /// Path absence check, used for structural rules where missing values are
    /// semantically distinct from false values.
    Absent {
        /// Values path whose absence selects the branch.
        path: String,
    },
    /// The path's string value matches a literal regular expression:
    /// `if regexMatch "…" .Values.X`. `regexMatch` type-asserts a string
    /// subject, so the guard holding implies string-ness as well. When
    /// `templated` is set the subject reached the match through `tpl`, so
    /// the pattern constrains the rendered OUTPUT: a raw value carrying a
    /// template action is admitted regardless (its render may match).
    MatchesPattern {
        /// Values path subjected to the pattern test.
        path: String,
        /// Literal regular expression required by the branch.
        pattern: String,
        /// Whether matching occurs after rendering the value through `tpl`.
        templated: bool,
    },
    /// A destructured range key starts with a literal prefix. The path names
    /// the ranged collection; the predicate applies to its matching entries,
    /// not to the collection value itself.
    RangeKeyPrefix {
        /// Values path of the ranged collection.
        path: String,
        /// Literal prefix required of the current key.
        prefix: String,
    },
    /// A destructured range key equals a literal (`if eq $key "name"`). The
    /// path names the ranged collection; the predicate selects exactly the
    /// entry with that key. Document-level lowering may only use the
    /// POSITIVE form (the key exists in the collection); the negation runs
    /// for every OTHER member and has no key-presence encoding.
    RangeKeyEquals {
        /// Values path of the ranged collection.
        path: String,
        /// Literal key selected by the branch.
        key: String,
    },
    /// A destructured range key matches a literal regular expression
    /// (`if regexMatch "[A-Z]" $name`). The path names the ranged
    /// collection; the predicate applies per key, so lowering targets the
    /// collection's key domain (traefik's uppercase `ingressRoute` gate).
    RangeKeyMatches {
        /// Values path of the ranged collection.
        path: String,
        /// Regular expression required of the current key.
        pattern: String,
    },
    /// Disjunction: `if or .Values.A .Values.B`
    Or {
        /// Values paths whose truthiness forms the disjunction.
        paths: Vec<String>,
    },
    /// Disjunction whose arms may each contain a conjunction of typed guards.
    ///
    /// This preserves structural forms such as
    /// `or (and .Values.A .Values.B) (eq .Values.mode "prod")` without
    /// degrading them into truthiness checks for every mentioned path.
    AnyOf {
        /// Guard conjunctions that form the disjunction's alternatives.
        alternatives: Vec<Vec<Guard>>,
    },
    /// Body of `range .Values.X` / `range .foo` block. The referenced path is
    /// being iterated as a collection, not interpreted as a boolean-valued
    /// scalar. This should not contribute a boolean type hint downstream.
    Range {
        /// Values path used as the range source.
        path: String,
    },
    /// Body of `with .Values.X` block. This distinguishes header binding from
    /// `if`-style truthy checks. The bound path is null-tolerant by
    /// construction because `with nil` skips the body.
    With {
        /// Values path selected as the branch context.
        path: String,
    },
    /// Rendered via a `default ... <path>` fallback, either in prefix form
    /// (`default "x" .Values.X`) or pipeline form (`.Values.X | default "x"`).
    ///
    /// This is stronger than a plain truthy guard: the template explicitly
    /// substitutes a fallback when the path is empty/nil, so `null` is an
    /// accepted chart input for that render site even when `values.yaml` ships
    /// a non-null default.
    Default {
        /// Values path protected by a fallback.
        path: String,
    },
    /// A `typeIs "<json type>" <path>` check in template logic.
    ///
    /// This is not a truthiness guard. It is a structural type declaration:
    /// helpers such as Bitnami's `common.tplvalues.render` explicitly branch on
    /// `typeIs "string" .value`, so callers may supply that values path as a
    /// string even when another branch renders it as a YAML object fragment.
    TypeIs {
        /// Values path subjected to the type test.
        path: String,
        /// JSON Schema type name selected by the branch.
        schema_type: String,
    },
    /// The complement of [`Guard::TypeIs`]: the `else` arm of a type
    /// dispatch (`if typeIs "string" x … else …`).
    ///
    /// Rows need this as a first-class variant because dropping the
    /// complement collapses a type-switch partition: member reads and
    /// structural placements under the `else` would otherwise apply to
    /// EVERY type of the dispatched path.
    NotTypeIs {
        /// Values path subjected to the type test.
        path: String,
        /// JSON Schema type name excluded by the branch.
        schema_type: String,
    },
    /// The path's RAW value is a JSON integer strictly greater than `bound`.
    ///
    /// This deliberately claims less than the Sprig coercion it stands in
    /// for: `gt (int64 .Values.x) N` also holds for numeric strings and
    /// `true`, so this guard is a SOUND SUBSET usable only where firing
    /// less often is safe (a fail-arm condition), never as an exact branch
    /// condition whose negation must also hold.
    IntGt {
        /// Values path subjected to the integer comparison.
        path: String,
        /// Exclusive lower bound.
        bound: i64,
    },
    /// The path's RAW value is a JSON integer strictly less than `bound`.
    ///
    /// The mirror of [`Guard::IntGt`], with the same sound-subset contract:
    /// `lt (int .Values.x) N` also holds for coercible non-integers, so
    /// this guard may only strengthen positive-polarity consumers.
    IntLt {
        /// Values path subjected to the integer comparison.
        path: String,
        /// Exclusive upper bound.
        bound: i64,
    },
    /// The collection at `path` has at most one entry.
    ///
    /// A sound SUBSET stand-in for loop-carried conditions that provably
    /// hold on a range's FIRST iteration (an empty-initialized dedup
    /// accumulator cannot shadow anything yet): with at most one member,
    /// every iteration is the first. Like [`Guard::IntGt`], it may only
    /// strengthen positive-polarity consumers.
    AtMostOneMember {
        /// Values path expected to hold the bounded collection.
        path: String,
    },
    /// The value at `path` is a mapping with at least `bound` members —
    /// the exact meaning of `gt (keys X | len) N` (`keys` aborts on
    /// non-maps, so the render reaches the body only for maps).
    MinMembers {
        /// Values path expected to hold the mapping.
        path: String,
        /// Inclusive minimum number of mapping members.
        bound: i64,
    },
    /// The mapping at `path` contains `key` as a literal member — Sprig
    /// `hasKey`/`dig` observability, where a present nil member IS present
    /// (cilium's removed-option guards abort on the truthy `"<nil>"`
    /// rendering of an explicit null). Contrast [`Guard::Absent`], which
    /// counts explicit null as absent for the nil-safe selector lanes.
    HasKey {
        /// Values path expected to hold a mapping.
        path: String,
        /// Literal mapping key whose presence selects the branch.
        key: String,
    },
    /// SOME item of the list at `path` deep-equals the scalar literal —
    /// Sprig `has LITERAL .Values.list`, the dual of the literal-list
    /// membership (`has .Values.x (list …)`). `has` returns false on a
    /// nil haystack and aborts rendering on non-lists, so the guard holds
    /// exactly for arrays carrying the literal (oauth2-proxy gates its
    /// secret keys on `has "cookie-secret" .Values.config.requiredSecretKeys`).
    ContainsEquals {
        /// Values path expected to hold a list.
        path: String,
        /// Literal that at least one list item must equal.
        value: GuardValue,
    },
}

impl Guard {
    pub(crate) fn canonicalize_all(guards: &mut Vec<Self>) {
        for guard in guards.iter_mut() {
            guard.canonicalize();
        }
        guards.sort();
        guards.dedup();
    }

    fn canonicalize(&mut self) {
        match self {
            Self::Or { paths } => {
                paths.sort();
                paths.dedup();
            }
            Self::AnyOf { alternatives } => {
                for guards in alternatives.iter_mut() {
                    Self::canonicalize_all(guards);
                }
                alternatives.sort();
                alternatives.dedup();
            }
            Self::Truthy { .. }
            | Self::Not { .. }
            | Self::Eq { .. }
            | Self::NotEq { .. }
            | Self::Absent { .. }
            | Self::MatchesPattern { .. }
            | Self::RangeKeyPrefix { .. }
            | Self::RangeKeyEquals { .. }
            | Self::RangeKeyMatches { .. }
            | Self::Range { .. }
            | Self::With { .. }
            | Self::Default { .. }
            | Self::TypeIs { .. }
            | Self::NotTypeIs { .. }
            | Self::IntGt { .. }
            | Self::IntLt { .. }
            | Self::AtMostOneMember { .. }
            | Self::MinMembers { .. }
            | Self::HasKey { .. }
            | Self::ContainsEquals { .. } => {}
        }
    }

    /// Return all `.Values.*` paths referenced by this guard.
    #[must_use]
    pub fn value_paths(&self) -> Vec<&str> {
        match self {
            Guard::Truthy { path }
            | Guard::Not { path }
            | Guard::Eq { path, .. }
            | Guard::NotEq { path, .. }
            | Guard::Absent { path }
            | Guard::MatchesPattern { path, .. }
            | Guard::RangeKeyPrefix { path, .. }
            | Guard::RangeKeyEquals { path, .. }
            | Guard::RangeKeyMatches { path, .. }
            | Guard::Range { path }
            | Guard::With { path }
            | Guard::Default { path }
            | Guard::TypeIs { path, .. }
            | Guard::NotTypeIs { path, .. }
            | Guard::IntGt { path, .. }
            | Guard::IntLt { path, .. }
            | Guard::AtMostOneMember { path }
            | Guard::MinMembers { path, .. }
            | Guard::HasKey { path, .. }
            | Guard::ContainsEquals { path, .. } => {
                vec![path.as_str()]
            }
            Guard::Or { paths } => paths.iter().map(std::string::String::as_str).collect(),
            Guard::AnyOf { alternatives } => alternatives
                .iter()
                .flat_map(|alternative| alternative.iter().flat_map(Guard::value_paths))
                .collect(),
        }
    }

    /// Rewrite value paths carried by this guard.
    #[must_use]
    pub fn map_value_paths<F>(self, map: &mut F) -> Self
    where
        F: FnMut(&str) -> String,
    {
        match self {
            Guard::Truthy { path } => Guard::Truthy { path: map(&path) },
            Guard::Not { path } => Guard::Not { path: map(&path) },
            Guard::Eq { path, value } => Guard::Eq {
                path: map(&path),
                value,
            },
            Guard::NotEq { path, value } => Guard::NotEq {
                path: map(&path),
                value,
            },
            Guard::Absent { path } => Guard::Absent { path: map(&path) },
            Guard::MatchesPattern {
                path,
                pattern,
                templated,
            } => Guard::MatchesPattern {
                path: map(&path),
                pattern,
                templated,
            },
            Guard::RangeKeyEquals { path, key } => Guard::RangeKeyEquals {
                path: map(&path),
                key,
            },
            Guard::RangeKeyPrefix { path, prefix } => Guard::RangeKeyPrefix {
                path: map(&path),
                prefix,
            },
            Guard::RangeKeyMatches { path, pattern } => Guard::RangeKeyMatches {
                path: map(&path),
                pattern,
            },
            Guard::Or { paths } => Guard::Or {
                paths: paths.into_iter().map(|path| map(&path)).collect(),
            },
            Guard::AnyOf { alternatives } => Guard::AnyOf {
                alternatives: alternatives
                    .into_iter()
                    .map(|alternative| {
                        alternative
                            .into_iter()
                            .map(|guard| guard.map_value_paths(map))
                            .collect()
                    })
                    .collect(),
            },
            Guard::Range { path } => Guard::Range { path: map(&path) },
            Guard::With { path } => Guard::With { path: map(&path) },
            Guard::Default { path } => Guard::Default { path: map(&path) },
            Guard::TypeIs { path, schema_type } => Guard::TypeIs {
                path: map(&path),
                schema_type,
            },
            Guard::NotTypeIs { path, schema_type } => Guard::NotTypeIs {
                path: map(&path),
                schema_type,
            },
            Guard::IntGt { path, bound } => Guard::IntGt {
                path: map(&path),
                bound,
            },
            Guard::IntLt { path, bound } => Guard::IntLt {
                path: map(&path),
                bound,
            },
            Guard::AtMostOneMember { path } => Guard::AtMostOneMember { path: map(&path) },
            Guard::MinMembers { path, bound } => Guard::MinMembers {
                path: map(&path),
                bound,
            },
            Guard::HasKey { path, key } => Guard::HasKey {
                path: map(&path),
                key,
            },
            Guard::ContainsEquals { path, value } => Guard::ContainsEquals {
                path: map(&path),
                value,
            },
        }
    }
}