-
Notifications
You must be signed in to change notification settings - Fork 193
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add toYaml and fromYaml to functions map
- Loading branch information
1 parent
7717a24
commit d4d0176
Showing
2 changed files
with
45 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package util | ||
|
||
import ( | ||
"strings" | ||
"text/template" | ||
|
||
"github.com/Masterminds/sprig/v3" | ||
"gopkg.in/yaml.v3" | ||
) | ||
|
||
func FuncMap() template.FuncMap { | ||
f := sprig.TxtFuncMap() | ||
f["toYaml"] = toYAML | ||
f["fromYaml"] = fromYAML | ||
return f | ||
} | ||
|
||
// toYAML takes an interface, marshals it to yaml, and returns a string. It will | ||
// always return a string, even on marshal error (empty string). | ||
// | ||
// This is designed to be called from a template. | ||
func toYAML(v interface{}) string { | ||
data, err := yaml.Marshal(v) | ||
if err != nil { | ||
// Swallow errors inside of a template. | ||
return "" | ||
} | ||
return strings.TrimSuffix(string(data), "\n") | ||
} | ||
|
||
// fromYAML converts a YAML document into a map[string]interface{}. | ||
// | ||
// This is not a general-purpose YAML parser, and will not parse all valid | ||
// YAML documents. Additionally, because its intended use is within templates | ||
// it tolerates errors. It will insert the returned error message string into | ||
// m["Error"] in the returned map. | ||
func fromYAML(str string) map[string]interface{} { | ||
m := map[string]interface{}{} | ||
|
||
if err := yaml.Unmarshal([]byte(str), &m); err != nil { | ||
m["Error"] = err.Error() | ||
} | ||
return m | ||
} |