unique_strings.go 2.2 KB

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