Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc-cloned / node_modules / yargs / lib / completion.js
1 var fs = require('fs')
2 var path = require('path')
3
4 // add bash completions to your
5 //  yargs-powered applications.
6 module.exports = function (yargs, usage) {
7   var self = {
8     completionKey: 'get-yargs-completions'
9   }
10
11   // get a list of completion commands.
12   self.getCompletion = function (done) {
13     var completions = []
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)
17
18     // a custom completion function can be provided
19     // to completion().
20     if (completionFunction) {
21       if (completionFunction.length < 3) {
22         var result = completionFunction(current, argv)
23
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 })
30           })
31         }
32
33         // synchronous completion function.
34         return done(result)
35       } else {
36         // asynchronous completion function
37         return completionFunction(current, argv, function (completions) {
38           done(completions)
39         })
40       }
41     }
42
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())
47       }
48     }
49
50     if (!current.match(/^-/)) {
51       usage.getCommands().forEach(function (command) {
52         if (previous.indexOf(command[0]) === -1) {
53           completions.push(command[0])
54         }
55       })
56     }
57
58     if (current.match(/^-/)) {
59       Object.keys(yargs.getOptions().key).forEach(function (key) {
60         completions.push('--' + key)
61       })
62     }
63
64     done(completions)
65   }
66
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'),
71       'utf-8'
72     )
73     var name = path.basename($0)
74
75     // add ./to applications not yet installed as bin.
76     if ($0.match(/\.js$/)) $0 = './' + $0
77
78     script = script.replace(/{{app_name}}/g, name)
79     return script.replace(/{{app_path}}/g, $0)
80   }
81
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
88   }
89
90   return self
91 }