strings.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 (
  16. "errors"
  17. "flag"
  18. "sort"
  19. "strings"
  20. )
  21. // NewStringsFlag creates a new string flag for which any one of the given
  22. // strings is a valid value, and any other value is an error.
  23. func NewStringsFlag(valids ...string) *StringsFlag {
  24. return &StringsFlag{Values: valids}
  25. }
  26. // StringsFlag implements the flag.Value interface.
  27. type StringsFlag struct {
  28. Values []string
  29. val string
  30. }
  31. // Set verifies the argument to be a valid member of the allowed values
  32. // before setting the underlying flag value.
  33. func (ss *StringsFlag) Set(s string) error {
  34. for _, v := range ss.Values {
  35. if s == v {
  36. ss.val = s
  37. return nil
  38. }
  39. }
  40. return errors.New("invalid value")
  41. }
  42. // String returns the set value (if any) of the StringsFlag
  43. func (ss *StringsFlag) String() string {
  44. return ss.val
  45. }
  46. // StringsValueV2 wraps "sort.StringSlice".
  47. type StringsValueV2 sort.StringSlice
  48. // Set parses a command line set of strings, separated by comma.
  49. // Implements "flag.Value" interface.
  50. func (ss *StringsValueV2) Set(s string) error {
  51. *ss = strings.Split(s, ",")
  52. return nil
  53. }
  54. // String implements "flag.Value" interface.
  55. func (ss *StringsValueV2) String() string { return strings.Join(*ss, ",") }
  56. // NewStringsValueV2 implements string slice as "flag.Value" interface.
  57. // Given value is to be separated by comma.
  58. func NewStringsValueV2(s string) (ss *StringsValueV2) {
  59. if s == "" {
  60. return &StringsValueV2{}
  61. }
  62. ss = new(StringsValueV2)
  63. if err := ss.Set(s); err != nil {
  64. plog.Panicf("new StringsValueV2 should never fail: %v", err)
  65. }
  66. return ss
  67. }
  68. // StringsFromFlagV2 returns a string slice from the flag.
  69. func StringsFromFlagV2(fs *flag.FlagSet, flagName string) []string {
  70. return []string(*fs.Lookup(flagName).Value.(*StringsValueV2))
  71. }