This repository has been archived by the owner on Jul 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Parse.go
77 lines (69 loc) · 1.87 KB
/
Parse.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package parse
import (
"github.com/SumoLogic/sumoshell/util"
"log"
"regexp"
"strings"
)
type Parser struct {
pattern string
extractions []string
regex *regexp.Regexp
output *util.JsonWriter
}
const Wildcard = '*'
const genericError = "parse takes arguments like: `parse \"[key=*]\" as key`\n"
func Build(args []string) (util.SumoOperator, error) {
// [parse x as y, z, w]
if len(args) < 2 {
log.Print("Error! No arguments provided.")
log.Print(genericError)
return nil, util.ParseError("Error! No arguments provided\n" + genericError)
}
parseExpression := args[1]
numExtractions := findNumExtractions(parseExpression)
// (parse pattern) (as) (foo, bar, baz)
expectedArgs := 2 + 1 + numExtractions
if len(args) < expectedArgs {
return nil, util.ParseError("Expected more arguments\n" + genericError)
}
as := args[2]
if as != "as" {
return nil, util.ParseError("Expected `as` got " + as + "\n" + genericError)
}
extractions := make([]string, len(args)-3)
for i, arg := range args[3:] {
extractions[i] = strings.Trim(arg, ",")
}
ret := Parser{parseExpression, extractions, regexFromPat(parseExpression), util.NewJsonWriter()}
return &ret, nil
}
func findNumExtractions(parseExpression string) int {
var count = 0
for _, element := range parseExpression {
if element == Wildcard {
count += 1
}
}
return count
}
func regexFromPat(pat string) *regexp.Regexp {
regex := ".*?" + strings.Replace(regexp.QuoteMeta(pat), "\\*", "(.*?)", -1)
if strings.HasSuffix(pat, "*") {
regex += "$"
} else {
regex += ".*$"
}
return regexp.MustCompile(regex)
}
func (p Parser) Process(inp map[string]interface{}) {
if util.IsPlus(inp) {
matches := p.regex.FindStringSubmatch(util.ExtractRaw(inp))
if len(matches) == 1+len(p.extractions) {
for i, match := range matches[1:] {
inp[p.extractions[i]] = match
}
p.output.Write(inp)
}
}
}