github.com/codefresh-io/kcfi@v0.0.0-20230301195427-c1578715cc46/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  	"io/ioutil"
    23  	"path"
    24  	"path/filepath"
    25  	"strings"
    26  	"text/template"
    27  
    28  	"github.com/BurntSushi/toml"
    29  	"github.com/Masterminds/sprig/v3"
    30  	"sigs.k8s.io/yaml"
    31  )
    32  
    33  // FuncMap returns a mapping of all of the functions that Engine has.
    34  //
    35  // Because some functions are late-bound (e.g. contain context-sensitive
    36  // data), the functions may not all perform identically outside of an Engine
    37  // as they will inside of an Engine.
    38  //
    39  // Known late-bound functions:
    40  //
    41  //	- "include"
    42  //	- "tpl"
    43  //
    44  // These are late-bound in Engine.Render().  The
    45  // version included in the FuncMap is a placeholder.
    46  //
    47  func FuncMap() template.FuncMap {
    48  	f := sprig.TxtFuncMap()
    49  	// delete(f, "env")
    50  	// delete(f, "expandenv")
    51  
    52  	// Add some extra functionality
    53  	extra := template.FuncMap{
    54  		"toToml":        toTOML,
    55  		"toYaml":        toYAML,
    56  		"fromYaml":      fromYAML,
    57  		"fromYamlArray": fromYAMLArray,
    58  		"toJson":        toJSON,
    59  		"fromJson":      fromJSON,
    60  		"fromJsonArray": fromJSONArray,
    61  
    62  		"getFileWithBaseDir": getFileWithBaseDir,
    63  
    64  		// This is a placeholder for the "include" function, which is
    65  		// late-bound to a template. By declaring it here, we preserve the
    66  		// integrity of the linter.
    67  		"include":  func(string, interface{}) string { return "not implemented" },
    68  		"tpl":      func(string, interface{}) interface{} { return "not implemented" },
    69  		"required": func(string, interface{}) (interface{}, error) { return "not implemented", nil },
    70  		// Provide a placeholder for the "lookup" function, which requires a kubernetes
    71  		// connection.
    72  		"lookup": func(string, string, string, string) (map[string]interface{}, error) {
    73  			return map[string]interface{}{}, nil
    74  		},
    75  	}
    76  
    77  	for k, v := range extra {
    78  		f[k] = v
    79  	}
    80  
    81  	return f
    82  }
    83  
    84  // toYAML takes an interface, marshals it to yaml, and returns a string. It will
    85  // always return a string, even on marshal error (empty string).
    86  //
    87  // This is designed to be called from a template.
    88  func toYAML(v interface{}) string {
    89  	data, err := yaml.Marshal(v)
    90  	if err != nil {
    91  		// Swallow errors inside of a template.
    92  		return ""
    93  	}
    94  	return strings.TrimSuffix(string(data), "\n")
    95  }
    96  
    97  // fromYAML converts a YAML document into a map[string]interface{}.
    98  //
    99  // This is not a general-purpose YAML parser, and will not parse all valid
   100  // YAML documents. Additionally, because its intended use is within templates
   101  // it tolerates errors. It will insert the returned error message string into
   102  // m["Error"] in the returned map.
   103  func fromYAML(str string) map[string]interface{} {
   104  	m := map[string]interface{}{}
   105  
   106  	if err := yaml.Unmarshal([]byte(str), &m); err != nil {
   107  		m["Error"] = err.Error()
   108  	}
   109  	return m
   110  }
   111  
   112  // fromYAMLArray converts a YAML array into a []interface{}.
   113  //
   114  // This is not a general-purpose YAML parser, and will not parse all valid
   115  // YAML documents. Additionally, because its intended use is within templates
   116  // it tolerates errors. It will insert the returned error message string as
   117  // the first and only item in the returned array.
   118  func fromYAMLArray(str string) []interface{} {
   119  	a := []interface{}{}
   120  
   121  	if err := yaml.Unmarshal([]byte(str), &a); err != nil {
   122  		a = []interface{}{err.Error()}
   123  	}
   124  	return a
   125  }
   126  
   127  // toTOML takes an interface, marshals it to toml, and returns a string. It will
   128  // always return a string, even on marshal error (empty string).
   129  //
   130  // This is designed to be called from a template.
   131  func toTOML(v interface{}) string {
   132  	b := bytes.NewBuffer(nil)
   133  	e := toml.NewEncoder(b)
   134  	err := e.Encode(v)
   135  	if err != nil {
   136  		return err.Error()
   137  	}
   138  	return b.String()
   139  }
   140  
   141  // toJSON takes an interface, marshals it to json, and returns a string. It will
   142  // always return a string, even on marshal error (empty string).
   143  //
   144  // This is designed to be called from a template.
   145  func toJSON(v interface{}) string {
   146  	data, err := json.Marshal(v)
   147  	if err != nil {
   148  		// Swallow errors inside of a template.
   149  		return ""
   150  	}
   151  	return string(data)
   152  }
   153  
   154  // fromJSON converts a JSON document into a map[string]interface{}.
   155  //
   156  // This is not a general-purpose JSON parser, and will not parse all valid
   157  // JSON documents. Additionally, because its intended use is within templates
   158  // it tolerates errors. It will insert the returned error message string into
   159  // m["Error"] in the returned map.
   160  func fromJSON(str string) map[string]interface{} {
   161  	m := make(map[string]interface{})
   162  
   163  	if err := json.Unmarshal([]byte(str), &m); err != nil {
   164  		m["Error"] = err.Error()
   165  	}
   166  	return m
   167  }
   168  
   169  // fromJSONArray converts a JSON array into a []interface{}.
   170  //
   171  // This is not a general-purpose JSON parser, and will not parse all valid
   172  // JSON documents. Additionally, because its intended use is within templates
   173  // it tolerates errors. It will insert the returned error message string as
   174  // the first and only item in the returned array.
   175  func fromJSONArray(str string) []interface{} {
   176  	a := []interface{}{}
   177  
   178  	if err := json.Unmarshal([]byte(str), &a); err != nil {
   179  		a = []interface{}{err.Error()}
   180  	}
   181  	return a
   182  }
   183  
   184  func getFileWithBaseDir(filename, basedir string) string {
   185  	var filePath string
   186  	if filepath.IsAbs(filename) {
   187  		filePath = filename
   188  	} else {
   189  		filePath = path.Join(basedir, filename)
   190  	}
   191  
   192  	fileB, err := ioutil.ReadFile(filePath)
   193  	if err != nil {
   194  		panic(err)
   195  	}
   196  	return string(fileB)
   197  
   198  }