blob: 89bdf950661adf3af850d383db0db8357f36448a [file] [log] [blame]
khenaidooffe076b2019-01-15 16:08:08 -05001// Copyright 2015 The etcd Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package flags
16
17import (
18 "errors"
19 "flag"
20 "sort"
21 "strings"
22)
23
24// NewStringsFlag creates a new string flag for which any one of the given
25// strings is a valid value, and any other value is an error.
26//
27// valids[0] will be default value. Caller must be sure len(valids)!=0 or
28// it will panic.
29func NewStringsFlag(valids ...string) *StringsFlag {
30 return &StringsFlag{Values: valids, val: valids[0]}
31}
32
33// StringsFlag implements the flag.Value interface.
34type StringsFlag struct {
35 Values []string
36 val string
37}
38
39// Set verifies the argument to be a valid member of the allowed values
40// before setting the underlying flag value.
41func (ss *StringsFlag) Set(s string) error {
42 for _, v := range ss.Values {
43 if s == v {
44 ss.val = s
45 return nil
46 }
47 }
48 return errors.New("invalid value")
49}
50
51// String returns the set value (if any) of the StringsFlag
52func (ss *StringsFlag) String() string {
53 return ss.val
54}
55
56// StringsValueV2 wraps "sort.StringSlice".
57type StringsValueV2 sort.StringSlice
58
59// Set parses a command line set of strings, separated by comma.
60// Implements "flag.Value" interface.
61func (ss *StringsValueV2) Set(s string) error {
62 *ss = strings.Split(s, ",")
63 return nil
64}
65
66// String implements "flag.Value" interface.
67func (ss *StringsValueV2) String() string { return strings.Join(*ss, ",") }
68
69// NewStringsValueV2 implements string slice as "flag.Value" interface.
70// Given value is to be separated by comma.
71func NewStringsValueV2(s string) (ss *StringsValueV2) {
72 if s == "" {
73 return &StringsValueV2{}
74 }
75 ss = new(StringsValueV2)
76 if err := ss.Set(s); err != nil {
77 plog.Panicf("new StringsValueV2 should never fail: %v", err)
78 }
79 return ss
80}
81
82// StringsFromFlagV2 returns a string slice from the flag.
83func StringsFromFlagV2(fs *flag.FlagSet, flagName string) []string {
84 return []string(*fs.Lookup(flagName).Value.(*StringsValueV2))
85}