Yaml: selectively quote leading zeros (#3595)

This commit is contained in:
andig 2022-06-06 14:21:06 +02:00
parent ff1cd4150e
commit 69bdae685c
5 changed files with 30 additions and 14 deletions

View file

@ -232,8 +232,8 @@ presets:
{{- if ne .title "" }}
title: {{ .title }}
{{- end }}
user: '{{ .user }}'
password: '{{ .password }}'
user: {{ .user }}
password: {{ .password }}
{{- if ne .capacity "" }}
capacity: {{ .capacity }}
{{- end }}

View file

@ -13,7 +13,7 @@ render: |
type: fiat
{{ include "vehicle-base" . }}
{{- if ne .pin "" }}
pin: '{{ .pin }}' # mandatory to deep refresh SoC
pin: {{ .pin }} # mandatory to deep refresh SoC
{{- end }}
{{ include "vehicle-identify" . }}
{{ include "vehicle-cloud" . }}

View file

@ -326,14 +326,16 @@ func (t *Template) RenderResult(renderMode string, other map[string]interface{})
}
tmpl := template.New("yaml")
var funcMap template.FuncMap = map[string]interface{}{}
// copied from: https://github.com/helm/helm/blob/8648ccf5d35d682dcd5f7a9c2082f0aaf071e817/pkg/engine/engine.go#L147-L154
funcMap["include"] = func(name string, data interface{}) (string, error) {
buf := bytes.NewBuffer(nil)
if err := tmpl.ExecuteTemplate(buf, name, data); err != nil {
return "", err
}
return buf.String(), nil
funcMap := template.FuncMap{
// include function
// copied from: https://github.com/helm/helm/blob/8648ccf5d35d682dcd5f7a9c2082f0aaf071e817/pkg/engine/engine.go#L147-L154
"include": func(name string, data interface{}) (string, error) {
buf := bytes.NewBuffer(nil)
if err := tmpl.ExecuteTemplate(buf, name, data); err != nil {
return "", err
}
return buf.String(), nil
},
}
tmpl, err := tmpl.Funcs(template.FuncMap(sprig.FuncMap())).Funcs(funcMap).Parse(t.Render)

View file

@ -7,7 +7,17 @@ import (
"gopkg.in/yaml.v3"
)
func quote(value string) string {
quoted := strings.ReplaceAll(value, `'`, `''`)
return fmt.Sprintf("'%s'", quoted)
}
func yamlQuote(value string) string {
// don't quote empty strings
if value == "" {
return value
}
input := fmt.Sprintf("key: %s", value)
var res struct {
@ -15,8 +25,12 @@ func yamlQuote(value string) string {
}
if err := yaml.Unmarshal([]byte(input), &res); err != nil || value != res.Value {
quoted := strings.ReplaceAll(value, `'`, `''`)
return fmt.Sprintf("'%s'", quoted)
return quote(value)
}
// fix 0815, but not 0
if strings.HasPrefix("0", value) && len(value) > 1 {
return quote(value)
}
return value

View file

@ -8,7 +8,7 @@ import (
)
func TestYamlDecode(t *testing.T) {
for _, value := range []string{`value`, `!value`, `@value`, `"value"`, `"va"lue"`, `va'lue`, `@va'lue`} {
for _, value := range []string{`value`, `!value`, `@value`, `"value"`, `"va"lue"`, `va'lue`, `@va'lue`, `0815`, `4711`, ``} {
t.Run(value, func(t *testing.T) {
quoted := yamlQuote(value)
input := fmt.Sprintf("key: %s", quoted)