strings.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright 2015 CoreOS, Inc.
  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. func NewStringsFlag(valids ...string) *StringsFlag {
  19. return &StringsFlag{Values: valids}
  20. }
  21. // StringsFlag implements the flag.Value interface.
  22. type StringsFlag struct {
  23. Values []string
  24. val string
  25. }
  26. // Set verifies the argument to be a valid member of the allowed values
  27. // before setting the underlying flag value.
  28. func (ss *StringsFlag) Set(s string) error {
  29. for _, v := range ss.Values {
  30. if s == v {
  31. ss.val = s
  32. return nil
  33. }
  34. }
  35. return errors.New("invalid value")
  36. }
  37. // String returns the set value (if any) of the StringsFlag
  38. func (ss *StringsFlag) String() string {
  39. return ss.val
  40. }