go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/flag/choice.go (about) 1 // Copyright 2019 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 flag 16 17 import ( 18 "strings" 19 20 "go.chromium.org/luci/common/errors" 21 ) 22 23 // Choice is an implementation of flag.Value for parsing a 24 // multiple-choice string. 25 type Choice struct { 26 choices []string 27 output *string 28 } 29 30 // NewChoice creates a Choice value 31 func NewChoice(output *string, choices ...string) Choice { 32 return Choice{choices: choices, output: output} 33 } 34 35 // String implements the flag.Value interface. 36 func (f Choice) String() string { 37 if f.output == nil { 38 return "" 39 } 40 return *f.output 41 } 42 43 // Set implements the flag.Value interface. 44 func (f Choice) Set(s string) error { 45 if f.output == nil { 46 return errors.Reason("Choice pointer is nil").Err() 47 } 48 for _, choice := range f.choices { 49 if s == choice { 50 *f.output = s 51 return nil 52 } 53 } 54 valid := strings.Join(f.choices, ", ") 55 return errors.Reason("%s is not a valid choice; please select one of: %s", s, valid).Err() 56 }