strings.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package flags
  14. import "errors"
  15. // NewStringsFlag creates a new string flag for which any one of the given
  16. // strings is a valid value, and any other value is an error.
  17. func NewStringsFlag(valids ...string) *StringsFlag {
  18. return &StringsFlag{Values: valids}
  19. }
  20. // StringsFlag implements the flag.Value interface.
  21. type StringsFlag struct {
  22. Values []string
  23. val string
  24. }
  25. // Set verifies the argument to be a valid member of the allowed values
  26. // before setting the underlying flag value.
  27. func (ss *StringsFlag) Set(s string) error {
  28. for _, v := range ss.Values {
  29. if s == v {
  30. ss.val = s
  31. return nil
  32. }
  33. }
  34. return errors.New("invalid value")
  35. }
  36. // String returns the set value (if any) of the StringsFlag
  37. func (ss *StringsFlag) String() string {
  38. return ss.val
  39. }