Skip to content

Commit

Permalink
Merge pull request #176 from jasondamour/master
Browse files Browse the repository at this point in the history
feat: add toYaml and fromYaml to functions map
  • Loading branch information
norwoodj authored Jul 6, 2024
2 parents 8fa02ac + d4d0176 commit 65110a3
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
3 changes: 1 addition & 2 deletions pkg/document/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (

"github.com/norwoodj/helm-docs/pkg/util"

"github.com/Masterminds/sprig/v3"
log "github.com/sirupsen/logrus"

"github.com/norwoodj/helm-docs/pkg/helm"
Expand Down Expand Up @@ -427,7 +426,7 @@ func getDocumentationTemplates(chartDirectory string, chartSearchRoot string, te

func newChartDocumentationTemplate(chartDocumentationInfo helm.ChartDocumentationInfo, chartSearchRoot string, templateFiles []string, badgeStyle string) (*template.Template, error) {
documentationTemplate := template.New(chartDocumentationInfo.ChartDirectory)
documentationTemplate.Funcs(sprig.TxtFuncMap())
documentationTemplate.Funcs(util.FuncMap())
goTemplateList, err := getDocumentationTemplates(chartDocumentationInfo.ChartDirectory, chartSearchRoot, templateFiles, badgeStyle)

if err != nil {
Expand Down
44 changes: 44 additions & 0 deletions pkg/util/funcs.go
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
}

0 comments on commit 65110a3

Please sign in to comment.