mirror of
https://github.com/anchore/syft.git
synced 2025-11-17 16:33:21 +01:00
* add template output Signed-off-by: Jonas Xavier <jonasx@anchore.com> * remove dead code Signed-off-by: Jonas Xavier <jonasx@anchore.com> * fix template cli flag Signed-off-by: Jonas Xavier <jonasx@anchore.com> * implement template's own format type Signed-off-by: Jonas Xavier <jonasx@anchore.com> * simpler code Signed-off-by: Jonas Xavier <jonasx@anchore.com> * fix readme link to Go template Signed-off-by: Jonas Xavier <jonasx@anchore.com> * feedback changes Signed-off-by: Jonas Xavier <jonasx@anchore.com> * simpler func signature patter Signed-off-by: Jonas Xavier <jonasx@anchore.com> * nit Signed-off-by: Jonas Xavier <jonasx@anchore.com> * fix linter error Signed-off-by: Jonas Xavier <jonasx@anchore.com>
50 lines
1.2 KiB
Go
50 lines
1.2 KiB
Go
package template
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"reflect"
|
|
"text/template"
|
|
|
|
"github.com/Masterminds/sprig/v3"
|
|
"github.com/mitchellh/go-homedir"
|
|
)
|
|
|
|
func makeTemplateExecutor(templateFilePath string) (*template.Template, error) {
|
|
if templateFilePath == "" {
|
|
return nil, errors.New("no template file: please provide a template path")
|
|
}
|
|
|
|
expandedPathToTemplateFile, err := homedir.Expand(templateFilePath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unable to expand path %s", templateFilePath)
|
|
}
|
|
|
|
templateContents, err := os.ReadFile(expandedPathToTemplateFile)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unable to get template content: %w", err)
|
|
}
|
|
|
|
templateName := expandedPathToTemplateFile
|
|
tmpl, err := template.New(templateName).Funcs(funcMap).Parse(string(templateContents))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unable to parse template: %w", err)
|
|
}
|
|
|
|
return tmpl, nil
|
|
}
|
|
|
|
// These are custom functions available to template authors.
|
|
var funcMap = func() template.FuncMap {
|
|
f := sprig.HermeticTxtFuncMap()
|
|
f["getLastIndex"] = func(collection interface{}) int {
|
|
if v := reflect.ValueOf(collection); v.Kind() == reflect.Slice {
|
|
return v.Len() - 1
|
|
}
|
|
|
|
return 0
|
|
}
|
|
return f
|
|
}()
|