text/expander-base-funcs.go

97 lines
2.8 KiB
Go

// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
// expander-base-funcs.go
package text
import (
"strings"
)
func ExFuncDefault(ctx ExpanderContext, varValue string, args []string) (result string, err error) {
if len(varValue) > 0 {
result = varValue
} else if len(args) > 0 {
if len(args) == 1 {
result = args[0]
} else if len(args) > 1 {
result = strings.Join(args[1:], args[0])
}
}
return
}
func ExFuncUpper(ctx ExpanderContext, varValue string, args []string) (result string, err error) {
result = strings.ToUpper(varValue)
return
}
func ExFuncLower(ctx ExpanderContext, varValue string, args []string) (result string, err error) {
result = strings.ToLower(varValue)
return
}
func ExFuncJoin(ctx ExpanderContext, varValue string, args []string) (result string, err error) {
if len(args) > 0 {
result = strings.Join(args[1:], args[0])
}
return
}
func ExFuncSet(ctx ExpanderContext, varValue string, args []string) (result string, err error) {
if len(args) == 1 {
result = ctx.SetVar(args[0], varValue)
} else if len(args) > 1 {
result = ctx.SetVar(args[0], args[1])
} else {
result = varValue
}
return
}
func ExFuncGet(ctx ExpanderContext, varValue string, args []string) (result string, err error) {
var found bool
if len(args) == 0 {
result, found = ctx.GetVar(varValue)
} else {
result, found = ctx.GetVar(args[0])
if !found && len(args) > 1 {
result = args[1]
}
}
return
}
func ExFuncTrimSuffix(ctx ExpanderContext, varValue string, args []string) (result string, err error) {
if len(args) == 0 {
if pos := strings.LastIndexByte(varValue, '.'); pos >= 0 {
result = varValue[:pos]
}
} else {
found := false
for _, arg := range args {
if remainder := strings.TrimSuffix(varValue, arg); remainder != varValue {
result = remainder
found = true
break
}
}
if !found {
result = varValue
}
}
return
}
func AddBaseFuncs(ctx ExpanderContext) ExpanderContext {
ctx.AddFunc("__default", ExFuncDefault, 0, -1, "Returns the flow value if not empty, else all args joined; first arg is used as separator.")
ctx.AddFunc("__get", ExFuncGet, 0, 2, "Returns the value of the specified variable (arg1). With no arguments it returns the value of the variable having the flow value as name (same as __get ${.}). Arg2 is the default value. ")
ctx.AddFunc("__set", ExFuncSet, 1, 2, "Sets the value (arg2 or flow) of the specified variables (arg1).")
ctx.AddFunc("__join", ExFuncJoin, 1, -1, "Joins its args starting from the second. The first one (arg1) is the separator")
ctx.AddFunc("__lower", ExFuncLower, 0, 0, "Changes the flow value to lower case.")
ctx.AddFunc("__upper", ExFuncUpper, 0, 0, "Changes the flow value to upper case.")
ctx.AddFunc("__trim-suffix", ExFuncTrimSuffix, 1, 1, "Removes the specified suffix (arg1) from the flow.")
return ctx
}