github.com/blixtra/rkt@v0.8.1-0.20160204105720-ab0d1add1a43/rkt/flag/optionlist.go (about) 1 // Copyright 2015 The rkt 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 "errors" 19 "fmt" 20 "strings" 21 22 "github.com/hashicorp/errwrap" 23 "github.com/spf13/pflag" 24 ) 25 26 // OptionList is a flag value type supporting a csv list of options 27 type OptionList struct { 28 // Options field holds all specified and valid options. Should 29 // not be modified. 30 Options []string 31 allOptions []string 32 permissible map[string]struct{} 33 typeName string 34 } 35 36 var _ pflag.Value = (*OptionList)(nil) 37 38 func NewOptionList(permissibleOptions []string, defaultOptions string) (*OptionList, error) { 39 permissible := make(map[string]struct{}) 40 ol := &OptionList{ 41 allOptions: permissibleOptions, 42 permissible: permissible, 43 typeName: "optionList", 44 } 45 46 for _, o := range permissibleOptions { 47 ol.permissible[o] = struct{}{} 48 } 49 50 if err := ol.Set(defaultOptions); err != nil { 51 return nil, errwrap.Wrap(errors.New("problem setting defaults"), err) 52 } 53 54 return ol, nil 55 } 56 57 func (ol *OptionList) Set(s string) error { 58 ol.Options = nil 59 if s == "" { 60 return nil 61 } 62 options := strings.Split(strings.ToLower(s), ",") 63 seen := map[string]struct{}{} 64 for _, o := range options { 65 if _, ok := ol.permissible[o]; !ok { 66 return fmt.Errorf("unknown option %q", o) 67 } 68 if _, ok := seen[o]; ok { 69 return fmt.Errorf("duplicated option %q", o) 70 } 71 ol.Options = append(ol.Options, o) 72 seen[o] = struct{}{} 73 } 74 75 return nil 76 } 77 78 func (ol *OptionList) String() string { 79 return strings.Join(ol.Options, ",") 80 } 81 82 func (ol *OptionList) Type() string { 83 return ol.typeName 84 } 85 86 func (ol *OptionList) PermissibleString() string { 87 return fmt.Sprintf(`"%s"`, strings.Join(ol.allOptions, `", "`)) 88 }