| 1 | package cli |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "flag" |
| 6 | "fmt" |
| 7 | "reflect" |
| 8 | "strings" |
| 9 | "time" |
| 10 | ) |
| 11 | |
| 12 | // Value represents a value as used by cli. |
| 13 | // For now it implements the golang flag.Value interface |
| 14 | type Value interface { |
| 15 | flag.Value |
| 16 | flag.Getter |
| 17 | } |
| 18 | |
| 19 | type boolFlag interface { |
| 20 | IsBoolFlag() bool |
| 21 | } |
| 22 | |
| 23 | type multiValueParsingConfig struct { |
| 24 | // SliceFlagSeparator is used to customize the separator for SliceFlag, the default is "," |
| 25 | SliceFlagSeparator string |
| 26 | // DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false |
| 27 | DisableSliceFlagSeparator bool |
| 28 | // MapFlagKeyValueSeparator is used to customize the separator for MapFlag, the default is "=" |
| 29 | MapFlagKeyValueSeparator string |
| 30 | } |
| 31 | |
| 32 | type multiValueParsingConfigSetter interface { |
| 33 | // configuration of parsing |
| 34 | setMultiValueParsingConfig(c multiValueParsingConfig) |
| 35 | } |
| 36 | |
| 37 | // ValueCreator is responsible for creating a flag.Value emulation |
| 38 | // as well as custom formatting |
| 39 | // |
| 40 | // T specifies the type |
| 41 | // C specifies the config for the type |
| 42 | type ValueCreator[T any, C any] interface { |
| 43 | Create(T, *T, C) Value |
| 44 | ToString(T) string |
| 45 | } |
| 46 | |
| 47 | // NoConfig is for flags which dont need a custom configuration |
| 48 | type NoConfig struct{} |
| 49 | |
| 50 | // FlagBase [T,C,VC] is a generic flag base which can be used |
| 51 | // as a boilerplate to implement the most common interfaces |
| 52 | // used by urfave/cli. |
| 53 | // |
| 54 | // T specifies the type |
| 55 | // C specifies the configuration required(if any for that flag type) |
| 56 | // VC specifies the value creator which creates the flag.Value emulation |
| 57 | type FlagBase[T any, C any, VC ValueCreator[T, C]] struct { |
| 58 | Name string `json:"name"` // name of the flag |
| 59 | Category string `json:"category"` // category of the flag, if any |
| 60 | DefaultText string `json:"defaultText"` // default text of the flag for usage purposes |
| 61 | HideDefault bool `json:"hideDefault"` // whether to hide the default value in output |
| 62 | Usage string `json:"usage"` // usage string for help output |
| 63 | Sources ValueSourceChain `json:"-"` // sources to load flag value from |
| 64 | Required bool `json:"required"` // whether the flag is required or not |
| 65 | Hidden bool `json:"hidden"` // whether to hide the flag in help output |
| 66 | Local bool `json:"local"` // whether the flag needs to be applied to subcommands as well |
| 67 | Value T `json:"defaultValue"` // default value for this flag if not set by from any source |
| 68 | Destination *T `json:"-"` // destination pointer for value when set |
| 69 | Aliases []string `json:"aliases"` // Aliases that are allowed for this flag |
| 70 | TakesFile bool `json:"takesFileArg"` // whether this flag takes a file argument, mainly for shell completion purposes |
| 71 | Action func(context.Context, *Command, T) error `json:"-"` // Action callback to be called when flag is set |
| 72 | Config C `json:"config"` // Additional/Custom configuration associated with this flag type |
| 73 | OnlyOnce bool `json:"onlyOnce"` // whether this flag can be duplicated on the command line |
| 74 | Validator func(T) error `json:"-"` // custom function to validate this flag value |
| 75 | ValidateDefaults bool `json:"validateDefaults"` // whether to validate defaults or not |
| 76 | |
| 77 | // unexported fields for internal use |
| 78 | count int // number of times the flag has been set |
| 79 | hasBeenSet bool // whether the flag has been set from env or file |
| 80 | applied bool // whether the flag has been applied to a flag set already |
| 81 | creator VC // value creator for this flag type |
| 82 | value Value // value representing this flag's value |
| 83 | } |
| 84 | |
| 85 | // GetValue returns the flags value as string representation and an empty |
| 86 | // string if the flag takes no value at all. |
| 87 | func (f *FlagBase[T, C, V]) GetValue() string { |
| 88 | var v V |
| 89 | return v.ToString(f.Value) |
| 90 | } |
| 91 | |
| 92 | // TypeName returns the type of the flag. |
| 93 | func (f *FlagBase[T, C, V]) TypeName() string { |
| 94 | ty := reflect.TypeOf(f.Value) |
| 95 | if ty == nil { |
| 96 | return "" |
| 97 | } |
| 98 | // convert the typename to generic type |
| 99 | convertToGenericType := func(name string) string { |
| 100 | prefixMap := map[string]string{ |
| 101 | "float": "float", |
| 102 | "int": "int", |
| 103 | "uint": "uint", |
| 104 | } |
| 105 | for prefix, genericType := range prefixMap { |
| 106 | if strings.HasPrefix(name, prefix) { |
| 107 | return genericType |
| 108 | } |
| 109 | } |
| 110 | return strings.ToLower(name) |
| 111 | } |
| 112 | |
| 113 | switch ty.Kind() { |
| 114 | // if it is a Slice, then return the slice's inner type. Will nested slices be used in the future? |
| 115 | case reflect.Slice: |
| 116 | elemType := ty.Elem() |
| 117 | return convertToGenericType(elemType.Name()) |
| 118 | // if it is a Map, then return the map's key and value types. |
| 119 | case reflect.Map: |
| 120 | keyType := ty.Key() |
| 121 | valueType := ty.Elem() |
| 122 | return fmt.Sprintf("%s=%s", convertToGenericType(keyType.Name()), convertToGenericType(valueType.Name())) |
| 123 | default: |
| 124 | return convertToGenericType(ty.Name()) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | // PostParse populates the flag given the flag set and environment |
| 129 | func (f *FlagBase[T, C, V]) PostParse() error { |
| 130 | tracef("postparse (flag=%[1]q)", f.Name) |
| 131 | |
| 132 | if !f.hasBeenSet { |
| 133 | if val, source, found := f.Sources.LookupWithSource(); found { |
| 134 | if val != "" || reflect.TypeOf(f.Value).Kind() == reflect.String { |
| 135 | if err := f.Set(f.Name, val); err != nil { |
| 136 | return fmt.Errorf( |
| 137 | "could not parse %[1]q as %[2]T value from %[3]s for flag %[4]s: %[5]s", |
| 138 | val, f.Value, source, f.Name, err, |
| 139 | ) |
| 140 | } |
| 141 | } else if val == "" && reflect.TypeOf(f.Value).Kind() == reflect.Bool { |
| 142 | _ = f.Set(f.Name, "false") |
| 143 | } |
| 144 | |
| 145 | f.hasBeenSet = true |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | return nil |
| 150 | } |
| 151 | |
| 152 | // pass configuration of parsing to value |
| 153 | func (f *FlagBase[T, C, V]) setMultiValueParsingConfig(c multiValueParsingConfig) { |
| 154 | tracef("setMultiValueParsingConfig %T, %+v", f.value, f.value) |
| 155 | if cf, ok := f.value.(multiValueParsingConfigSetter); ok { |
| 156 | cf.setMultiValueParsingConfig(c) |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | func (f *FlagBase[T, C, V]) PreParse() error { |
| 161 | newVal := f.Value |
| 162 | |
| 163 | if f.Destination == nil { |
| 164 | f.value = f.creator.Create(newVal, new(T), f.Config) |
| 165 | } else { |
| 166 | f.value = f.creator.Create(newVal, f.Destination, f.Config) |
| 167 | } |
| 168 | |
| 169 | // Validate the given default or values set from external sources as well |
| 170 | if f.Validator != nil && f.ValidateDefaults { |
| 171 | if err := f.Validator(f.value.Get().(T)); err != nil { |
| 172 | return err |
| 173 | } |
| 174 | } |
| 175 | f.applied = true |
| 176 | return nil |
| 177 | } |
| 178 | |
| 179 | // Set applies given value from string |
| 180 | func (f *FlagBase[T, C, V]) Set(_ string, val string) error { |
| 181 | tracef("apply (flag=%[1]q)", f.Name) |
| 182 | |
| 183 | // TODO move this phase into a separate flag initialization function |
| 184 | // if flag has been applied previously then it would have already been set |
| 185 | // from env or file. So no need to apply the env set again. However |
| 186 | // lots of units tests prior to persistent flags assumed that the |
| 187 | // flag can be applied to different flag sets multiple times while still |
| 188 | // keeping the env set. |
| 189 | if !f.applied { |
| 190 | if err := f.PreParse(); err != nil { |
| 191 | return err |
| 192 | } |
| 193 | f.applied = true |
| 194 | } |
| 195 | |
| 196 | if f.count == 1 && f.OnlyOnce { |
| 197 | return fmt.Errorf("can't duplicate this flag") |
| 198 | } |
| 199 | |
| 200 | f.count++ |
| 201 | if err := f.value.Set(val); err != nil { |
| 202 | return err |
| 203 | } |
| 204 | f.hasBeenSet = true |
| 205 | if f.Validator != nil { |
| 206 | if err := f.Validator(f.value.Get().(T)); err != nil { |
| 207 | return err |
| 208 | } |
| 209 | } |
| 210 | return nil |
| 211 | } |
| 212 | |
| 213 | func (f *FlagBase[T, C, V]) Get() any { |
| 214 | if f.value != nil { |
| 215 | return f.value.Get() |
| 216 | } |
| 217 | return f.Value |
| 218 | } |
| 219 | |
| 220 | // IsDefaultVisible returns true if the flag is not hidden, otherwise false |
| 221 | func (f *FlagBase[T, C, V]) IsDefaultVisible() bool { |
| 222 | return !f.HideDefault |
| 223 | } |
| 224 | |
| 225 | // String returns a readable representation of this value (for usage defaults) |
| 226 | func (f *FlagBase[T, C, V]) String() string { |
| 227 | return FlagStringer(f) |
| 228 | } |
| 229 | |
| 230 | // IsSet returns whether or not the flag has been set through env or file |
| 231 | func (f *FlagBase[T, C, V]) IsSet() bool { |
| 232 | return f.hasBeenSet |
| 233 | } |
| 234 | |
| 235 | // Names returns the names of the flag |
| 236 | func (f *FlagBase[T, C, V]) Names() []string { |
| 237 | return FlagNames(f.Name, f.Aliases) |
| 238 | } |
| 239 | |
| 240 | // IsRequired returns whether or not the flag is required |
| 241 | func (f *FlagBase[T, C, V]) IsRequired() bool { |
| 242 | return f.Required |
| 243 | } |
| 244 | |
| 245 | // IsVisible returns true if the flag is not hidden, otherwise false |
| 246 | func (f *FlagBase[T, C, V]) IsVisible() bool { |
| 247 | return !f.Hidden |
| 248 | } |
| 249 | |
| 250 | // GetCategory returns the category of the flag |
| 251 | func (f *FlagBase[T, C, V]) GetCategory() string { |
| 252 | return f.Category |
| 253 | } |
| 254 | |
| 255 | func (f *FlagBase[T, C, V]) SetCategory(c string) { |
| 256 | f.Category = c |
| 257 | } |
| 258 | |
| 259 | // GetUsage returns the usage string for the flag |
| 260 | func (f *FlagBase[T, C, V]) GetUsage() string { |
| 261 | return f.Usage |
| 262 | } |
| 263 | |
| 264 | // GetEnvVars returns the env vars for this flag |
| 265 | func (f *FlagBase[T, C, V]) GetEnvVars() []string { |
| 266 | return f.Sources.EnvKeys() |
| 267 | } |
| 268 | |
| 269 | // TakesValue returns true if the flag takes a value, otherwise false |
| 270 | func (f *FlagBase[T, C, V]) TakesValue() bool { |
| 271 | var t T |
| 272 | return reflect.TypeOf(t) == nil || reflect.TypeOf(t).Kind() != reflect.Bool |
| 273 | } |
| 274 | |
| 275 | // GetDefaultText returns the default text for this flag |
| 276 | func (f *FlagBase[T, C, V]) GetDefaultText() string { |
| 277 | return f.DefaultText |
| 278 | } |
| 279 | |
| 280 | // RunAction executes flag action if set |
| 281 | func (f *FlagBase[T, C, V]) RunAction(ctx context.Context, cmd *Command) error { |
| 282 | if f.Action != nil { |
| 283 | return f.Action(ctx, cmd, f.value.Get().(T)) |
| 284 | } |
| 285 | |
| 286 | return nil |
| 287 | } |
| 288 | |
| 289 | // SchemaType returns the JSON Schema type for the flag's value type. |
| 290 | func (f *FlagBase[T, C, V]) SchemaType() string { |
| 291 | var zero T |
| 292 | switch any(zero).(type) { |
| 293 | case bool: |
| 294 | return "boolean" |
| 295 | case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: |
| 296 | return "integer" |
| 297 | case float32, float64: |
| 298 | return "number" |
| 299 | case string: |
| 300 | return "string" |
| 301 | case time.Duration: |
| 302 | return "duration" |
| 303 | case time.Time: |
| 304 | return "date-time" |
| 305 | case []string, []int, []int8, []int16, []int32, []int64, |
| 306 | []uint, []uint8, []uint16, []uint32, []uint64, |
| 307 | []float32, []float64: |
| 308 | return "array" |
| 309 | case map[string]string: |
| 310 | return "object" |
| 311 | default: |
| 312 | return "" |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | // SchemaItemsType returns the JSON Schema element type for slice flags. |
| 317 | func (f *FlagBase[T, C, V]) SchemaItemsType() string { |
| 318 | var zero T |
| 319 | t := reflect.TypeOf(zero) |
| 320 | if t.Kind() == reflect.Slice { |
| 321 | switch t.Elem().Kind() { |
| 322 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, |
| 323 | reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: |
| 324 | return "integer" |
| 325 | case reflect.Float32, reflect.Float64: |
| 326 | return "number" |
| 327 | case reflect.String: |
| 328 | return "string" |
| 329 | } |
| 330 | } |
| 331 | return "" |
| 332 | } |
| 333 | |
| 334 | // IsMultiValueFlag returns true if the value type T can take multiple |
| 335 | // values from cmd line. This is true for slice and map type flags |
| 336 | func (f *FlagBase[T, C, VC]) IsMultiValueFlag() bool { |
| 337 | // TBD how to specify |
| 338 | if reflect.TypeOf(f.Value) == nil { |
| 339 | return false |
| 340 | } |
| 341 | kind := reflect.TypeOf(f.Value).Kind() |
| 342 | return kind == reflect.Slice || kind == reflect.Map |
| 343 | } |
| 344 | |
| 345 | // IsLocal returns false if flag needs to be persistent across subcommands |
| 346 | func (f *FlagBase[T, C, VC]) IsLocal() bool { |
| 347 | return f.Local |
| 348 | } |
| 349 | |
| 350 | // IsBoolFlag returns whether the flag doesn't need to accept args |
| 351 | func (f *FlagBase[T, C, VC]) IsBoolFlag() bool { |
| 352 | bf, ok := f.value.(boolFlag) |
| 353 | return ok && bf.IsBoolFlag() |
| 354 | } |
| 355 | |
| 356 | // Count returns the number of times this flag has been invoked |
| 357 | func (f *FlagBase[T, C, VC]) Count() int { |
| 358 | return f.count |
| 359 | } |