github.com/bazelbuild/bazel-gazelle@v0.36.1-0.20240520142334-61b277ba6fed/flag/flag.go (about) 1 // Copyright 2017 The Bazel Authors. All rights reserved. 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 provides some general-purpose types which satisfy the 16 // flag.Value interface. 17 package flag 18 19 import ( 20 stdflag "flag" 21 "fmt" 22 "strings" 23 ) 24 25 // MultiFlag collects repeated string flags into a slice. 26 type MultiFlag struct { 27 IsSet *bool 28 Values *[]string 29 } 30 31 var _ stdflag.Value = (*MultiFlag)(nil) 32 33 func (m *MultiFlag) Set(v string) error { 34 if m.IsSet != nil && !*m.IsSet { 35 *m.IsSet = true 36 *m.Values = nil // clear any default values 37 } 38 *m.Values = append(*m.Values, v) 39 return nil 40 } 41 42 func (m *MultiFlag) String() string { 43 if m == nil || m.Values == nil { 44 return "" 45 } 46 return strings.Join(*m.Values, ",") 47 } 48 49 // ExplicitFlag is a string flag that tracks whether it was set. 50 type ExplicitFlag struct { 51 IsSet *bool 52 Value *string 53 } 54 55 var _ stdflag.Value = (*ExplicitFlag)(nil) 56 57 func (f *ExplicitFlag) Set(value string) error { 58 *f.IsSet = true 59 *f.Value = value 60 return nil 61 } 62 63 func (f *ExplicitFlag) String() string { 64 if f == nil || f.Value == nil { 65 return "" 66 } 67 return *f.Value 68 } 69 70 var _ stdflag.Value = (*AllowedStringFlag)(nil) 71 72 type AllowedStringFlag struct { 73 Allowed []string 74 Value *string 75 } 76 77 func (f *AllowedStringFlag) Set(v string) error { 78 for _, a := range f.Allowed { 79 if v == a { 80 *f.Value = v 81 return nil 82 } 83 } 84 return fmt.Errorf("Invalid argument %q. Possible values are: %s", v, strings.Join(f.Allowed, ", ")) 85 } 86 87 func (f *AllowedStringFlag) String() string { 88 if f == nil || f.Value == nil { 89 return "" 90 } 91 return *f.Value 92 }