mirror of
https://github.com/go-task/task.git
synced 2024-12-16 10:59:23 +02:00
6ed30f1add
This shouldn't have any behavior changes for now. This is a code refactor that should allow us to do further improvements on how variables are handled, specially regarding respecting the declaration order in Taskfiles, which should make it easier for the users. Initial work on #218
81 lines
1.5 KiB
Go
81 lines
1.5 KiB
Go
package templater
|
|
|
|
import (
|
|
"bytes"
|
|
"text/template"
|
|
|
|
"github.com/go-task/task/v2/internal/taskfile"
|
|
)
|
|
|
|
// Templater is a help struct that allow us to call "replaceX" funcs multiple
|
|
// times, without having to check for error each time. The first error that
|
|
// happen will be assigned to r.err, and consecutive calls to funcs will just
|
|
// return the zero value.
|
|
type Templater struct {
|
|
Vars *taskfile.Vars
|
|
|
|
cacheMap map[string]interface{}
|
|
err error
|
|
}
|
|
|
|
func (r *Templater) ResetCache() {
|
|
r.cacheMap = r.Vars.ToCacheMap()
|
|
}
|
|
|
|
func (r *Templater) Replace(str string) string {
|
|
if r.err != nil || str == "" {
|
|
return ""
|
|
}
|
|
|
|
templ, err := template.New("").Funcs(templateFuncs).Parse(str)
|
|
if err != nil {
|
|
r.err = err
|
|
return ""
|
|
}
|
|
|
|
if r.cacheMap == nil {
|
|
r.cacheMap = r.Vars.ToCacheMap()
|
|
}
|
|
|
|
var b bytes.Buffer
|
|
if err = templ.Execute(&b, r.cacheMap); err != nil {
|
|
r.err = err
|
|
return ""
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
func (r *Templater) ReplaceSlice(strs []string) []string {
|
|
if r.err != nil || len(strs) == 0 {
|
|
return nil
|
|
}
|
|
|
|
new := make([]string, len(strs))
|
|
for i, str := range strs {
|
|
new[i] = r.Replace(str)
|
|
}
|
|
return new
|
|
}
|
|
|
|
func (r *Templater) ReplaceVars(vars *taskfile.Vars) *taskfile.Vars {
|
|
if r.err != nil || vars == nil || len(vars.Keys) == 0 {
|
|
return nil
|
|
}
|
|
|
|
var new taskfile.Vars
|
|
vars.Range(func(k string, v taskfile.Var) error {
|
|
new.Set(k, taskfile.Var{
|
|
Static: r.Replace(v.Static),
|
|
Live: v.Live,
|
|
Sh: r.Replace(v.Sh),
|
|
})
|
|
return nil
|
|
})
|
|
|
|
return &new
|
|
}
|
|
|
|
func (r *Templater) Err() error {
|
|
return r.err
|
|
}
|