strings.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // 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. package flags
  15. import "errors"
  16. // NewStringsFlag creates a new string flag for which any one of the given
  17. // strings is a valid value, and any other value is an error.
  18. //
  19. // valids[0] will be default value. Caller must be sure len(valids)!=0 or
  20. // it will panic.
  21. func NewStringsFlag(valids ...string) *StringsFlag {
  22. return &StringsFlag{Values: valids, val: valids[0]}
  23. }
  24. // StringsFlag implements the flag.Value interface.
  25. type StringsFlag struct {
  26. Values []string
  27. val string
  28. }
  29. // Set verifies the argument to be a valid member of the allowed values
  30. // before setting the underlying flag value.
  31. func (ss *StringsFlag) Set(s string) error {
  32. for _, v := range ss.Values {
  33. if s == v {
  34. ss.val = s
  35. return nil
  36. }
  37. }
  38. return errors.New("invalid value")
  39. }
  40. // String returns the set value (if any) of the StringsFlag
  41. func (ss *StringsFlag) String() string {
  42. return ss.val
  43. }