vitess.io/vitess@v0.16.2/go/flagutil/sets.go (about) 1 /* 2 Copyright 2021 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package flagutil 18 19 import ( 20 "strings" 21 22 "github.com/spf13/pflag" 23 "k8s.io/apimachinery/pkg/util/sets" 24 ) 25 26 var _ pflag.Value = (*StringSetFlag)(nil) 27 28 // StringSetFlag can be used to collect multiple instances of a flag into a set 29 // of values. 30 // 31 // For example, defining the following: 32 // 33 // var x flagutil.StringSetFlag 34 // flag.Var(&x, "foo", "") 35 // 36 // And then specifying "-foo x -foo y -foo x", will result in a set of {x, y}. 37 // 38 // In addition to implemnting the standard flag.Value interface, it also 39 // provides an implementation of pflag.Value, so it is usable in libraries like 40 // cobra. 41 type StringSetFlag struct { 42 set sets.Set[string] 43 } 44 45 // ToSet returns the underlying string set, or an empty set if the underlying 46 // set is nil. 47 func (set *StringSetFlag) ToSet() sets.Set[string] { 48 if set.set == nil { 49 set.set = sets.New[string]() 50 } 51 52 return set.set 53 } 54 55 // Set is part of the pflag.Value and flag.Value interfaces. 56 func (set *StringSetFlag) Set(s string) error { 57 if set.set == nil { 58 set.set = sets.New[string]() 59 return nil 60 } 61 62 set.set.Insert(s) 63 return nil 64 } 65 66 // String is part of the pflag.Value and flag.Value interfaces. 67 func (set *StringSetFlag) String() string { 68 if set.set == nil { 69 return "" 70 } 71 72 return strings.Join(sets.List(set.set), ", ") 73 } 74 75 // Type is part of the pflag.Value interface. 76 func (set *StringSetFlag) Type() string { return "StringSetFlag" }