diff --git a/cli.go b/cli.go index afea65f..88d4321 100644 --- a/cli.go +++ b/cli.go @@ -163,6 +163,7 @@ func (cli *CliParser) Parse() (err error) { cli.addHelpAndVersion() + // first parse options and collect argument in the args array skipNext := false for i, arg = range cli.cliArgs[1:] { if skipNext { @@ -182,12 +183,16 @@ func (cli *CliParser) Parse() (err error) { } } } + + // then parse collected arguments if err == nil { - var argSpec argSpec - var n, specIndex int + var n int 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 { break } @@ -196,16 +201,22 @@ func (cli *CliParser) Parse() (err error) { break } } + + // check if there are remaining arg-specs that require a value if err == nil { if i < len(args) { err = fmt.Errorf("too many arguments: %d allowed", i) } else { specIndex++ - for _, spec := range cli.argSpecs[specIndex:] { - if !spec.getBase().required { - specIndex++ + if specIndex < len(cli.argSpecs) { + // skip all non required args + for _, spec := range cli.argSpecs[specIndex:] { + if !spec.getBase().required { + specIndex++ + } } } + // return error if there are remaining arg-specs that require a value if specIndex < len(cli.argSpecs) { err = errTooFewArguments(len(cli.argSpecs)) }