Skip to content

Commit

Permalink
feat: adds recommendCommands() for command suggestions (#580)
Browse files Browse the repository at this point in the history
* feat: provide suggestions if unknown command is called

* add y18n locale support for command recommendations

* fix tests for command recommendations

* make german translation more personal

* update .recommendCommands() following @nexdrew's review

* add more tests for .recommendCommands()

* add didyoumean threshold

* mention in readme no parameter is required for .recommendCommands()

* fix silly mistake

* feat: adds recommendCommands()

* fix: implement @nexdrew's suggestion; sort commands so that we recommend longest first
  • Loading branch information
bcoe committed Aug 14, 2016
1 parent 59a830b commit 59474dc
Show file tree
Hide file tree
Showing 7 changed files with 129 additions and 6 deletions.
6 changes: 6 additions & 0 deletions README.md
Expand Up @@ -1406,6 +1406,12 @@ as a configuration object.
`cwd` can optionally be provided, the package.json will be read
from this location.

.recommendCommands()
---------------------------

Should yargs provide suggestions regarding similar commands if no matching
command is found?

.require(key, [msg | boolean])
------------------------------
.required(key, [msg | boolean])
Expand Down
47 changes: 47 additions & 0 deletions lib/levenshtein.js
@@ -0,0 +1,47 @@
/*
Copyright (c) 2011 Andrei Mackenzie
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

// levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed.
// gist, which can be found here: https://gist.github.com/andrei-m/982927

// Compute the edit distance between the two given strings
module.exports = function (a, b) {
if (a.length === 0) return b.length
if (b.length === 0) return a.length

var matrix = []

// increment along the first column of each row
var i
for (i = 0; i <= b.length; i++) {
matrix[i] = [i]
}

// increment each column in the first row
var j
for (j = 0; j <= a.length; j++) {
matrix[0][j] = j
}

// Fill in the rest of the matrix
for (i = 1; i <= b.length; i++) {
for (j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1]
} else {
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
Math.min(matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j] + 1)) // deletion
}
}
}

return matrix[b.length][a.length]
}
17 changes: 17 additions & 0 deletions lib/validation.js
Expand Up @@ -274,6 +274,23 @@ module.exports = function (yargs, usage, y18n) {
}
}

self.recommendCommands = function (cmd, potentialCommands) {
const distance = require('./levenshtein')
const threshold = 3 // if it takes more than three edits, let's move on.
potentialCommands = potentialCommands.sort(function (a, b) { return b.length - a.length })

var recommended = null
var bestDistance = Infinity
for (var i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
var d = distance(cmd, candidate)
if (d <= threshold && d < bestDistance) {
bestDistance = d
recommended = candidate
}
}
if (recommended) usage.fail(__('Did you mean %s?', recommended))
}

self.reset = function (globalLookup) {
implied = objFilter(implied, function (k, v) {
return globalLookup[k]
Expand Down
3 changes: 2 additions & 1 deletion locales/de.json
Expand Up @@ -33,5 +33,6 @@
"Invalid JSON config file: %s": "Fehlerhafte JSON-Config Datei: %s",
"Path to JSON config file": "Pfad zur JSON-Config Datei",
"Show help": "Hilfe anzeigen",
"Show version number": "Version anzeigen"
"Show version number": "Version anzeigen",
"Did you mean %s?": "Meintest du %s?"
}
3 changes: 2 additions & 1 deletion locales/en.json
Expand Up @@ -33,5 +33,6 @@
"Invalid JSON config file: %s": "Invalid JSON config file: %s",
"Path to JSON config file": "Path to JSON config file",
"Show help": "Show help",
"Show version number": "Show version number"
"Show version number": "Show version number",
"Did you mean %s?": "Did you mean %s?"
}
34 changes: 34 additions & 0 deletions test/yargs.js
Expand Up @@ -261,6 +261,40 @@ describe('yargs dsl tests', function () {
.argv
})

it('recommends a similar command if no command handler is found', function () {
var r = checkOutput(function () {
yargs(['boat'])
.command('goat')
.recommendCommands()
.argv
})

r.errors[1].should.match(/Did you mean goat/)
})

it('does not recommend a similiar command if no similar command exists', function () {
var r = checkOutput(function () {
yargs(['foo'])
.command('nothingSimilar')
.recommendCommands()
.argv
})

r.logs.should.be.empty
})

it('recommends the longest match first', function () {
var r = checkOutput(function () {
yargs(['boat'])
.command('bot')
.command('goat')
.recommendCommands()
.argv
})

r.errors[1].should.match(/Did you mean goat/)
})

it("skips executing top-level command if builder's help is executed", function () {
var r = checkOutput(function () {
yargs(['blerg', '-h'])
Expand Down
25 changes: 21 additions & 4 deletions yargs.js
Expand Up @@ -640,6 +640,12 @@ function Yargs (processArgs, cwd, parentRequire) {
return detectLocale
}

var recommendCommands
self.recommendCommands = function () {
recommendCommands = true
return self
}

self.getUsageInstance = function () {
return usage
}
Expand Down Expand Up @@ -715,10 +721,21 @@ function Yargs (processArgs, cwd, parentRequire) {
// if there's a handler associated with a
// command defer processing to it.
var handlerKeys = command.getCommands()
for (var i = 0, cmd; (cmd = argv._[i]) !== undefined; i++) {
if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
setPlaceholderKeys(argv)
return command.runCommand(cmd, self, parsed)
if (handlerKeys.length) {
var firstUnknownCommand
for (var i = 0, cmd; (cmd = argv._[i]) !== undefined; i++) {
if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
setPlaceholderKeys(argv)
return command.runCommand(cmd, self, parsed)
} else if (!firstUnknownCommand && cmd !== completionCommand) {
firstUnknownCommand = cmd
}
}

// recommend a command if recommendCommands() has
// been enabled, and no commands were found to execute
if (recommendCommands && firstUnknownCommand) {
validation.recommendCommands(firstUnknownCommand, handlerKeys)
}
}

Expand Down

0 comments on commit 59474dc

Please sign in to comment.