cli.go: fixed an out-of-bound error on cli.argSpecs array

This commit is contained in:
Celestino Amoroso 2026-03-05 06:33:14 +01:00
parent ac8d5fa3a9
commit b5f8d9eaab

17
cli.go
View File

@ -163,6 +163,7 @@ func (cli *CliParser) Parse() (err error) {
cli.addHelpAndVersion() 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 {
@ -182,12 +183,16 @@ func (cli *CliParser) Parse() (err error) {
} }
} }
} }
// then parse collected arguments
if err == nil { if err == nil {
var argSpec argSpec var n int
var n, specIndex int
i = 0 i = 0
for specIndex, argSpec = range cli.argSpecs { // acquire arguments as required by the argSpecs
specIndex := -1
for index, argSpec := range cli.argSpecs {
specIndex = index
if n, err = argSpec.parse(cli, specIndex, args, i); err != nil { if n, err = argSpec.parse(cli, specIndex, args, i); err != nil {
break break
} }
@ -196,16 +201,22 @@ func (cli *CliParser) Parse() (err error) {
break break
} }
} }
// check if there are remaining arg-specs that require a value
if err == nil { if err == nil {
if i < len(args) { 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++
if specIndex < len(cli.argSpecs) {
// skip all non required args
for _, spec := range cli.argSpecs[specIndex:] { for _, spec := range cli.argSpecs[specIndex:] {
if !spec.getBase().required { if !spec.getBase().required {
specIndex++ specIndex++
} }
} }
}
// return error if there are remaining arg-specs that require a value
if specIndex < len(cli.argSpecs) { if specIndex < len(cli.argSpecs) {
err = errTooFewArguments(len(cli.argSpecs)) err = errTooFewArguments(len(cli.argSpecs))
} }