2 var path = require('path')
4 // add bash completions to your
5 // yargs-powered applications.
6 module.exports = function (yargs, usage) {
8 completionKey: 'get-yargs-completions'
11 // get a list of completion commands.
12 self.getCompletion = function (done) {
14 var current = process.argv[process.argv.length - 1]
15 var previous = process.argv.slice(process.argv.indexOf('--' + self.completionKey) + 1)
16 var argv = yargs.parse(previous)
18 // a custom completion function can be provided
20 if (completionFunction) {
21 if (completionFunction.length < 3) {
22 var result = completionFunction(current, argv)
24 // promise based completion function.
25 if (typeof result.then === 'function') {
26 return result.then(function (list) {
27 process.nextTick(function () { done(list) })
28 }).catch(function (err) {
29 process.nextTick(function () { throw err })
33 // synchronous completion function.
36 // asynchronous completion function
37 return completionFunction(current, argv, function (completions) {
43 var handlers = yargs.getCommandHandlers()
44 for (var i = 0, ii = previous.length; i < ii; ++i) {
45 if (handlers[previous[i]]) {
46 return handlers[previous[i]](yargs.reset())
50 if (!current.match(/^-/)) {
51 usage.getCommands().forEach(function (command) {
52 if (previous.indexOf(command[0]) === -1) {
53 completions.push(command[0])
58 if (current.match(/^-/)) {
59 Object.keys(yargs.getOptions().key).forEach(function (key) {
60 completions.push('--' + key)
67 // generate the completion script to add to your .bashrc.
68 self.generateCompletionScript = function ($0) {
69 var script = fs.readFileSync(
70 path.resolve(__dirname, '../completion.sh.hbs'),
73 var name = path.basename($0)
75 // add ./to applications not yet installed as bin.
76 if ($0.match(/\.js$/)) $0 = './' + $0
78 script = script.replace(/{{app_name}}/g, name)
79 return script.replace(/{{app_path}}/g, $0)
82 // register a function to perform your own custom
83 // completions., this function can be either
84 // synchrnous or asynchronous.
85 var completionFunction = null
86 self.registerFunction = function (fn) {
87 completionFunction = fn