Added map-lines and upgraded UCL
All checks were successful
Release Build / build (push) Successful in 1m52s
All checks were successful
Release Build / build (push) Successful in 1m52s
This commit is contained in:
parent
18604ec5a6
commit
add62fbfa0
7 changed files with 63 additions and 5 deletions
51
plugins.go
51
plugins.go
|
|
@ -1,6 +1,8 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
|
@ -18,7 +20,6 @@ const pluginKeyPrefix = "plugin:"
|
|||
|
||||
// PluginFilters is the registry of text filters defined by UCL plugin files.
|
||||
type PluginFilters struct {
|
||||
inst *ucl.Inst
|
||||
filters map[string]TextProcessor
|
||||
errors []error
|
||||
}
|
||||
|
|
@ -34,7 +35,8 @@ func (p *PluginFilters) Module() ucl.Module {
|
|||
return ucl.Module{
|
||||
Name: "d",
|
||||
Builtins: map[string]ucl.BuiltinHandler{
|
||||
"filter": p.filterBuiltin,
|
||||
"filter": p.filterBuiltin,
|
||||
"map-lines": p.mapLinesBuiltin,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -78,6 +80,51 @@ func (p *PluginFilters) filterBuiltin(ctx context.Context, args ucl.CallArgs) (a
|
|||
return nil, nil
|
||||
}
|
||||
|
||||
// mapLinesBuiltin implements `d:map-lines INPUT PROC` which applies a transform for each line of the input.
|
||||
func (p *PluginFilters) mapLinesBuiltin(ctx context.Context, args ucl.CallArgs) (any, error) {
|
||||
var (
|
||||
input string
|
||||
proc ucl.Invokable
|
||||
)
|
||||
|
||||
if err := args.Bind(&input, &proc); err != nil {
|
||||
return nil, fmt.Errorf("d:map-lines: expected INPUT and PROC: %w", err)
|
||||
}
|
||||
|
||||
var (
|
||||
dst bytes.Buffer
|
||||
dstLine bytes.Buffer
|
||||
)
|
||||
|
||||
scnr := bufio.NewScanner(strings.NewReader(input))
|
||||
isFirst := true
|
||||
for scnr.Scan() {
|
||||
dstLine.Reset()
|
||||
line := scnr.Text()
|
||||
|
||||
out, err := proc.Invoke(ctx, line)
|
||||
if err != nil {
|
||||
return TextFilterResponse{}, err
|
||||
} else if out == nil {
|
||||
continue
|
||||
} else if strOut, ok := out.(fmt.Stringer); ok {
|
||||
dstLine.WriteString(strOut.String())
|
||||
} else {
|
||||
dstLine.WriteString(fmt.Sprint(out))
|
||||
}
|
||||
|
||||
if isFirst {
|
||||
isFirst = false
|
||||
} else {
|
||||
dst.WriteString("\n")
|
||||
}
|
||||
|
||||
dst.WriteString(dstLine.String())
|
||||
}
|
||||
|
||||
return dst.String(), nil
|
||||
}
|
||||
|
||||
// LoadDir evaluates every *.ucl file found under dir (recursively, in lexical order). Files
|
||||
// that fail to load are recorded in Errors() and skipped; loading continues with the rest.
|
||||
// A missing directory is not an error.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue