completion.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. 'use strict';
  2. const constants = require('constants');
  3. const fs = require('fs');
  4. const path = require('path');
  5. const Q = require('q');
  6. const shell = require('./shell');
  7. const escape = shell.escape;
  8. const unescape = shell.unescape;
  9. /**
  10. * Most of the code adopted from the npm package shell completion code.
  11. * See https://github.com/isaacs/npm/blob/master/lib/completion.js
  12. *
  13. * @returns {COA.CoaObject}
  14. */
  15. module.exports = function completion() {
  16. return this
  17. .title('Shell completion')
  18. .helpful()
  19. .arg()
  20. .name('raw')
  21. .title('Completion words')
  22. .arr()
  23. .end()
  24. .act((opts, args) => {
  25. if(process.platform === 'win32') {
  26. const e = new Error('shell completion not supported on windows');
  27. e.code = 'ENOTSUP';
  28. e.errno = constants.ENOTSUP;
  29. return this.reject(e);
  30. }
  31. // if the COMP_* isn't in the env, then just dump the script
  32. if((process.env.COMP_CWORD == null)
  33. || (process.env.COMP_LINE == null)
  34. || (process.env.COMP_POINT == null)) {
  35. return dumpScript(this._cmd._name);
  36. }
  37. console.error('COMP_LINE: %s', process.env.COMP_LINE);
  38. console.error('COMP_CWORD: %s', process.env.COMP_CWORD);
  39. console.error('COMP_POINT: %s', process.env.COMP_POINT);
  40. console.error('args: %j', args.raw);
  41. // completion opts
  42. opts = getOpts(args.raw);
  43. // cmd
  44. const parsed = this._cmd._parseCmd(opts.partialWords);
  45. return Q.when(complete(parsed.cmd, parsed.opts), compls => {
  46. console.error('filtered: %j', compls);
  47. return console.log(compls.map(escape).join('\n'));
  48. });
  49. });
  50. };
  51. function dumpScript(name) {
  52. const defer = Q.defer();
  53. fs.readFile(path.resolve(__dirname, 'completion.sh'), 'utf8', function(err, d) {
  54. if(err) return defer.reject(err);
  55. d = d.replace(/{{cmd}}/g, path.basename(name)).replace(/^#!.*?\n/, '');
  56. process.stdout.on('error', onError);
  57. process.stdout.write(d, () => defer.resolve());
  58. });
  59. return defer.promise;
  60. function onError(err) {
  61. // Darwin is a real dick sometimes.
  62. //
  63. // This is necessary because the "source" or "." program in
  64. // bash on OS X closes its file argument before reading
  65. // from it, meaning that you get exactly 1 write, which will
  66. // work most of the time, and will always raise an EPIPE.
  67. //
  68. // Really, one should not be tossing away EPIPE errors, or any
  69. // errors, so casually. But, without this, `. <(cmd completion)`
  70. // can never ever work on OS X.
  71. if(err.errno !== constants.EPIPE) return defer.reject(err);
  72. process.stdout.removeListener('error', onError);
  73. return defer.resolve();
  74. }
  75. }
  76. function getOpts(argv) {
  77. // get the partial line and partial word, if the point isn't at the end
  78. // ie, tabbing at: cmd foo b|ar
  79. const line = process.env.COMP_LINE;
  80. const w = +process.env.COMP_CWORD;
  81. const point = +process.env.COMP_POINT;
  82. const words = argv.map(unescape);
  83. const word = words[w];
  84. const partialLine = line.substr(0, point);
  85. const partialWords = words.slice(0, w);
  86. // figure out where in that last word the point is
  87. let partialWord = argv[w] || '';
  88. let i = partialWord.length;
  89. while(partialWord.substr(0, i) !== partialLine.substr(-1 * i) && i > 0) i--;
  90. partialWord = unescape(partialWord.substr(0, i));
  91. partialWord && partialWords.push(partialWord);
  92. return {
  93. line,
  94. w,
  95. point,
  96. words,
  97. word,
  98. partialLine,
  99. partialWords,
  100. partialWord
  101. };
  102. }
  103. function complete(cmd, opts) {
  104. let optWord, optPrefix,
  105. compls = [];
  106. // Complete on cmds
  107. if(opts.partialWord.indexOf('-'))
  108. compls = Object.keys(cmd._cmdsByName);
  109. // Complete on required opts without '-' in last partial word
  110. // (if required not already specified)
  111. //
  112. // Commented out because of uselessness:
  113. // -b, --block suggest results in '-' on cmd line;
  114. // next completion suggest all options, because of '-'
  115. //.concat Object.keys(cmd._optsByKey).filter (v) -> cmd._optsByKey[v]._req
  116. else {
  117. // complete on opt values: --opt=| case
  118. const m = opts.partialWord.match(/^(--\w[\w-_]*)=(.*)$/);
  119. if(m) {
  120. optWord = m[1];
  121. optPrefix = optWord + '=';
  122. } else
  123. // complete on opts
  124. // don't complete on opts in case of --opt=val completion
  125. // TODO: don't complete on opts in case of unknown arg after commands
  126. // TODO: complete only on opts with arr() or not already used
  127. // TODO: complete only on full opts?
  128. compls = Object.keys(cmd._optsByKey);
  129. }
  130. // complete on opt values: next arg case
  131. opts.partialWords[opts.w - 1].indexOf('-') || (optWord = opts.partialWords[opts.w - 1]);
  132. // complete on opt values: completion
  133. let opt;
  134. optWord
  135. && (opt = cmd._optsByKey[optWord])
  136. && !opt._flag
  137. && opt._comp
  138. && (compls = Q.join(compls,
  139. Q.when(opt._comp(opts),
  140. (c, o) => c.concat(o.map(v => (optPrefix || '') + v)))));
  141. // TODO: complete on args values (context aware, custom completion?)
  142. // custom completion on cmds
  143. cmd._comp && (compls = Q.join(compls, Q.when(cmd._comp(opts)), (c, o) => c.concat(o)));
  144. // TODO: context aware custom completion on cmds, opts and args
  145. // (can depend on already entered values, especially options)
  146. return Q.when(compls, complitions => {
  147. console.error('partialWord: %s', opts.partialWord);
  148. console.error('compls: %j', complitions);
  149. return compls.filter(c => c.indexOf(opts.partialWord) === 0);
  150. });
  151. }