| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package charttpl |
| 4 | |
| 5 | const ( |
| 6 | defaultChartType = "line" |
| 7 | ) |
| 8 | |
| 9 | // applyDefaults mutates parsed template with phase-1 defaults. |
| 10 | func applyDefaults(spec *Spec) { |
| 11 | if spec == nil { |
| 12 | return |
| 13 | } |
| 14 | if spec.Version == "" { |
| 15 | spec.Version = VersionV1 |
| 16 | } |
| 17 | for i := range spec.Groups { |
| 18 | applyGroupDefaults(&spec.Groups[i], nil) |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | func applyGroupDefaults(group *Group, inherited *ChartDefaults) { |
| 23 | effective := inheritChartDefaults(inherited, group.ChartDefaults) |
| 24 | for i := range group.Charts { |
| 25 | applyChartDefaults(&group.Charts[i], effective) |
| 26 | if group.Charts[i].Type == "" { |
| 27 | group.Charts[i].Type = defaultChartType |
| 28 | } |
| 29 | } |
| 30 | for i := range group.Groups { |
| 31 | applyGroupDefaults(&group.Groups[i], effective) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | func applyChartDefaults(chart *Chart, defaults *ChartDefaults) { |
| 36 | if chart == nil || defaults == nil { |
| 37 | return |
| 38 | } |
| 39 | if chart.LabelPromoted == nil && defaults.LabelPromoted != nil { |
| 40 | chart.LabelPromoted = append([]string(nil), defaults.LabelPromoted...) |
| 41 | } |
| 42 | if chart.Instances == nil && defaults.Instances != nil { |
| 43 | chart.Instances = cloneInstances(defaults.Instances) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | func inheritChartDefaults(parent, own *ChartDefaults) *ChartDefaults { |
| 48 | if parent == nil && own == nil { |
| 49 | return nil |
| 50 | } |
| 51 | |
| 52 | out := &ChartDefaults{} |
| 53 | if parent != nil { |
| 54 | if parent.LabelPromoted != nil { |
| 55 | out.LabelPromoted = append([]string(nil), parent.LabelPromoted...) |
| 56 | } |
| 57 | if parent.Instances != nil { |
| 58 | out.Instances = cloneInstances(parent.Instances) |
| 59 | } |
| 60 | } |
| 61 | if own != nil { |
| 62 | if own.LabelPromoted != nil { |
| 63 | out.LabelPromoted = append([]string(nil), own.LabelPromoted...) |
| 64 | } |
| 65 | if own.Instances != nil { |
| 66 | out.Instances = cloneInstances(own.Instances) |
| 67 | } |
| 68 | } |
| 69 | if out.LabelPromoted == nil && out.Instances == nil { |
| 70 | return nil |
| 71 | } |
| 72 | return out |
| 73 | } |
| 74 | |
| 75 | func cloneInstances(in *Instances) *Instances { |
| 76 | if in == nil { |
| 77 | return nil |
| 78 | } |
| 79 | return &Instances{ |
| 80 | ByLabels: append([]string(nil), in.ByLabels...), |
| 81 | } |
| 82 | } |