github.com/stefanmcshane/helm@v0.0.0-20221213002717-88a4a2c6e77d/pkg/engine/funcs.go (about)

     1  /*
     2  Copyright The Helm Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package engine
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"strings"
    23  	"text/template"
    24  
    25  	"github.com/BurntSushi/toml"
    26  	"github.com/Masterminds/sprig/v3"
    27  	"sigs.k8s.io/yaml"
    28  )
    29  
    30  // funcMap returns a mapping of all of the functions that Engine has.
    31  //
    32  // Because some functions are late-bound (e.g. contain context-sensitive
    33  // data), the functions may not all perform identically outside of an Engine
    34  // as they will inside of an Engine.
    35  //
    36  // Known late-bound functions:
    37  //
    38  //	- "include"
    39  //	- "tpl"
    40  //
    41  // These are late-bound in Engine.Render().  The
    42  // version included in the FuncMap is a placeholder.
    43  //
    44  func funcMap() template.FuncMap {
    45  	f := sprig.TxtFuncMap()
    46  	delete(f, "env")
    47  	delete(f, "expandenv")
    48  
    49  	// Add some extra functionality
    50  	extra := template.FuncMap{
    51  		"toToml":        toTOML,
    52  		"toYaml":        toYAML,
    53  		"fromYaml":      fromYAML,
    54  		"fromYamlArray": fromYAMLArray,
    55  		"toJson":        toJSON,
    56  		"fromJson":      fromJSON,
    57  		"fromJsonArray": fromJSONArray,
    58  
    59  		// This is a placeholder for the "include" function, which is
    60  		// late-bound to a template. By declaring it here, we preserve the
    61  		// integrity of the linter.
    62  		"include":  func(string, interface{}) string { return "not implemented" },
    63  		"tpl":      func(string, interface{}) interface{} { return "not implemented" },
    64  		"required": func(string, interface{}) (interface{}, error) { return "not implemented", nil },
    65  		// Provide a placeholder for the "lookup" function, which requires a kubernetes
    66  		// connection.
    67  		"lookup": func(string, string, string, string) (map[string]interface{}, error) {
    68  			return map[string]interface{}{}, nil
    69  		},
    70  	}
    71  
    72  	for k, v := range extra {
    73  		f[k] = v
    74  	}
    75  
    76  	return f
    77  }
    78  
    79  // toYAML takes an interface, marshals it to yaml, and returns a string. It will
    80  // always return a string, even on marshal error (empty string).
    81  //
    82  // This is designed to be called from a template.
    83  func toYAML(v interface{}) string {
    84  	data, err := yaml.Marshal(v)
    85  	if err != nil {
    86  		// Swallow errors inside of a template.
    87  		return ""
    88  	}
    89  	return strings.TrimSuffix(string(data), "\n")
    90  }
    91  
    92  // fromYAML converts a YAML document into a map[string]interface{}.
    93  //
    94  // This is not a general-purpose YAML parser, and will not parse all valid
    95  // YAML documents. Additionally, because its intended use is within templates
    96  // it tolerates errors. It will insert the returned error message string into
    97  // m["Error"] in the returned map.
    98  func fromYAML(str string) map[string]interface{} {
    99  	m := map[string]interface{}{}
   100  
   101  	if err := yaml.Unmarshal([]byte(str), &m); err != nil {
   102  		m["Error"] = err.Error()
   103  	}
   104  	return m
   105  }
   106  
   107  // fromYAMLArray converts a YAML array into a []interface{}.
   108  //
   109  // This is not a general-purpose YAML parser, and will not parse all valid
   110  // YAML documents. Additionally, because its intended use is within templates
   111  // it tolerates errors. It will insert the returned error message string as
   112  // the first and only item in the returned array.
   113  func fromYAMLArray(str string) []interface{} {
   114  	a := []interface{}{}
   115  
   116  	if err := yaml.Unmarshal([]byte(str), &a); err != nil {
   117  		a = []interface{}{err.Error()}
   118  	}
   119  	return a
   120  }
   121  
   122  // toTOML takes an interface, marshals it to toml, and returns a string. It will
   123  // always return a string, even on marshal error (empty string).
   124  //
   125  // This is designed to be called from a template.
   126  func toTOML(v interface{}) string {
   127  	b := bytes.NewBuffer(nil)
   128  	e := toml.NewEncoder(b)
   129  	err := e.Encode(v)
   130  	if err != nil {
   131  		return err.Error()
   132  	}
   133  	return b.String()
   134  }
   135  
   136  // toJSON takes an interface, marshals it to json, and returns a string. It will
   137  // always return a string, even on marshal error (empty string).
   138  //
   139  // This is designed to be called from a template.
   140  func toJSON(v interface{}) string {
   141  	data, err := json.Marshal(v)
   142  	if err != nil {
   143  		// Swallow errors inside of a template.
   144  		return ""
   145  	}
   146  	return string(data)
   147  }
   148  
   149  // fromJSON converts a JSON document into a map[string]interface{}.
   150  //
   151  // This is not a general-purpose JSON parser, and will not parse all valid
   152  // JSON documents. Additionally, because its intended use is within templates
   153  // it tolerates errors. It will insert the returned error message string into
   154  // m["Error"] in the returned map.
   155  func fromJSON(str string) map[string]interface{} {
   156  	m := make(map[string]interface{})
   157  
   158  	if err := json.Unmarshal([]byte(str), &m); err != nil {
   159  		m["Error"] = err.Error()
   160  	}
   161  	return m
   162  }
   163  
   164  // fromJSONArray converts a JSON array into a []interface{}.
   165  //
   166  // This is not a general-purpose JSON parser, and will not parse all valid
   167  // JSON documents. Additionally, because its intended use is within templates
   168  // it tolerates errors. It will insert the returned error message string as
   169  // the first and only item in the returned array.
   170  func fromJSONArray(str string) []interface{} {
   171  	a := []interface{}{}
   172  
   173  	if err := json.Unmarshal([]byte(str), &a); err != nil {
   174  		a = []interface{}{err.Error()}
   175  	}
   176  	return a
   177  }