go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/flag/stringsetflag/stringsetflag.go (about) 1 // Copyright 2016 The LUCI 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 15 // Package stringsetflag provides a flag.Value implementation which resolves 16 // multiple args into a stringset. 17 package stringsetflag 18 19 import ( 20 "flag" 21 "fmt" 22 "sort" 23 "strings" 24 25 "go.chromium.org/luci/common/data/stringset" 26 ) 27 28 // Flag is a flag.Value implementation which represents an unordered set of 29 // strings. 30 // 31 // For example, this allows you to construct a flag that would behave like: 32 // 33 // -myflag Foo 34 // -myflag Bar 35 // -myflag Bar 36 // 37 // And then myflag.Data.Has("Bar") would be true. 38 type Flag struct{ Data stringset.Set } 39 40 var _ flag.Value = (*Flag)(nil) 41 42 func (f Flag) String() string { 43 if f.Data == nil { 44 return "" 45 } 46 slc := f.Data.ToSlice() 47 sort.Strings(slc) 48 return strings.Join(slc, ",") 49 } 50 51 // Set implements flag.Value's Set function. 52 func (f *Flag) Set(val string) error { 53 if val == "" { 54 return fmt.Errorf("must have an argument value") 55 } 56 57 if f.Data == nil { 58 f.Data = stringset.NewFromSlice(val) 59 } else { 60 f.Data.Add(val) 61 } 62 return nil 63 }