|
| 1 | +package enumflag |
| 2 | + |
| 3 | +// Adapted from https://github.com/creachadair/goflags/blob/main/enumflag/flag.go |
| 4 | +// under BSD 3-Clause license |
| 5 | + |
| 6 | +import ( |
| 7 | + "fmt" |
| 8 | + "strings" |
| 9 | +) |
| 10 | + |
| 11 | +// A Value represents an enumeration of string values. A pointer to a Value |
| 12 | +// satisfies the flag.Value interface. Use the Key method to recover the |
| 13 | +// currently-selected value of the enumeration. |
| 14 | +type Value struct { |
| 15 | + keys []string |
| 16 | + index int // The selected index in the enumeration |
| 17 | +} |
| 18 | + |
| 19 | +// Help concatenates a human-readable string summarizing the legal values of v |
| 20 | +// to h, for use in generating a documentation string. |
| 21 | +func (v *Value) Help(h string) string { |
| 22 | + return fmt.Sprintf("%s (%s)", h, strings.Join(v.keys, "|")) |
| 23 | +} |
| 24 | + |
| 25 | +// New returns a *Value for the specified enumerators, where defaultKey is the |
| 26 | +// default value and otherKeys are additional options. The index of a selected |
| 27 | +// key reflects its position in the order given to this function, so that if: |
| 28 | +// |
| 29 | +// v := enumflag.New("a", "b", "c", "d") |
| 30 | +// |
| 31 | +// then the index of "a" is 0, "b" is 1, "c" is 2, "d" is 3. The default key is |
| 32 | +// always stored at index 0. |
| 33 | +func New(defaultKey string, otherKeys ...string) *Value { |
| 34 | + return &Value{keys: append([]string{defaultKey}, otherKeys...)} |
| 35 | +} |
| 36 | + |
| 37 | +// Key returns the currently-selected key in the enumeration. The original |
| 38 | +// spelling of the selected value is returned, as given to the constructor, not |
| 39 | +// the value as parsed. |
| 40 | +func (v *Value) Key() string { |
| 41 | + if len(v.keys) == 0 { |
| 42 | + return "" // BUG: https://github.com/golang/go/issues/16694 |
| 43 | + } |
| 44 | + return v.keys[v.index] |
| 45 | +} |
| 46 | + |
| 47 | +// Get satisfies the flag.Getter interface. |
| 48 | +// The concrete value is the the string of the current key. |
| 49 | +func (v *Value) Get() any { return v.Key() } |
| 50 | + |
| 51 | +// Index returns the currently-selected index in the enumeration. |
| 52 | +// The order of keys reflects the original order in which they were passed to |
| 53 | +// the constructor, so index 0 is the default value. |
| 54 | +func (v *Value) Index() int { return v.index } |
| 55 | + |
| 56 | +// String satisfies part of the flag.Value interface. |
| 57 | +func (v *Value) String() string { return fmt.Sprintf("%q", v.Key()) } |
| 58 | + |
| 59 | +// Set satisfies part of the flag.Value interface. |
| 60 | +func (v *Value) Set(s string) error { |
| 61 | + for i, key := range v.keys { |
| 62 | + if strings.EqualFold(s, key) { |
| 63 | + v.index = i |
| 64 | + return nil |
| 65 | + } |
| 66 | + } |
| 67 | + return fmt.Errorf("expected one of (%s)", strings.Join(v.keys, "|")) |
| 68 | +} |
0 commit comments