-
Notifications
You must be signed in to change notification settings - Fork 8
/
format.go
54 lines (45 loc) · 1.32 KB
/
format.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package functions
import (
"context"
"fmt"
"reflect"
"github.com/Velocidex/ordereddict"
"www.velocidex.com/golang/vfilter/arg_parser"
"www.velocidex.com/golang/vfilter/types"
)
type FormatArgs struct {
Format string `vfilter:"required,field=format,doc=Format string to use"`
Args types.Any `vfilter:"optional,field=args,doc=An array of elements to apply into the format string."`
}
type FormatFunction struct{}
func (self FormatFunction) Call(ctx context.Context,
scope types.Scope,
args *ordereddict.Dict) types.Any {
arg := &FormatArgs{}
err := arg_parser.ExtractArgs(scope, args, arg)
if err != nil {
scope.Log("format: %v", err)
return false
}
var format_args []interface{}
if arg.Args != nil {
slice := reflect.ValueOf(arg.Args)
// A slice of strings.
if slice.Type().Kind() != reflect.Slice {
format_args = append(format_args, arg.Args)
} else {
for i := 0; i < slice.Len(); i++ {
value := slice.Index(i).Interface()
format_args = append(format_args, value)
}
}
}
return fmt.Sprintf(arg.Format, format_args...)
}
func (self FormatFunction) Info(scope types.Scope, type_map *types.TypeMap) *types.FunctionInfo {
return &types.FunctionInfo{
Name: "format",
Doc: "Format one or more items according to a format string.",
ArgType: type_map.AddType(scope, &FormatArgs{}),
}
}