lang: interfaces, funcs: Implement fmt.Stringer for functions

This adds the requirement that all function implementations provider a
String() string method so that these can be used as vertices in the
pgraph library. If we eventually move to generics for the pgraph DAG,
then this might not matter, but it's not bad that these have names
either.
This commit is contained in:
James Shubin
2023-03-03 14:12:09 -05:00
parent 8366cf0873
commit 5d664855de
35 changed files with 365 additions and 39 deletions

View File

@@ -31,17 +31,10 @@ import (
"github.com/purpleidea/mgmt/util/errwrap"
)
var (
// errorType represents a reflection type of error as seen in:
// https://github.com/golang/go/blob/ec62ee7f6d3839fe69aeae538dadc1c9dc3bf020/src/text/template/exec.go#L612
errorType = reflect.TypeOf((*error)(nil)).Elem()
)
func init() {
funcs.Register("template", func() interfaces.Func { return &TemplateFunc{} })
}
const (
// TemplateFuncName is the name this function is registered as.
TemplateFuncName = "template"
// TemplateName is the name of our template as required by the template
// library.
TemplateName = "template"
@@ -50,6 +43,16 @@ const (
argNameVars = "vars"
)
var (
// errorType represents a reflection type of error as seen in:
// https://github.com/golang/go/blob/ec62ee7f6d3839fe69aeae538dadc1c9dc3bf020/src/text/template/exec.go#L612
errorType = reflect.TypeOf((*error)(nil)).Elem()
)
func init() {
funcs.Register(TemplateFuncName, func() interfaces.Func { return &TemplateFunc{} })
}
// TemplateFunc is a static polymorphic function that compiles a template and
// returns the output as a string. It bases its output on the values passed in
// to it. It examines the type of the second argument (the input data vars) at
@@ -73,6 +76,12 @@ type TemplateFunc struct {
closeChan chan struct{}
}
// String returns a simple name for this function. This is needed so this struct
// can satisfy the pgraph.Vertex interface.
func (obj *TemplateFunc) String() string {
return TemplateFuncName
}
// ArgGen returns the Nth arg name for this function.
func (obj *TemplateFunc) ArgGen(index int) (string, error) {
seq := []string{argNameTemplate, argNameVars}