unique_strings.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2018 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. "flag"
  17. "sort"
  18. "strings"
  19. )
  20. // UniqueStringsValue wraps a list of unique strings.
  21. // The values are set in order.
  22. type UniqueStringsValue struct {
  23. Values map[string]struct{}
  24. }
  25. // Set parses a command line set of strings, separated by comma.
  26. // Implements "flag.Value" interface.
  27. // The values are set in order.
  28. func (us *UniqueStringsValue) Set(s string) error {
  29. for _, v := range strings.Split(s, ",") {
  30. us.Values[v] = struct{}{}
  31. }
  32. return nil
  33. }
  34. // String implements "flag.Value" interface.
  35. func (us *UniqueStringsValue) String() string {
  36. return strings.Join(us.stringSlice(), ",")
  37. }
  38. func (us *UniqueStringsValue) stringSlice() []string {
  39. ss := make([]string, 0, len(us.Values))
  40. for v := range us.Values {
  41. ss = append(ss, v)
  42. }
  43. sort.Strings(ss)
  44. return ss
  45. }
  46. // NewUniqueStringsValue implements string slice as "flag.Value" interface.
  47. // Given value is to be separated by comma.
  48. // The values are set in order.
  49. func NewUniqueStringsValue(s string) (us *UniqueStringsValue) {
  50. us = &UniqueStringsValue{Values: make(map[string]struct{})}
  51. if s == "" {
  52. return us
  53. }
  54. if err := us.Set(s); err != nil {
  55. plog.Panicf("new UniqueStringsValue should never fail: %v", err)
  56. }
  57. return us
  58. }
  59. // UniqueStringsFromFlag returns a string slice from the flag.
  60. func UniqueStringsFromFlag(fs *flag.FlagSet, flagName string) []string {
  61. return []string((*fs.Lookup(flagName).Value.(*UniqueStringsValue)).stringSlice())
  62. }
  63. // UniqueStringsMapFromFlag returns a map of strings from the flag.
  64. func UniqueStringsMapFromFlag(fs *flag.FlagSet, flagName string) map[string]struct{} {
  65. return (*fs.Lookup(flagName).Value.(*UniqueStringsValue)).Values
  66. }