core/generate/template.go
core/generate/template.goBrowse 1970 files
275 tokens
1,087 bytes
Token encoding: o200k_base
Snapshot 21a254f
← Back to SKILL.md
1package generate2 3import (4 "bytes"5 "errors"6 "fmt"7 "text/template"8 9 "github.com/railwayapp/railpack/core/app"10)11 12type TemplateFileResult struct {13 Filename string14 Contents string15}16 17// TemplateFiles will look the first file that exists in the list of potential files and render it with the given data18// If no file is found, it will use the default contents and render it with the given data19func (c *GenerateContext) TemplateFiles(potentialFiles []string, defaultContents string, data map[string]any) (*TemplateFileResult, error) {20 filename, contents, err := c.App.ReadFirstFileOf(potentialFiles...)21 if err != nil {22 if !errors.Is(err, app.ErrNoFileFound) {23 return nil, err24 }25 26 contents = defaultContents27 }28 29 tmpl, err := template.New(filename).Parse(contents)30 if err != nil {31 return nil, fmt.Errorf("failed to parse template: %w", err)32 }33 34 var buf bytes.Buffer35 if err := tmpl.Execute(&buf, data); err != nil {36 return nil, fmt.Errorf("failed to execute template: %w", err)37 }38 39 return &TemplateFileResult{40 Filename: filename,41 Contents: buf.String(),42 }, nil43}44