Documentation ¶
Overview ¶
Package codegen implements the core code generation functionality of stencil. This package contains everything from the template functions exposed to stencil templates, to the core stencil renderer that powers everything.
package codegen provides funcutions to stencil templates.
Description: Implements the stencil function passed to templates
Description: This file contains the logic and type for a template that is being rendered by stencil.
Example (FromJson) ¶
example := ` { "a": "b", "c": "d" } ` fmt.Println(fromJSON(example))
Output: map[a:b c:d] <nil>
Example (FromYaml) ¶
example := ` a: b c: d ` fmt.Println(fromYAML(example))
Output: map[a:b c:d] <nil>
Example (Quotejoinstrings) ¶
example := []string{"a", "b", "c"} fmt.Println(quotejoinstrings(example, " "))
Output: "a" "b" "c"
Example (ToJson) ¶
example := map[string]interface{}{ "a": "b", "c": "d", } fmt.Println(toJSON(example))
Output: {"a":"b","c":"d"} <nil>
Example (ToYaml) ¶
example := map[string]interface{}{ "a": "b", "c": "d", } fmt.Println(toYAML(example))
Output: a: b c: d <nil>
Index ¶
- Variables
- func NewFuncMap(st *Stencil, t *Template, log logrus.FieldLogger) template.FuncMap
- type File
- func (f *File) AddDeprecationNotice(msg string)
- func (f *File) Block(name string) string
- func (f *File) Bytes() []byte
- func (f *File) IsDir() bool
- func (f *File) ModTime() time.Time
- func (f *File) Mode() os.FileMode
- func (f *File) Name() string
- func (f *File) SetContents(contents string)
- func (f *File) SetMode(mode os.FileMode)
- func (f *File) SetPath(path string) error
- func (f *File) Size() int64
- func (f *File) String() string
- func (f *File) Sys() interface{}
- type Stencil
- func (s *Stencil) GenerateLockfile(tpls []*Template) *stencil.Lockfile
- func (s *Stencil) PostRun(ctx context.Context, log logrus.FieldLogger) error
- func (s *Stencil) RegisterExtensions(ctx context.Context) error
- func (s *Stencil) Render(ctx context.Context, log logrus.FieldLogger) ([]*Template, error)
- type Template
- type TplFile
- func (f *TplFile) Block(name string) string
- func (f *TplFile) Create(path string, mode os.FileMode, modTime time.Time) error
- func (f *TplFile) Delete() error
- func (f *TplFile) Path() string
- func (f *TplFile) SetContents(contents string) error
- func (f *TplFile) SetPath(path string) error
- func (f *TplFile) Skip(_ string) error
- func (f *TplFile) Static() error
- type TplStencil
- func (s *TplStencil) AddToModuleHook(module, name string, data interface{}) error
- func (s *TplStencil) ApplyTemplate(name string, dataSli ...interface{}) (string, error)
- func (s *TplStencil) Arg(pth string) (interface{}, error)
- func (s *TplStencil) Args() map[string]interface{}
- func (s *TplStencil) GetModuleHook(name string) []interface{}
- func (s *TplStencil) ReadFile(name string) (string, error)
- type Values
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var Default = template.FuncMap{
"Dereference": dereference,
"QuoteJoinStrings": quotejoinstrings,
"toYaml": toYAML,
"fromYaml": fromYAML,
"toJson": toJSON,
"fromJson": fromJSON,
}
Default are stock template functions that don't impact the generation of a file. Anything that does that should be located in the scope of the file renderer function instead
Functions ¶
func NewFuncMap ¶
NewFuncMap returns the standard func map for a template
Types ¶
type File ¶
type File struct { // Deleted denotes this file as being deleted, if this is // true then f.contents should not be used. Deleted bool // Skipped denotes this file as being skipped, if this is // true then f.contents should not be used. Skipped bool // Warnings is an array of warnings that were created // while rendering this template Warnings []string // contains filtered or unexported fields }
File is a file that was created by a rendered template
func NewFile ¶
NewFile creates a new file, an existing file at the given path is parsed to read blocks from, if it exists. An error is returned if the file is unable to be read for a reason other than not existing.
func (*File) AddDeprecationNotice ¶
AddDeprecationNotice adds a deprecation notice to a file
func (*File) IsDir ¶
IsDir returns if this is file is a directory or not Note: We only support rendering files currently
func (*File) SetContents ¶
SetContents updates the contents of the current file
func (*File) SetPath ¶
SetPath updates the path of this file. This causes the blocks to be parsed again.
type Stencil ¶
type Stencil struct {
// contains filtered or unexported fields
}
Stencil provides the basic functions for stencil templates
func NewStencil ¶
func NewStencil(m *configuration.ServiceManifest, mods []*modules.Module, log logrus.FieldLogger) *Stencil
NewStencil creates a new, fully initialized Stencil renderer function
func (*Stencil) GenerateLockfile ¶
GenerateLockfile generates a stencil.Lockfile based on a list of templates.
func (*Stencil) PostRun ¶
PostRun runs all post run commands specified in the modules that this service depends on
Example ¶
fs := memfs.New() ctx := context.Background() // create a stub manifest f, _ := fs.Create("manifest.yaml") f.Write([]byte("name: testing\npostRunCommand:\n- command: echo \"hello\"")) f.Close() nullLog := logrus.New() nullLog.SetOutput(io.Discard) st := NewStencil(&configuration.ServiceManifest{ Name: "test", Arguments: map[string]interface{}{}, }, []*modules.Module{ modules.NewWithFS(ctx, "testing", fs), }, logrus.New()) err := st.PostRun(ctx, nullLog) if err != nil { fmt.Println(err) }
Output: hello
func (*Stencil) RegisterExtensions ¶
RegisterExtensions registers all extensions on the currently loaded modules.
type Template ¶
type Template struct { // Module is the underlying module that's creating this template Module *modules.Module // Path is the path of this template relative to the owning module Path string // Files is a list of files that this template generated Files []*File // Contents is the content of this template Contents []byte // contains filtered or unexported fields }
Template is a file that has been processed by stencil
func NewTemplate ¶
func NewTemplate(m *modules.Module, fpath string, mode os.FileMode, modTime time.Time, contents []byte, log logrus.FieldLogger) (*Template, error)
NewTemplate creates a new Template with the current file being the same name with the extension .tpl being removed.
func (*Template) ImportPath ¶
ImportPath returns the path to this template, this is meant to denote which module this template is attached to
type TplFile ¶
type TplFile struct {
// contains filtered or unexported fields
}
TplFile is the current file we're writing output to in a template. This can be changed via file.SetPath and written to by file.Install. When a template does not call file.SetPath a default file is created that matches the current template path with the extension '.tpl' removed from the path and operated on.
func (*TplFile) Block ¶
Block returns the contents of a given block
###Block(name) Hello, world! ###EndBlock(name) ###Block(name) {{- /* Only output if the block is set */}} {{- if not (empty (file.Block "name")) }} {{ file.Block "name" }} {{- end }} ###EndBlock(name) ###Block(name) {{ - /* Short hand syntax, but adds newline if no contents */}} {{ file.Block "name" }} ###EndBlock(name)
func (*TplFile) Create ¶
Create creates a new file that is rendered by the current template
If the template has a single file with no contents this file replaces it.
{{- define "command" }} package main import "fmt" func main() { fmt.Println("hello, world!") } {{- end }} # Generate a "<commandName>.go" file for each command in .arguments.commands {{- range $_, $commandName := (stencil.Arg "commands") }} {{- file.Create (printf "cmd/%s.go" $commandName) 0600 now }} {{- stencil.ApplyTemplate "command" | file.SetContents }} {{- end }}
func (*TplFile) Path ¶ added in v1.11.1
Path returns the current path of the file we're writing to
{{ file.Path }}
func (*TplFile) SetContents ¶
SetContents sets the contents of file being rendered to the value
This is useful for programmatic file generation within a template.
{{ file.SetContents "Hello, world!" }}
func (*TplFile) SetPath ¶
SetPath changes the path of the current file being rendered
{{ $_ := file.SetPath "new/path/to/file.txt" }}
Note: The $_ is required to ensure <nil> isn't outputted into the template.
func (*TplFile) Skip ¶
Skip skips the current file being rendered
{{ $_ := file.Skip "A reason to skip this reason" }}
func (*TplFile) Static ¶ added in v1.11.0
Static marks the current file as static
Marking a file is equivalent to calling file.Skip, but instead file.Skip is only called if the file already exists. This is useful for files you want to generate but only once. It's generally recommended that you do not do this as it limits your ability to change the file in the future.
{{ $_ := file.Static }}
type TplStencil ¶
type TplStencil struct {
// contains filtered or unexported fields
}
TplStencil contains the global functions available to a template for interacting with stencil.
func (*TplStencil) AddToModuleHook ¶
func (s *TplStencil) AddToModuleHook(module, name string, data interface{}) error
AddToModuleHook adds to a hook in another module
This functions write to module hook owned by another module for it to operate on. These are not strongly typed so it's best practice to look at how the owning module uses it for now. Module hooks must always be written to with a list to ensure that they can always be written to multiple times.
{{- /* This writes to a module hook */}} {{ stencil.AddToModuleHook "github.com/myorg/repo" "myModuleHook" (list "myData") }}
func (*TplStencil) ApplyTemplate ¶
func (s *TplStencil) ApplyTemplate(name string, dataSli ...interface{}) (string, error)
ApplyTemplate executes a template inside of the current module
This function does not support rendering a template from another module.
{{- define "command"}} package main import "fmt" func main() { fmt.Println("hello, world!") } {{- end }} {{- stencil.ApplyTemplate "command" | file.SetContents }}
func (*TplStencil) Arg ¶
func (s *TplStencil) Arg(pth string) (interface{}, error)
Arg returns the value of an argument in the service's manifest
{{- stencil.Arg "name" }}
func (*TplStencil) Args ¶
func (s *TplStencil) Args() map[string]interface{}
Args returns all arguments passed to stencil from the service's manifest
Note: This doesn't set default values and is instead representative of _all_ data passed in its raw form.
{{- (stencil.Args).name }}
func (*TplStencil) GetModuleHook ¶
func (s *TplStencil) GetModuleHook(name string) []interface{}
GetModuleHook returns a module block in the scope of this module
This is incredibly useful for allowing other modules to write to files that your module owns. Think of them as extension points for your module. The value returned by this function is always a []interface{}, aka a list.
{{- /* This returns a []interface{} */}} {{ $hook := stencil.GetModuleHook "myModuleHook" }} {{- range $hook }} {{ . }} {{- end }}
type Values ¶
type Values struct { // Git is information about the current git repository, if there is one Git *git // Runtime is information about the current runtime environment Runtime *runtime // Config is strongly type values from the service manifest Config *config }
Values is the top level container for variables being passed to a stencil template.
func NewValues ¶
func NewValues(ctx context.Context, sm *configuration.ServiceManifest) *Values
NewValues returns a fully initialized Values based on the current runtime environment.