2023-10-29 22:47:47 +00:00
|
|
|
package salix
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
|
2023-10-31 01:38:53 +00:00
|
|
|
"go.elara.ws/salix/ast"
|
2023-10-29 22:47:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrIncludeInvalidArgs = errors.New("include expects one string argument")
|
|
|
|
ErrNoSuchTemplate = errors.New("no such template")
|
|
|
|
)
|
|
|
|
|
2023-10-30 02:56:15 +00:00
|
|
|
// includeTag represents an #include tag within a Salix template
|
2023-10-29 22:47:47 +00:00
|
|
|
type includeTag struct{}
|
|
|
|
|
|
|
|
func (it includeTag) Run(tc *TagContext, block, args []ast.Node) error {
|
2023-10-31 20:45:00 +00:00
|
|
|
if len(args) < 1 {
|
2023-12-18 00:55:13 +00:00
|
|
|
return tc.PosError(tc.Tag, "expected at least one argument, got %d", len(args))
|
2023-10-29 22:47:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
val, err := tc.GetValue(args[0], nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
name, ok := val.(string)
|
|
|
|
if !ok {
|
2023-12-18 00:55:13 +00:00
|
|
|
return tc.PosError(args[0], "invalid first argument type: %T (expected string)", val)
|
2023-10-29 22:47:47 +00:00
|
|
|
}
|
|
|
|
|
2024-02-20 20:10:23 +00:00
|
|
|
ignoreMissing := false
|
|
|
|
if name[0] == '?' {
|
|
|
|
name = name[1:]
|
|
|
|
ignoreMissing = true
|
|
|
|
}
|
|
|
|
|
2023-10-29 22:47:47 +00:00
|
|
|
tmpl, ok := tc.t.ns.GetTemplate(name)
|
|
|
|
if !ok {
|
2024-02-20 20:10:23 +00:00
|
|
|
if ignoreMissing {
|
|
|
|
return nil
|
|
|
|
}
|
2023-12-18 00:55:13 +00:00
|
|
|
return tc.PosError(args[0], "no such template: %q", name)
|
2023-10-29 22:47:47 +00:00
|
|
|
}
|
|
|
|
|
2023-10-31 20:45:00 +00:00
|
|
|
local := map[string]any{}
|
|
|
|
|
|
|
|
// Use the variable assignments after the first argument
|
|
|
|
// to set the local variables of the execution
|
|
|
|
for _, arg := range args[1:] {
|
|
|
|
if a, ok := arg.(ast.Assignment); ok {
|
|
|
|
val, err := tc.GetValue(a.Value, local)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
local[a.Name.Value] = val
|
|
|
|
} else {
|
2023-12-18 00:55:13 +00:00
|
|
|
// If the argument isn't an assigment, return an error
|
|
|
|
return tc.PosError(tc.Tag, "invalid argument type: %T (expected ast.Assignment)", val)
|
2023-10-31 20:45:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return tc.Execute(tmpl.ast, local)
|
2023-10-29 22:47:47 +00:00
|
|
|
}
|