78 lines
1.6 KiB
Go
78 lines
1.6 KiB
Go
package cli
|
|
|
|
import (
|
|
"fmt"
|
|
"strconv"
|
|
)
|
|
|
|
const (
|
|
multiTypeName = "num"
|
|
)
|
|
|
|
type cliOptionMulti struct {
|
|
cliOptionBase
|
|
defaultValue int
|
|
targetVar *int
|
|
}
|
|
|
|
func (opt *cliOptionMulti) init() {
|
|
if opt.targetVar != nil {
|
|
*opt.targetVar = opt.defaultValue
|
|
}
|
|
}
|
|
|
|
func (opt *cliOptionMulti) getTargetVar() (any, string) {
|
|
var value int
|
|
if opt.targetVar != nil {
|
|
value = *opt.targetVar
|
|
}
|
|
return value, multiTypeName
|
|
}
|
|
|
|
func (opt *cliOptionMulti) requiresValue() bool {
|
|
return false
|
|
}
|
|
|
|
func (opt *cliOptionMulti) getDefaultValue() string {
|
|
return strconv.Itoa(opt.defaultValue)
|
|
}
|
|
|
|
func (opt *cliOptionMulti) 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 *cliOptionMulti) parse(parser cliParser, argIndex int, valuePtr *string) (skipNextArg bool, value string, err error) {
|
|
if opt.targetVar != nil {
|
|
*opt.targetVar++
|
|
}
|
|
value = "true"
|
|
return
|
|
}
|
|
func (opt *cliOptionMulti) finalCheck(cliValue string) (err error) {
|
|
currentValue, _ := opt.getTargetVar()
|
|
return opt.getBase().checkValue(cliValue, currentValue)
|
|
}
|
|
|
|
func (cli *CliParser) AddMultiOpt(name, short string, targetVar *int, defaultValue int, description string, aliases ...string) OptReference {
|
|
if cli.optionExists(name, short, aliases) {
|
|
panic(errOptionAlreadyDefined(name))
|
|
}
|
|
opt := &cliOptionMulti{
|
|
cliOptionBase: cliOptionBase{
|
|
name: name,
|
|
shortAlias: short,
|
|
aliases: aliases,
|
|
description: description,
|
|
},
|
|
targetVar: targetVar,
|
|
defaultValue: defaultValue,
|
|
}
|
|
cli.options = append(cli.options, opt)
|
|
return opt
|
|
}
|