-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfilterspec.go
51 lines (46 loc) · 1.11 KB
/
filterspec.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
package nettrigger
import (
"fmt"
"strings"
)
// FilterSpec is a parsed filter specification.
type FilterSpec struct {
Type string
Args []string
}
// Arg returns the argument with the nth index.
//
// An empty string is returned if the argument doesn't exist.
func (spec FilterSpec) Arg(n int) string {
if n >= len(spec.Args) {
return ""
}
return spec.Args[n]
}
// ParseFilter parses v as a string representation of a filter.
func ParseFilter(v string) (FilterSpec, error) {
parts := strings.Fields(v)
switch len(parts) {
case 0:
return FilterSpec{}, fmt.Errorf("missing definition: \"%s\"", v)
case 1:
return FilterSpec{Type: parts[0]}, nil
default:
return FilterSpec{Type: parts[0], Args: parts[1:]}, nil
}
}
// ParseFilters parses v as a string representation of a filter list.
func ParseFilters(v string) ([]FilterSpec, error) {
if v == "" {
return nil, nil
}
var filters []FilterSpec
for i, f := range strings.Split(v, ",") {
filter, err := ParseFilter(f)
if err != nil {
return nil, fmt.Errorf("invalid filter %d: %v", i, err)
}
filters = append(filters, filter)
}
return filters, nil
}