completion.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import { isCommandBuilderCallback } from './command.js';
  2. import { assertNotStrictEqual } from './typings/common-types.js';
  3. import * as templates from './completion-templates.js';
  4. import { isPromise } from './utils/is-promise.js';
  5. import { parseCommand } from './parse-command.js';
  6. export class Completion {
  7. constructor(yargs, usage, command, shim) {
  8. var _a, _b, _c;
  9. this.yargs = yargs;
  10. this.usage = usage;
  11. this.command = command;
  12. this.shim = shim;
  13. this.completionKey = 'get-yargs-completions';
  14. this.aliases = null;
  15. this.customCompletionFunction = null;
  16. this.indexAfterLastReset = 0;
  17. this.zshShell =
  18. (_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) ||
  19. ((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false;
  20. }
  21. defaultCompletion(args, argv, current, done) {
  22. const handlers = this.command.getCommandHandlers();
  23. for (let i = 0, ii = args.length; i < ii; ++i) {
  24. if (handlers[args[i]] && handlers[args[i]].builder) {
  25. const builder = handlers[args[i]].builder;
  26. if (isCommandBuilderCallback(builder)) {
  27. this.indexAfterLastReset = i + 1;
  28. const y = this.yargs.getInternalMethods().reset();
  29. builder(y, true);
  30. return y.argv;
  31. }
  32. }
  33. }
  34. const completions = [];
  35. this.commandCompletions(completions, args, current);
  36. this.optionCompletions(completions, args, argv, current);
  37. this.choicesFromOptionsCompletions(completions, args, argv, current);
  38. this.choicesFromPositionalsCompletions(completions, args, argv, current);
  39. done(null, completions);
  40. }
  41. commandCompletions(completions, args, current) {
  42. const parentCommands = this.yargs
  43. .getInternalMethods()
  44. .getContext().commands;
  45. if (!current.match(/^-/) &&
  46. parentCommands[parentCommands.length - 1] !== current &&
  47. !this.previousArgHasChoices(args)) {
  48. this.usage.getCommands().forEach(usageCommand => {
  49. const commandName = parseCommand(usageCommand[0]).cmd;
  50. if (args.indexOf(commandName) === -1) {
  51. if (!this.zshShell) {
  52. completions.push(commandName);
  53. }
  54. else {
  55. const desc = usageCommand[1] || '';
  56. completions.push(commandName.replace(/:/g, '\\:') + ':' + desc);
  57. }
  58. }
  59. });
  60. }
  61. }
  62. optionCompletions(completions, args, argv, current) {
  63. if ((current.match(/^-/) || (current === '' && completions.length === 0)) &&
  64. !this.previousArgHasChoices(args)) {
  65. const options = this.yargs.getOptions();
  66. const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
  67. Object.keys(options.key).forEach(key => {
  68. const negable = !!options.configuration['boolean-negation'] &&
  69. options.boolean.includes(key);
  70. const isPositionalKey = positionalKeys.includes(key);
  71. if (!isPositionalKey &&
  72. !options.hiddenOptions.includes(key) &&
  73. !this.argsContainKey(args, key, negable)) {
  74. this.completeOptionKey(key, completions, current);
  75. if (negable && !!options.default[key])
  76. this.completeOptionKey(`no-${key}`, completions, current);
  77. }
  78. });
  79. }
  80. }
  81. choicesFromOptionsCompletions(completions, args, argv, current) {
  82. if (this.previousArgHasChoices(args)) {
  83. const choices = this.getPreviousArgChoices(args);
  84. if (choices && choices.length > 0) {
  85. completions.push(...choices.map(c => c.replace(/:/g, '\\:')));
  86. }
  87. }
  88. }
  89. choicesFromPositionalsCompletions(completions, args, argv, current) {
  90. if (current === '' &&
  91. completions.length > 0 &&
  92. this.previousArgHasChoices(args)) {
  93. return;
  94. }
  95. const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
  96. const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length +
  97. 1);
  98. const positionalKey = positionalKeys[argv._.length - offset - 1];
  99. if (!positionalKey) {
  100. return;
  101. }
  102. const choices = this.yargs.getOptions().choices[positionalKey] || [];
  103. for (const choice of choices) {
  104. if (choice.startsWith(current)) {
  105. completions.push(choice.replace(/:/g, '\\:'));
  106. }
  107. }
  108. }
  109. getPreviousArgChoices(args) {
  110. if (args.length < 1)
  111. return;
  112. let previousArg = args[args.length - 1];
  113. let filter = '';
  114. if (!previousArg.startsWith('-') && args.length > 1) {
  115. filter = previousArg;
  116. previousArg = args[args.length - 2];
  117. }
  118. if (!previousArg.startsWith('-'))
  119. return;
  120. const previousArgKey = previousArg.replace(/^-+/, '');
  121. const options = this.yargs.getOptions();
  122. const possibleAliases = [
  123. previousArgKey,
  124. ...(this.yargs.getAliases()[previousArgKey] || []),
  125. ];
  126. let choices;
  127. for (const possibleAlias of possibleAliases) {
  128. if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) &&
  129. Array.isArray(options.choices[possibleAlias])) {
  130. choices = options.choices[possibleAlias];
  131. break;
  132. }
  133. }
  134. if (choices) {
  135. return choices.filter(choice => !filter || choice.startsWith(filter));
  136. }
  137. }
  138. previousArgHasChoices(args) {
  139. const choices = this.getPreviousArgChoices(args);
  140. return choices !== undefined && choices.length > 0;
  141. }
  142. argsContainKey(args, key, negable) {
  143. const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1;
  144. if (argsContains(key))
  145. return true;
  146. if (negable && argsContains(`no-${key}`))
  147. return true;
  148. if (this.aliases) {
  149. for (const alias of this.aliases[key]) {
  150. if (argsContains(alias))
  151. return true;
  152. }
  153. }
  154. return false;
  155. }
  156. completeOptionKey(key, completions, current) {
  157. const descs = this.usage.getDescriptions();
  158. const startsByTwoDashes = (s) => /^--/.test(s);
  159. const isShortOption = (s) => /^[^0-9]$/.test(s);
  160. const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
  161. if (!this.zshShell) {
  162. completions.push(dashes + key);
  163. }
  164. else {
  165. const desc = descs[key] || '';
  166. completions.push(dashes +
  167. `${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`);
  168. }
  169. }
  170. customCompletion(args, argv, current, done) {
  171. assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
  172. if (isSyncCompletionFunction(this.customCompletionFunction)) {
  173. const result = this.customCompletionFunction(current, argv);
  174. if (isPromise(result)) {
  175. return result
  176. .then(list => {
  177. this.shim.process.nextTick(() => {
  178. done(null, list);
  179. });
  180. })
  181. .catch(err => {
  182. this.shim.process.nextTick(() => {
  183. done(err, undefined);
  184. });
  185. });
  186. }
  187. return done(null, result);
  188. }
  189. else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
  190. return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => {
  191. done(null, completions);
  192. });
  193. }
  194. else {
  195. return this.customCompletionFunction(current, argv, completions => {
  196. done(null, completions);
  197. });
  198. }
  199. }
  200. getCompletion(args, done) {
  201. const current = args.length ? args[args.length - 1] : '';
  202. const argv = this.yargs.parse(args, true);
  203. const completionFunction = this.customCompletionFunction
  204. ? (argv) => this.customCompletion(args, argv, current, done)
  205. : (argv) => this.defaultCompletion(args, argv, current, done);
  206. return isPromise(argv)
  207. ? argv.then(completionFunction)
  208. : completionFunction(argv);
  209. }
  210. generateCompletionScript($0, cmd) {
  211. let script = this.zshShell
  212. ? templates.completionZshTemplate
  213. : templates.completionShTemplate;
  214. const name = this.shim.path.basename($0);
  215. if ($0.match(/\.js$/))
  216. $0 = `./${$0}`;
  217. script = script.replace(/{{app_name}}/g, name);
  218. script = script.replace(/{{completion_command}}/g, cmd);
  219. return script.replace(/{{app_path}}/g, $0);
  220. }
  221. registerFunction(fn) {
  222. this.customCompletionFunction = fn;
  223. }
  224. setParsed(parsed) {
  225. this.aliases = parsed.aliases;
  226. }
  227. }
  228. export function completion(yargs, usage, command, shim) {
  229. return new Completion(yargs, usage, command, shim);
  230. }
  231. function isSyncCompletionFunction(completionFunction) {
  232. return completionFunction.length < 3;
  233. }
  234. function isFallbackCompletionFunction(completionFunction) {
  235. return completionFunction.length > 3;
  236. }