Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bad argument list to user error when possible #38

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 27 additions & 9 deletions docopt.go
Original file line number Diff line number Diff line change
@@ -129,18 +129,22 @@ func parse(doc string, argv []string, help bool, version string, optionsFirst bo
return
}
matched, left, collected := pat.match(&patternArgv, nil)
if matched && len(*left) == 0 {
patFlat, err = pat.flat(patternDefault)
if err != nil {
output = handleError(err, usage)
return
if !matched || len(*left) > 0 {
badArgs := left.ArgumentsString()
if len(badArgs) > 0 {
err = newUserError("unexpected arguments: " + badArgs)
} else {
err = newUserError("")
}
args = append(patFlat, *collected...).dictionary()
output = handleError(err, usage)
return
}

err = newUserError("")
output = handleError(err, usage)
patFlat, err = pat.flat(patternDefault)
if err != nil {
output = handleError(err, usage)
return
}
args = append(patFlat, *collected...).dictionary()
return
}

@@ -1215,6 +1219,20 @@ func (pl patternList) dictionary() map[string]interface{} {
return dict
}

// ArgumentsString converts patternList into a space separated string of
// arguments; it ignores any patterns that are not arguments, and does not walk
// children.
func (pl patternList) ArgumentsString() string {
args := []string{}
for _, arg := range pl {
argStr, ok := arg.value.(string)
if ok && (arg.t&patternArgument) != 0 {
args = append(args, argStr)
}
}
return strings.Join(args, " ")
}

func stringPartition(s, sep string) (string, string, string) {
sepPos := strings.Index(s, sep)
if sepPos == -1 { // no seperator found
14 changes: 13 additions & 1 deletion docopt_test.go
Original file line number Diff line number Diff line change
@@ -138,9 +138,21 @@ func TestCommands(t *testing.T) {
t.Error(err)
}
_, err := Parse("Usage: prog a b", []string{"b", "a"}, true, "", false, false)
if _, ok := err.(*UserError); !ok {
userErr, ok := err.(*UserError)
if !ok {
t.Error(err)
}
if !strings.HasSuffix(userErr.Error(), ": b a") {
t.Error("expected invalid arguments")
}
_, err = Parse("Usage: prog a", []string{"a", "b", "c"}, true, "", false, false)
userErr, ok = err.(*UserError)
if !ok {
t.Error(err)
}
if !strings.HasSuffix(userErr.Error(), ": b c") {
t.Error("expected invalid arguments")
}
return
}