github.com/pluralsh/plural-cli@v0.9.5/cmd/plural/template.go (about) 1 package plural 2 3 import ( 4 "bytes" 5 "io" 6 "os" 7 8 "github.com/pluralsh/gqlclient" 9 10 "github.com/pluralsh/plural-cli/pkg/api" 11 "github.com/pluralsh/plural-cli/pkg/config" 12 lua "github.com/pluralsh/plural-cli/pkg/scaffold/template" 13 "github.com/pluralsh/plural-cli/pkg/template" 14 "github.com/urfave/cli" 15 "gopkg.in/yaml.v2" 16 ) 17 18 func testTemplate(c *cli.Context) error { 19 conf := config.Read() 20 client := api.NewClient() 21 installations, _ := client.GetInstallations() 22 repoName := c.Args().Get(0) 23 templateTypeFlag := c.String("templateType") 24 templateType := gqlclient.TemplateTypeGotemplate 25 testTemplate, err := io.ReadAll(os.Stdin) 26 if err != nil { 27 return err 28 } 29 if templateTypeFlag != "" { 30 templateType = gqlclient.TemplateType(templateTypeFlag) 31 } 32 33 for _, installation := range installations { 34 if installation.Repository.Name != repoName { 35 continue 36 } 37 38 var output []byte 39 vals := genDefaultValues(conf, installation) 40 41 if templateType == gqlclient.TemplateTypeLua { 42 output, err = luaTmpValues(string(testTemplate), vals) 43 if err != nil { 44 return err 45 } 46 } else { 47 output, err = goTmpValues(string(testTemplate), vals) 48 if err != nil { 49 return err 50 } 51 } 52 if _, err := os.Stdout.Write(output); err != nil { 53 return err 54 } 55 } 56 57 return nil 58 } 59 60 func genDefaultValues(conf config.Config, installation *api.Installation) map[string]interface{} { 61 return map[string]interface{}{ 62 "Values": installation.Context, 63 "License": installation.LicenseKey, 64 "Region": "region", 65 "Project": "example", 66 "Cluster": "cluster", 67 "Provider": "provider", 68 "Config": conf, 69 "Context": map[string]interface{}{}, 70 } 71 } 72 73 func goTmpValues(valuesTmpl string, defaultValues map[string]interface{}) ([]byte, error) { 74 var buf bytes.Buffer 75 buf.Grow(5 * 1024) 76 tmpl, err := template.MakeTemplate(valuesTmpl) 77 if err != nil { 78 return nil, err 79 } 80 if err = tmpl.Execute(&buf, defaultValues); err != nil { 81 return nil, err 82 } 83 84 return buf.Bytes(), nil 85 } 86 87 func luaTmpValues(valuesTmpl string, defaultValues map[string]interface{}) ([]byte, error) { 88 output, err := lua.ExecuteLua(defaultValues, valuesTmpl) 89 if err != nil { 90 return nil, err 91 } 92 93 return yaml.Marshal(output) 94 } 95 96 type GrafanaDashboard struct { 97 Title string 98 Panels []struct { 99 Title string 100 Targets []struct { 101 Expr string 102 LegendFormat string 103 } 104 } 105 }