completion.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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, negable && !!options.default[key]);
  75. }
  76. });
  77. }
  78. }
  79. choicesFromOptionsCompletions(completions, args, argv, current) {
  80. if (this.previousArgHasChoices(args)) {
  81. const choices = this.getPreviousArgChoices(args);
  82. if (choices && choices.length > 0) {
  83. completions.push(...choices.map(c => c.replace(/:/g, '\\:')));
  84. }
  85. }
  86. }
  87. choicesFromPositionalsCompletions(completions, args, argv, current) {
  88. if (current === '' &&
  89. completions.length > 0 &&
  90. this.previousArgHasChoices(args)) {
  91. return;
  92. }
  93. const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
  94. const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length +
  95. 1);
  96. const positionalKey = positionalKeys[argv._.length - offset - 1];
  97. if (!positionalKey) {
  98. return;
  99. }
  100. const choices = this.yargs.getOptions().choices[positionalKey] || [];
  101. for (const choice of choices) {
  102. if (choice.startsWith(current)) {
  103. completions.push(choice.replace(/:/g, '\\:'));
  104. }
  105. }
  106. }
  107. getPreviousArgChoices(args) {
  108. if (args.length < 1)
  109. return;
  110. let previousArg = args[args.length - 1];
  111. let filter = '';
  112. if (!previousArg.startsWith('-') && args.length > 1) {
  113. filter = previousArg;
  114. previousArg = args[args.length - 2];
  115. }
  116. if (!previousArg.startsWith('-'))
  117. return;
  118. const previousArgKey = previousArg.replace(/^-+/, '');
  119. const options = this.yargs.getOptions();
  120. const possibleAliases = [
  121. previousArgKey,
  122. ...(this.yargs.getAliases()[previousArgKey] || []),
  123. ];
  124. let choices;
  125. for (const possibleAlias of possibleAliases) {
  126. if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) &&
  127. Array.isArray(options.choices[possibleAlias])) {
  128. choices = options.choices[possibleAlias];
  129. break;
  130. }
  131. }
  132. if (choices) {
  133. return choices.filter(choice => !filter || choice.startsWith(filter));
  134. }
  135. }
  136. previousArgHasChoices(args) {
  137. const choices = this.getPreviousArgChoices(args);
  138. return choices !== undefined && choices.length > 0;
  139. }
  140. argsContainKey(args, key, negable) {
  141. const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1;
  142. if (argsContains(key))
  143. return true;
  144. if (negable && argsContains(`no-${key}`))
  145. return true;
  146. if (this.aliases) {
  147. for (const alias of this.aliases[key]) {
  148. if (argsContains(alias))
  149. return true;
  150. }
  151. }
  152. return false;
  153. }
  154. completeOptionKey(key, completions, current, negable) {
  155. var _a, _b, _c, _d;
  156. let keyWithDesc = key;
  157. if (this.zshShell) {
  158. const descs = this.usage.getDescriptions();
  159. const aliasKey = (_b = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b.find(alias => {
  160. const desc = descs[alias];
  161. return typeof desc === 'string' && desc.length > 0;
  162. });
  163. const descFromAlias = aliasKey ? descs[aliasKey] : undefined;
  164. const desc = (_d = (_c = descs[key]) !== null && _c !== void 0 ? _c : descFromAlias) !== null && _d !== void 0 ? _d : '';
  165. keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc
  166. .replace('__yargsString__:', '')
  167. .replace(/(\r\n|\n|\r)/gm, ' ')}`;
  168. }
  169. const startsByTwoDashes = (s) => /^--/.test(s);
  170. const isShortOption = (s) => /^[^0-9]$/.test(s);
  171. const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
  172. completions.push(dashes + keyWithDesc);
  173. if (negable) {
  174. completions.push(dashes + 'no-' + keyWithDesc);
  175. }
  176. }
  177. customCompletion(args, argv, current, done) {
  178. assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
  179. if (isSyncCompletionFunction(this.customCompletionFunction)) {
  180. const result = this.customCompletionFunction(current, argv);
  181. if (isPromise(result)) {
  182. return result
  183. .then(list => {
  184. this.shim.process.nextTick(() => {
  185. done(null, list);
  186. });
  187. })
  188. .catch(err => {
  189. this.shim.process.nextTick(() => {
  190. done(err, undefined);
  191. });
  192. });
  193. }
  194. return done(null, result);
  195. }
  196. else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
  197. return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => {
  198. done(null, completions);
  199. });
  200. }
  201. else {
  202. return this.customCompletionFunction(current, argv, completions => {
  203. done(null, completions);
  204. });
  205. }
  206. }
  207. getCompletion(args, done) {
  208. const current = args.length ? args[args.length - 1] : '';
  209. const argv = this.yargs.parse(args, true);
  210. const completionFunction = this.customCompletionFunction
  211. ? (argv) => this.customCompletion(args, argv, current, done)
  212. : (argv) => this.defaultCompletion(args, argv, current, done);
  213. return isPromise(argv)
  214. ? argv.then(completionFunction)
  215. : completionFunction(argv);
  216. }
  217. generateCompletionScript($0, cmd) {
  218. let script = this.zshShell
  219. ? templates.completionZshTemplate
  220. : templates.completionShTemplate;
  221. const name = this.shim.path.basename($0);
  222. if ($0.match(/\.js$/))
  223. $0 = `./${$0}`;
  224. script = script.replace(/{{app_name}}/g, name);
  225. script = script.replace(/{{completion_command}}/g, cmd);
  226. return script.replace(/{{app_path}}/g, $0);
  227. }
  228. registerFunction(fn) {
  229. this.customCompletionFunction = fn;
  230. }
  231. setParsed(parsed) {
  232. this.aliases = parsed.aliases;
  233. }
  234. }
  235. export function completion(yargs, usage, command, shim) {
  236. return new Completion(yargs, usage, command, shim);
  237. }
  238. function isSyncCompletionFunction(completionFunction) {
  239. return completionFunction.length < 3;
  240. }
  241. function isFallbackCompletionFunction(completionFunction) {
  242. return completionFunction.length > 3;
  243. }