completion.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var fs = require('fs'),
  2. path = require('path')
  3. // add bash completions to your
  4. // yargs-powered applications.
  5. module.exports = function (yargs, usage) {
  6. var self = {
  7. completionKey: 'get-yargs-completions'
  8. }
  9. // get a list of completion commands.
  10. self.getCompletion = function (done) {
  11. var completions = [],
  12. current = process.argv[process.argv.length - 1],
  13. previous = process.argv.slice(process.argv.indexOf('--' + self.completionKey) + 1),
  14. argv = yargs.parse(previous)
  15. // a custom completion function can be provided
  16. // to completion().
  17. if (completionFunction) {
  18. if (completionFunction.length < 3) {
  19. // synchronous completion function.
  20. return done(completionFunction(current, argv))
  21. } else {
  22. // asynchronous completion function
  23. return completionFunction(current, argv, function (completions) {
  24. done(completions)
  25. })
  26. }
  27. }
  28. if (!current.match(/^-/)) {
  29. usage.getCommands().forEach(function (command) {
  30. completions.push(command[0])
  31. })
  32. }
  33. if (current.match(/^-/)) {
  34. Object.keys(yargs.getOptions().key).forEach(function (key) {
  35. completions.push('--' + key)
  36. })
  37. }
  38. done(completions)
  39. }
  40. // generate the completion script to add to your .bashrc.
  41. self.generateCompletionScript = function ($0) {
  42. var script = fs.readFileSync(
  43. path.resolve(__dirname, '../completion.sh.hbs'),
  44. 'utf-8'
  45. ),
  46. name = path.basename($0)
  47. // add ./to applications not yet installed as bin.
  48. if ($0.match(/\.js$/)) $0 = './' + $0
  49. script = script.replace(/{{app_name}}/g, name)
  50. return script.replace(/{{app_path}}/g, $0)
  51. }
  52. // register a function to perform your own custom
  53. // completions., this function can be either
  54. // synchrnous or asynchronous.
  55. var completionFunction = null
  56. self.registerFunction = function (fn) {
  57. completionFunction = fn
  58. }
  59. return self
  60. }