Skip to content

Commit 6f304bc

Browse files
blakepetterssonbuchdag
authored andcommitted
feat: add yaml to/from functions
1 parent 78ec676 commit 6f304bc

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ require (
77
github.com/Masterminds/sprig/v3 v3.2.3
88
github.com/fsouza/go-dockerclient v1.10.2
99
github.com/stretchr/testify v1.8.4
10+
gopkg.in/yaml.v3 v3.0.1
1011
)
1112

1213
require (
@@ -47,5 +48,4 @@ require (
4748
golang.org/x/sys v0.16.0 // indirect
4849
golang.org/x/tools v0.6.0 // indirect
4950
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
50-
gopkg.in/yaml.v3 v3.0.1 // indirect
5151
)

internal/template/template.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,10 @@ func newTemplate(name string) *template.Template {
7575
"replace": strings.Replace,
7676
"parseBool": strconv.ParseBool,
7777
"parseJson": unmarshalJson,
78+
"fromYaml": fromYaml,
79+
"toYaml": toYaml,
80+
"mustFromYaml": mustFromYaml,
81+
"mustToYaml": mustToYaml,
7882
"queryEscape": url.QueryEscape,
7983
"sha1": hashSha1,
8084
"split": strings.Split,

internal/template/yaml.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package template
2+
3+
import "gopkg.in/yaml.v3"
4+
5+
// fromYaml decodes YAML into a structured value, ignoring errors.
6+
func fromYaml(v string) interface{} {
7+
output, _ := mustFromYaml(v)
8+
return output
9+
}
10+
11+
// mustFromYaml decodes YAML into a structured value, returning errors.
12+
func mustFromYaml(v string) (interface{}, error) {
13+
var output interface{}
14+
err := yaml.Unmarshal([]byte(v), &output)
15+
return output, err
16+
}
17+
18+
// toYaml encodes an item into a YAML string
19+
func toYaml(v interface{}) string {
20+
output, _ := mustToYaml(v)
21+
return string(output)
22+
}
23+
24+
// toYaml encodes an item into a YAML string, returning errors
25+
func mustToYaml(v interface{}) (string, error) {
26+
output, err := yaml.Marshal(v)
27+
if err != nil {
28+
return "", err
29+
}
30+
return string(output), nil
31+
}

0 commit comments

Comments
 (0)