cli/opt-bool.go
2025-12-11 07:57:48 +01:00

86 lines
1.7 KiB
Go

package cli
import (
"fmt"
)
const (
boolTypeName = "bool"
)
type cliOptionBool struct {
cliOptionBase
targetVar *bool
}
func (opt *cliOptionBool) init() {
if opt.targetVar != nil {
*opt.targetVar = false
}
}
func (opt *cliOptionBool) getTargetVar() (any, string) {
var value bool
if opt.targetVar != nil {
value = *opt.targetVar
}
return value, boolTypeName
}
func (opt *cliOptionBool) isSet() bool {
if opt.targetVar != nil {
return *(opt.targetVar)
}
return false
}
func (opt *cliOptionBool) requiresValue() bool {
return false
}
func (opt *cliOptionBool) getTemplate() (templ string) {
if opt.shortAlias != "" {
templ = fmt.Sprintf(`-%s, --%s`, opt.shortAlias, opt.name)
} else {
templ = fmt.Sprintf(`--%s`, opt.name)
}
return
}
func (opt *cliOptionBool) parse(parser cliParser, argIndex int, valuePtr *string) (skipNextArg bool, err error) {
var boxedValue any
value := "true"
if boxedValue, err = opt.getSpecialValue(parser, value, opt.targetVar); err == nil {
if opt.targetVar != nil {
if boxedValue != nil {
if val, ok := boxedValue.(bool); ok {
*(opt.targetVar) = val
} else {
err = errInvalidOptionValue(opt.name, boxedValue, "bool")
}
} else {
*(opt.targetVar) = true
}
}
}
return
}
func (cli *CliParser) AddBoolOpt(name, short string, targetVar *bool, description string, aliases ...string) OptReference {
if cli.optionExists(name, short, aliases) {
panic(errOptionAlreadyDefined(name))
}
opt := &cliOptionBool{
cliOptionBase: cliOptionBase{
name: name,
shortAlias: short,
aliases: aliases,
description: description,
},
targetVar: targetVar,
}
cli.options = append(cli.options, opt)
return opt
}