codegen

package
v1.39.0-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 18, 2024 License: Apache-2.0 Imports: 35 Imported by: 0

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

Examples

Constants

This section is empty.

Variables

View Source
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

func NewFuncMap(st *Stencil, t *Template, log logrus.FieldLogger) template.FuncMap

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

	// SkippedReason is the reason why this file was skipped
	SkippedReason string

	// 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

func NewFile(path string, mode os.FileMode, modTime time.Time) (*File, error)

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

func (f *File) AddDeprecationNotice(msg string)

AddDeprecationNotice adds a deprecation notice to a file

func (*File) Block

func (f *File) Block(name string) string

Block returns the contents of a given block.

func (*File) Bytes

func (f *File) Bytes() []byte

Bytes returns the contents of this file as bytes

func (*File) IsDir

func (f *File) IsDir() bool

IsDir returns if this is file is a directory or not Note: We only support rendering files currently

func (*File) ModTime

func (f *File) ModTime() time.Time

ModTime returns the last modification time for the file

func (*File) Mode

func (f *File) Mode() os.FileMode

Mode returns the file mode

func (*File) Name

func (f *File) Name() string

Name returns the name of the file

func (*File) SetContents

func (f *File) SetContents(contents string)

SetContents updates the contents of the current file

func (*File) SetMode added in v1.6.0

func (f *File) SetMode(mode os.FileMode)

SetMode updates the mode of the file

func (*File) SetPath

func (f *File) SetPath(path string) error

SetPath updates the path of this file. This causes the blocks to be parsed again.

func (*File) Size

func (f *File) Size() int64

Size returns the size of the file

func (*File) String

func (f *File) String() string

String returns the contents of this file as a string

func (*File) Sys

func (f *File) Sys() interface{}

Sys implements the os.FileInfo.Sys method. This does not do anything.

type Stencil

type Stencil struct {
	// contains filtered or unexported fields
}

Stencil provides the basic functions for stencil templates

func NewStencil

NewStencil creates a new, fully initialized Stencil renderer function

func (*Stencil) Close added in v1.26.0

func (s *Stencil) Close() error

Close closes all resources that should be closed when done rendering templates.

func (*Stencil) GenerateLockfile

func (s *Stencil) GenerateLockfile(tpls []*Template) *stencil.Lockfile

GenerateLockfile generates a stencil.Lockfile based on a list of templates.

func (*Stencil) PostRun

func (s *Stencil) PostRun(ctx context.Context, log logrus.FieldLogger) error

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

func (s *Stencil) RegisterExtensions(ctx context.Context) error

RegisterExtensions registers all extensions on the currently loaded modules.

func (*Stencil) RegisterInprocExtensions added in v1.20.0

func (s *Stencil) RegisterInprocExtensions(name string, ext apiv1.Implementation)

RegisterInprocExtensions registers the input ext extension directly. This API is used in unit tests to render modules with templates that invoke native extensions: input 'ext' can be either an actual extension or a mock one (feeding fake data into the template).

func (*Stencil) Render

func (s *Stencil) Render(ctx context.Context, log logrus.FieldLogger) ([]*Template, error)

Render renders all templates using the ServiceManifest that was provided to stencil at creation time, returned is the templates that were produced and their associated files.

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

func (t *Template) ImportPath() string

ImportPath returns the path to this template, this is meant to denote which module this template is attached to

func (*Template) Parse

func (t *Template) Parse(st *Stencil) error

Parse parses the provided template and makes it available to be Rendered in the context of the current module.

func (*Template) Render

func (t *Template) Render(st *Stencil, vals *Values) error

Render renders the provided template, the produced files are rendered onto the Files field of the template struct.

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

func (f *TplFile) Block(name string) string

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

func (f *TplFile) Create(path string, mode os.FileMode, modTime time.Time) (out, err error)

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) Delete

func (f *TplFile) Delete() error

Delete deletes the current file being rendered

{{ file.Delete }}

func (*TplFile) Path added in v1.11.1

func (f *TplFile) Path() string

Path returns the current path of the file we're writing to

{{ file.Path }}

func (*TplFile) RemoveAll added in v1.21.0

func (f *TplFile) RemoveAll(path string) (out, err error)

RemoveAll deletes all the contents in the provided path

{{ file.RemoveAll "path" }}

func (*TplFile) SetContents

func (f *TplFile) SetContents(contents string) error

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

func (f *TplFile) SetPath(path string) (out, err error)

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

func (f *TplFile) Skip(reason string) error

