Compare commits

..

No commits in common. "main" and "v1.3.0" have entirely different histories.
main ... v1.3.0

11 changed files with 124 additions and 171 deletions

72
cli.go
View File

@ -14,7 +14,6 @@ type cliParser interface {
getCliArgs(startIndex, endIndex int) (args []string) getCliArgs(startIndex, endIndex int) (args []string)
PrintVersion(specs []string) PrintVersion(specs []string)
PrintUsage() PrintUsage()
FlagIsSet(flag int16) bool
} }
type cliOptionParser interface { type cliOptionParser interface {
@ -26,7 +25,7 @@ type cliOptionParser interface {
isSet() bool isSet() bool
isHidden() bool isHidden() bool
requiresValue() bool requiresValue() bool
finalCheck() (err error) finalCheck(cliValue string) (err error)
} }
type OptManager interface { type OptManager interface {
@ -34,7 +33,7 @@ type OptManager interface {
} }
type SpecialValueFunc func(manager OptManager, cliValue string, currentValue any) (value any, err error) type SpecialValueFunc func(manager OptManager, cliValue string, currentValue any) (value any, err error)
type FinalCheckFunc func(currentValue any) (err error) type FinalCheckFunc func(cliValue string, currentValue any) (err error)
type OptReference interface { type OptReference interface {
AddSpecialValue(cliValue string, specialFunc SpecialValueFunc) AddSpecialValue(cliValue string, specialFunc SpecialValueFunc)
@ -42,31 +41,20 @@ type OptReference interface {
SetHidden(hidden bool) SetHidden(hidden bool)
} }
const (
ResetOnEqualSign = int16(1 << iota) // for some option types, like arrays, the equal signs reset to empty the accumulator of values
)
type CliParser struct { type CliParser struct {
description string description string
version string version string
options []cliOptionParser options []cliOptionParser
argSpecs []argSpec argSpecs []argSpec
cliArgs []string cliArgs []string
flags int16
} }
func (cli *CliParser) Init(argv []string, version string, description string, flags ...int16) { func (cli *CliParser) Init(argv []string, version string, description string) {
cli.version = version cli.version = version
cli.description = description cli.description = description
cli.cliArgs = argv cli.cliArgs = argv
for _, flag := range flags {
cli.flags |= flag
}
} }
func (cli *CliParser) FlagIsSet(flag int16) bool {
return (cli.flags & flag) == flag
}
func (cli *CliParser) GetOption(name string) (ref OptReference) { func (cli *CliParser) GetOption(name string) (ref OptReference) {
var opt cliOptionParser var opt cliOptionParser
if strings.HasPrefix(name, "-") { if strings.HasPrefix(name, "-") {
@ -170,12 +158,17 @@ func (cli *CliParser) addHelpAndVersion() {
} }
func (cli *CliParser) parseOptions() (commandArgs []string, err error) { func (cli *CliParser) Parse() (err error) {
// var commandArgs []string var arg string
var i int
var args []string
var optionsAllowed bool = true var optionsAllowed bool = true
cli.addHelpAndVersion()
// first parse options and collect argument in the args array
skipNext := false skipNext := false
for i, arg := range cli.cliArgs[1:] { for i, arg = range cli.cliArgs[1:] {
if skipNext { if skipNext {
skipNext = false skipNext = false
} else { } else {
@ -189,42 +182,32 @@ func (cli *CliParser) parseOptions() (commandArgs []string, err error) {
break break
} }
} else { } else {
commandArgs = append(commandArgs, arg) args = append(args, arg)
} }
} }
} }
return
}
func (cli *CliParser) checkOptionValues() (err error) { // then parse collected arguments
for _, opt := range cli.options { if err == nil {
if err = opt.finalCheck(); err != nil {
break
}
}
return
}
func (cli *CliParser) parseCommandArgs(commandArgs []string) (err error) {
var n int var n int
i = 0
i := 0
// acquire arguments as required by the argSpecs // acquire arguments as required by the argSpecs
specIndex := -1 specIndex := -1
for index, argSpec := range cli.argSpecs { for index, argSpec := range cli.argSpecs {
specIndex = index specIndex = index
if n, err = argSpec.parse(cli, specIndex, commandArgs, i); err != nil { if n, err = argSpec.parse(cli, specIndex, args, i); err != nil {
break break
} }
i += n i += n
if i >= len(commandArgs) { if i >= len(args) {
break break
} }
} }
// check if there are remaining arg-specs that require a value // check if there are remaining arg-specs that require a value
if err == nil { if err == nil {
if i < len(commandArgs) { if i < len(args) {
err = fmt.Errorf("too many arguments: %d allowed", i) err = fmt.Errorf("too many arguments: %d allowed", i)
} else { } else {
specIndex++ specIndex++
@ -242,26 +225,7 @@ func (cli *CliParser) parseCommandArgs(commandArgs []string) (err error) {
} }
} }
} }
return
}
func (cli *CliParser) Parse() (err error) {
var commandArgs []string
cli.addHelpAndVersion()
// first parse options and collect command arguments in the args array
if commandArgs, err = cli.parseOptions(); err != nil {
return
} }
// do final checks
if err = cli.checkOptionValues(); err != nil {
return
}
// then parse collected arguments
err = cli.parseCommandArgs(commandArgs)
return return
} }

View File

@ -153,13 +153,13 @@ func (opt *cliOptionBase) fetchOptionValue(parser cliParser, argIndex int, value
return return
} }
func (opt *cliOptionBase) finalCheck() (err error) { func (opt *cliOptionBase) finalCheck(cliValue string) (err error) {
return return
} }
func (opt *cliOptionBase) checkValue(value any) (err error) { func (opt *cliOptionBase) checkValue(cliValue string, value any) (err error) {
if opt.finalCheckFunc != nil { if opt.finalCheckFunc != nil {
err = opt.finalCheckFunc(value) err = opt.finalCheckFunc(cliValue, value)
} }
return return
} }

View File

@ -67,9 +67,9 @@ func (opt *cliOptionBool) parse(parser cliParser, argIndex int, valuePtr *string
return return
} }
func (opt *cliOptionBool) finalCheck() (err error) { func (opt *cliOptionBool) finalCheck(cliValue string) (err error) {
currentValue, _ := opt.getTargetVar() currentValue, _ := opt.getTargetVar()
return opt.getBase().checkValue(currentValue) return opt.getBase().checkValue(cliValue, currentValue)
} }
func (cli *CliParser) AddBoolOpt(name, short string, targetVar *bool, description string, aliases ...string) OptReference { func (cli *CliParser) AddBoolOpt(name, short string, targetVar *bool, description string, aliases ...string) OptReference {

View File

@ -75,7 +75,7 @@ func (opt *cliOptionIntArray) parse(parser cliParser, argIndex int, valuePtr *st
err = errInvalidOptionValue(opt.name, boxedValue, "num-array") err = errInvalidOptionValue(opt.name, boxedValue, "num-array")
} }
} else { } else {
if !opt.alreadySeen || (valuePtr != nil && parser.FlagIsSet(ResetOnEqualSign)) { if !opt.alreadySeen {
*opt.targetVar = []int{} *opt.targetVar = []int{}
opt.alreadySeen = true opt.alreadySeen = true
} }
@ -97,9 +97,9 @@ func (opt *cliOptionIntArray) parse(parser cliParser, argIndex int, valuePtr *st
return return
} }
func (opt *cliOptionIntArray) finalCheck() (err error) { func (opt *cliOptionIntArray) finalCheck(cliValue string) (err error) {
currentValue, _ := opt.getTargetVar() currentValue, _ := opt.getTargetVar()
return opt.getBase().checkValue(currentValue) return opt.getBase().checkValue(cliValue, currentValue)
} }
func (cli *CliParser) AddIntArrayOpt(name, short string, targetVar *[]int, defaultValue []int, description string, aliases ...string) OptReference { func (cli *CliParser) AddIntArrayOpt(name, short string, targetVar *[]int, defaultValue []int, description string, aliases ...string) OptReference {

View File

@ -57,9 +57,9 @@ func (opt *cliOptionInt) parse(parser cliParser, argIndex int, valuePtr *string)
} }
return return
} }
func (opt *cliOptionInt) finalCheck() (err error) { func (opt *cliOptionInt) finalCheck(cliValue string) (err error) {
currentValue, _ := opt.getTargetVar() currentValue, _ := opt.getTargetVar()
return opt.getBase().checkValue(currentValue) return opt.getBase().checkValue(cliValue, currentValue)
} }
func (cli *CliParser) AddIntOpt(name, short string, targetVar *int, defaultValue int, description string, aliases ...string) OptReference { func (cli *CliParser) AddIntOpt(name, short string, targetVar *int, defaultValue int, description string, aliases ...string) OptReference {

View File

@ -53,9 +53,9 @@ func (opt *cliOptionMulti) parse(parser cliParser, argIndex int, valuePtr *strin
value = "true" value = "true"
return return
} }
func (opt *cliOptionMulti) finalCheck() (err error) { func (opt *cliOptionMulti) finalCheck(cliValue string) (err error) {
currentValue, _ := opt.getTargetVar() currentValue, _ := opt.getTargetVar()
return opt.getBase().checkValue(currentValue) return opt.getBase().checkValue(cliValue, currentValue)
} }
func (cli *CliParser) AddMultiOpt(name, short string, targetVar *int, defaultValue int, description string, aliases ...string) OptReference { func (cli *CliParser) AddMultiOpt(name, short string, targetVar *int, defaultValue int, description string, aliases ...string) OptReference {

View File

@ -85,7 +85,7 @@ func (cli *CliParser) AddStringArrayOpt(name, short string, targetVar *[]string,
return opt return opt
} }
func (opt *cliOptionStringArray) finalCheck() (err error) { func (opt *cliOptionStringArray) finalCheck(cliValue string) (err error) {
currentValue, _ := opt.getTargetVar() currentValue, _ := opt.getTargetVar()
return opt.getBase().checkValue(currentValue) return opt.getBase().checkValue(cliValue, currentValue)
} }

View File

@ -89,9 +89,9 @@ func (opt *cliOptionStringMap) parse(parser cliParser, argIndex int, valuePtr *s
return return
} }
func (opt *cliOptionStringMap) finalCheck() (err error) { func (opt *cliOptionStringMap) finalCheck(cliValue string) (err error) {
currentValue, _ := opt.getTargetVar() currentValue, _ := opt.getTargetVar()
return opt.getBase().checkValue(currentValue) return opt.getBase().checkValue(cliValue, currentValue)
} }
func (cli *CliParser) AddStringMapOpt(name, short string, targetVar *map[string]string, defaultValue map[string]string, description string, aliases ...string) OptReference { func (cli *CliParser) AddStringMapOpt(name, short string, targetVar *map[string]string, defaultValue map[string]string, description string, aliases ...string) OptReference {

View File

@ -55,9 +55,9 @@ func (opt *cliOptionString) parse(parser cliParser, argIndex int, valuePtr *stri
} }
return return
} }
func (opt *cliOptionString) finalCheck() (err error) { func (opt *cliOptionString) finalCheck(cliValue string) (err error) {
currentValue, _ := opt.getTargetVar() currentValue, _ := opt.getTargetVar()
return opt.getBase().checkValue(currentValue) return opt.getBase().checkValue(cliValue, currentValue)
} }
func (cli *CliParser) AddStringOpt(name, short string, targetVar *string, defaultValue string, description string, aliases ...string) OptReference { func (cli *CliParser) AddStringOpt(name, short string, targetVar *string, defaultValue string, description string, aliases ...string) OptReference {

View File

@ -37,7 +37,7 @@ func TestOneOptWithEqual(t *testing.T) {
func addBoxOption(cli *CliParser, boxPtr *[]int) { func addBoxOption(cli *CliParser, boxPtr *[]int) {
// Define options // Define options
optRef := cli.AddIntArrayOpt("box", "b", boxPtr, []int{1, 2, 3, 4}, "Box spec: Left,Width,Top,Height; provide 4 int values") optRef := cli.AddIntArrayOpt("box", "b", boxPtr, []int{1, 2, 3, 4}, "Box spec: Left,Width,Top,Height; provide 4 int values")
optRef.OnFinalCheck(func(currentValue any) (err error) { optRef.OnFinalCheck(func(cliValue string, currentValue any) (err error) {
if array, ok := currentValue.([]int); ok { if array, ok := currentValue.([]int); ok {
if len(array) != 4 { if len(array) != 4 {
err = fmt.Errorf("--box option requires exactly 4 items, %d provided", len(array)) err = fmt.Errorf("--box option requires exactly 4 items, %d provided", len(array))
@ -49,34 +49,8 @@ func addBoxOption(cli *CliParser, boxPtr *[]int) {
}) })
} }
func testIntArrayOptOk(t *testing.T, n int, args []string, flags ...int16) {
var box []int
var cli CliParser
t.Logf("Arg set n. %d", n)
addBoxOption(&cli, &box)
cli.Init(args, "1.0.0", "TestIntArrayOpt description", flags...)
if err := cli.Parse(); err != nil {
t.Error(err)
} else if len(box) != 4 {
t.Errorf(`Expected 4 items, got %d`, len(box))
}
}
func testIntArrayOptKo(t *testing.T, n int, args []string, msg string, flags ...int16) {
var box []int
var cli CliParser
t.Logf("Arg set n. %d", n)
addBoxOption(&cli, &box)
cli.Init(args, "1.0.0", "TestIntArrayOpt description", flags...)
if err := cli.Parse(); err == nil {
t.Errorf("Expected error, got nil")
} else if err.Error() != msg {
t.Errorf(`Invalid error: %q; expected: %q`, err.Error(), msg)
}
}
func TestIntArrayOpt(t *testing.T) { func TestIntArrayOpt(t *testing.T) {
var args []string var box []int
// Always recover from panic to return error before adding options // Always recover from panic to return error before adding options
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
@ -87,57 +61,68 @@ func TestIntArrayOpt(t *testing.T) {
} }
}() }()
n := 0 args_1 := []string{
n++
args = []string{
"TestIntArrayOpt", "TestIntArrayOpt",
"--box=100,200,150,450", "--box=100,200,150,450",
} }
testIntArrayOptOk(t, n, args)
n++ if true {
args = []string{ var cli CliParser
t.Logf("Arg set n. 1")
addBoxOption(&cli, &box)
cli.Init(args_1, "1.0.0", "TestIntArrayOpt description")
if err := cli.Parse(); err != nil {
t.Error(err)
} else if len(box) != 4 {
t.Errorf(`Expected 4 items, got %d`, len(box))
}
}
args_2 := []string{
"TestIntArrayOpt", "TestIntArrayOpt",
"--box=100,200,150", "--box=100,200,150",
} }
testIntArrayOptKo(t, n, args, "--box option requires exactly 4 items, 3 provided") if true {
var cli CliParser
t.Logf("Arg set n. 2")
addBoxOption(&cli, &box)
cli.Init(args_2, "1.0.0", "TestIntArrayOpt description")
if err := cli.Parse(); err == nil {
t.Errorf("Expected error, got nil")
} else if err.Error() != "--box option requires exactly 4 items, 3 provided" {
t.Errorf(`Invalid error: %q; expected: "--box option requires exactly 4 items, 3 provided"`, err.Error())
}
}
n++ args_3 := []string{
args = []string{
"TestIntArrayOpt", "TestIntArrayOpt",
"--box", "100,200,150,450", "--box", "100,200,150,450",
} }
testIntArrayOptOk(t, n, args) if true {
var cli CliParser
t.Logf("Arg set n. 3")
addBoxOption(&cli, &box)
cli.Init(args_3, "1.0.0", "TestIntArrayOpt description")
if err := cli.Parse(); err != nil {
t.Error(err)
} else if len(box) != 4 {
t.Errorf(`Expected 4 items, got %d`, len(box))
}
}
n++ args_4 := []string{
args = []string{
"TestIntArrayOpt", "TestIntArrayOpt",
"--box", "--box",
} }
testIntArrayOptKo(t, n, args, `option "box" requires a value`) if true {
var cli CliParser
n++ t.Logf("Arg set n. 4")
args = []string{ addBoxOption(&cli, &box)
"TestIntArrayOpt", cli.Init(args_4, "1.0.0", "TestIntArrayOpt description")
"--box", "100,200,150", if err := cli.Parse(); err == nil {
"--box", "450", t.Errorf("Expected error, got nil")
} else if err.Error() != `option "box" requires a value` {
t.Errorf(`Invalid error - Expected: 'option "box" requires a value'; got '%s'`, err.Error())
} }
testIntArrayOptOk(t, n, args)
n++
args = []string{
"TestIntArrayOpt",
"--box", "100,200,150",
"--box", "450,12",
} }
testIntArrayOptKo(t, n, args, "--box option requires exactly 4 items, 5 provided")
n++
args = []string{
"TestIntArrayOpt",
"--box", "100,200,150",
"--box=100,200,150,450",
}
testIntArrayOptOk(t, n, args, ResetOnEqualSign)
} }

View File

@ -104,12 +104,16 @@ func (cli *CliParser) parseArg(arg string, index int) (skipNextArg bool, err err
} }
for i, optName := range opts { for i, optName := range opts {
if opt := cli.findOptionByArg(dashes + optName); opt != nil { if opt := cli.findOptionByArg(dashes + optName); opt != nil {
var optValue string
if equalPresent && i == len(opts)-1 { if equalPresent && i == len(opts)-1 {
_, _, err = opt.parse(cli, index, &value) _, optValue, err = opt.parse(cli, index, &value)
} else if i < len(opts)-1 && opt.requiresValue() { } else if i < len(opts)-1 && opt.requiresValue() {
err = errMissingOptionValue(dashes + optName) err = errMissingOptionValue(dashes + optName)
} else { } else {
skipNextArg, _, err = opt.parse(cli, index, nil) skipNextArg, optValue, err = opt.parse(cli, index, nil)
}
if err == nil && i == len(opts)-1 {
err = opt.finalCheck(optValue)
} }
} else { } else {
err = errUnknownOption(dashes + optName) err = errUnknownOption(dashes + optName)