forked from open-policy-agent/opa
/
enumflag.go
54 lines (47 loc) · 1.16 KB
/
enumflag.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
// Copyright 2017 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package util
import (
"fmt"
"strings"
)
// EnumFlag implements the pflag.Value interface to provide enumerated command
// line parameter values.
type EnumFlag struct {
defaultValue string
vs []string
i int
}
// NewEnumFlag returns a new EnumFlag that has a defaultValue and vs enumerated
// values.
func NewEnumFlag(defaultValue string, vs []string) *EnumFlag {
f := &EnumFlag{
i: -1,
vs: vs,
defaultValue: defaultValue,
}
return f
}
// Type returns the valid enumeration values.
func (f *EnumFlag) Type() string {
return "{" + strings.Join(f.vs, ",") + "}"
}
// String returns the EnumValue's value as string.
func (f *EnumFlag) String() string {
if f.i == -1 {
return f.defaultValue
}
return f.vs[f.i]
}
// Set sets the enum value. If s is not a valid enum value, an error is
// returned.
func (f *EnumFlag) Set(s string) error {
for i := range f.vs {
if f.vs[i] == s {
f.i = i
return nil
}
}
return fmt.Errorf("must be one of %v", f.Type())
}