Skip skips the current file being rendered

{{ $_ := file.Skip "A reason to skip this reason" }}

func (*TplFile) Static added in v1.11.0

func (f *TplFile) Static() (out, err error)

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{}) (out, err 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" }}

Note: Using `stencil.Arg` with no path returns all arguments and is equivalent to `stencil.Args`. However, that is DEPRECATED along with `stencil.Args` as it doesn't provide default types, or check the JSON schema, or track which module calls what argument.

func (*TplStencil) Args deprecated

func (s *TplStencil) Args() map[string]interface{}

Deprecated: Use Arg instead. 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.

This is deprecated and will be removed in a future release.

{{- (stencil.Args).name }}

func (*TplStencil) Debug added in v1.32.0

func (s *TplStencil) Debug(args ...interface{}) error

Debug logs the provided arguments under the DEBUG log level (must run stencil with --debug).

{{- $_ := stencil.Debug "I'm a log!" }}

func (*TplStencil) Exists added in v1.28.0

func (s *TplStencil) Exists(name string) bool

Exists returns true if the file exists in the current directory

{{- if stencil.Exists "myfile.txt" }}
{{ stencil.ReadFile "myfile.txt" }}
{{- end }}

func (*TplStencil) GetGlobal added in v1.29.0

func (s *TplStencil) GetGlobal(name string) interface{}

GetGlobal retrieves a global variable set by SetGlobal. The data returned from this function is unstructured so by averse to panics - look at where it was set to ensure you're dealing with the proper type of data that you think it is.

{{- /* This retrieves a global from the current context of the template module repository */}}
{{ $isGeorgeCool := stencil.GetGlobal "IsGeorgeCool" }}

func (*TplStencil) GetModuleHook

func (s *TplStencil) GetModuleHook(name string) []any

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 []any, aka a list.

{{- /* This returns a []any */}}
{{ $hook := stencil.GetModuleHook "myModuleHook" }}
{{- range $hook }}
  {{ . }}
{{- end }}

func (*TplStencil) ReadBlocks added in v1.26.0

func (s *TplStencil) ReadBlocks(fpath string) (map[string]string, error)

ReadBlocks parses a file and attempts to read the blocks from it, and their data.

As a special case, if the file does not exist, an empty map is returned instead of an error.

**NOTE**: This function does not guarantee that blocks are able to be read during runtime. for example, if you try to read the blocks of a file from another module there is no guarantee that that file will exist before you run this function. Nor is there the ability to tell stencil to do that (stencil does not have any order guarantees). Keep that in mind when using this function.

{{- $blocks := stencil.ReadBlocks "myfile.txt" }}
{{- range $name, $data := $blocks }}
  {{- $name }}
  {{- $data }}
{{- end }}

func (*TplStencil) ReadFile added in v1.15.0

func (s *TplStencil) ReadFile(name string) (string, error)

ReadFile reads a file from the current directory and returns it's contents

{{ stencil.ReadFile "myfile.txt" }}

func (*TplStencil) SetGlobal added in v1.29.0

func (s *TplStencil) SetGlobal(name string, data interface{}) error

SetGlobal sets a global to be used in the context of the current template module repository. This is useful because sometimes you want to define variables inside of a helpers template file after doing manifest argument processing and then use them within one or more template files to be rendered; however, go templates limit the scope of symbols to the current template they are defined in, so this is not possible without external tooling like this function.

This template function stores (and its inverse, GetGlobal, retrieves) data that is not strongly typed, so use this at your own risk and be averse to panics that could occur if you're using the data it returns in the wrong way.

{{- /* This writes a global into the current context of the template module repository */}}
{{ stencil.SetGlobal "IsGeorgeCool" true }}

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

	// Module is information about the current module being rendered
	Module module

	// Template is the name of the template being rendered
	Template stencilTemplate
}

Values is the top level container for variables being passed to a stencil template.

func NewValues

func NewValues(ctx context.Context, sm *configuration.ServiceManifest, mods []*modules.Module) *Values

NewValues returns a fully initialized Values based on the current runtime environment.

func (*Values) Copy added in v1.28.0

func (v *Values) Copy() *Values

Copy returns a copy of the current values

func (*Values) WithModule added in v1.28.0

func (v *Values) WithModule(name, version string) *Values

WithModule returns a copy of the current values with the provided module information being set.

func (*Values) WithTemplate added in v1.28.0

func (v *Values) WithTemplate(name string) *Values

WithTemplate returns a copy of the current values with the provided template information being set.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL