Skip to content
Open
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
41 changes: 39 additions & 2 deletions confutils.nim
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import
std/[options, strutils, wordwrap],
std/[options, strutils, wordwrap, editdistance],
stew/shims/macros,
confutils/[defs, cli_parser, config_file]

Expand Down Expand Up @@ -409,6 +409,36 @@ proc findSubCmd(cmd: CmdInfo, name: string): CmdInfo =

return nil

proc distanceOpt(opts: openarray[OptInfo], name: string): (OptInfo, int) =
# find nearest match using `editDistance`
if opts.len == 0:
return

var
currOpt = opts[0]
currDist = editDistance(currOpt.name, name)

for i in 1..<opts.len:
let distance = editDistance(opts[i].name, name)
if distance < currDist:
currOpt = opts[i]
currDist = distance

(currOpt, currDist)

proc distanceOpt(cmds: openarray[CmdInfo], name: string): OptInfo =
if cmds.len == 0:
return

var (currOpt, currDist) = distanceOpt(cmds[0].opts, name)
for i in 1..<cmds.len:
let (opt, distance) = distanceOpt(cmds[i].opts, name)
if distance < currDist:
currOpt = opt
currDist = distance

currOpt

proc startsWithIgnoreStyle(s: string, prefix: string): bool =
# Similar in spirit to cmpIgnoreStyle, but compare only the prefix.
var i = 0
Expand Down Expand Up @@ -1002,13 +1032,20 @@ proc load*(Configuration: type,
opt = findOpt(defaultCmd.opts, key)
if opt != nil:
activateCmd(subCmdDiscriminator, defaultCmd)
else:
# we will fail, but before that, suggest nearest match from defaultCmd too.
activeCmds.add defaultCmd
else:
discard

if opt != nil:
applySetter(opt.idx, val)
else:
fail "Unrecognized option '$1'" % [key]
let opt = distanceOpt(activeCmds, key) # suggest nearest match
if opt != nil:
fail "Unrecognized option '$1'. Did you mean '$2'?" % [key, opt.name]
else:
fail "Unrecognized option '$1'" % [key]

of cmdArgument:
if lastCmd.hasSubCommands:
Expand Down