| OLD | NEW |
| 1 // Copyright 2016 The LUCI Authors. All rights reserved. | 1 // Copyright 2016 The LUCI Authors. All rights reserved. |
| 2 // Use of this source code is governed under the Apache License, Version 2.0 | 2 // Use of this source code is governed under the Apache License, Version 2.0 |
| 3 // that can be found in the LICENSE file. | 3 // that can be found in the LICENSE file. |
| 4 | 4 |
| 5 // Package stringsetflag provides a flag.Value implementation which resolves | 5 // Package stringlistflag provides a flag.Value implementation which resolves |
| 6 // multiple args into a stringset. | 6 // multiple args into a []string. |
| 7 package stringsetflag | 7 package stringlistflag |
| 8 | 8 |
| 9 import ( | 9 import ( |
| 10 "flag" | 10 "flag" |
| 11 "fmt" | 11 "fmt" |
| 12 "sort" | |
| 13 "strings" | 12 "strings" |
| 14 | |
| 15 "github.com/luci/luci-go/common/stringset" | |
| 16 ) | 13 ) |
| 17 | 14 |
| 18 // Flag is a flag.Value implementation which represents an unordered set of | 15 // Flag is a flag.Value implementation which represents an ordered set of |
| 19 // strings. | 16 // strings. |
| 20 // | 17 // |
| 21 // For example, this allows you to construct a flag that would behave like: | 18 // For example, this allows you to construct a flag that would behave like: |
| 22 // -myflag Foo | 19 // -myflag Foo |
| 23 // -myflag Bar | 20 // -myflag Bar |
| 24 // -myflag Bar | 21 // -myflag Bar |
| 25 // | 22 // |
| 26 // And then myflag.Data.Has("Bar") would be true. | 23 // And then myflag would be []string{"Foo", "Bar", "Bar"} |
| 27 type Flag struct{ Data stringset.Set } | 24 type Flag []string |
| 28 | 25 |
| 29 var _ flag.Value = (*Flag)(nil) | 26 var _ flag.Value = (*Flag)(nil) |
| 30 | 27 |
| 31 func (f Flag) String() string { | 28 func (f Flag) String() string { |
| 32 » if f.Data == nil { | 29 » return strings.Join(f, ", ") |
| 33 » » return "" | |
| 34 » } | |
| 35 » slc := f.Data.ToSlice() | |
| 36 » sort.Strings(slc) | |
| 37 » return strings.Join(slc, ",") | |
| 38 } | 30 } |
| 39 | 31 |
| 40 // Set implements flag.Value's Set function. | 32 // Set implements flag.Value's Set function. |
| 41 func (f *Flag) Set(val string) error { | 33 func (f *Flag) Set(val string) error { |
| 42 if val == "" { | 34 if val == "" { |
| 43 return fmt.Errorf("must have an argument value") | 35 return fmt.Errorf("must have an argument value") |
| 44 } | 36 } |
| 45 | 37 |
| 46 » if f.Data == nil { | 38 » *f = append(*f, val) |
| 47 » » f.Data = stringset.NewFromSlice(val) | |
| 48 » } else { | |
| 49 » » f.Data.Add(val) | |
| 50 » } | |
| 51 return nil | 39 return nil |
| 52 } | 40 } |
| OLD | NEW |