completion.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. var _a, _b, _c;
  158. const descs = this.usage.getDescriptions();
  159. const startsByTwoDashes = (s) => /^--/.test(s);
  160. const isShortOption = (s) => /^[^0-9]$/.test(s);
  161. const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
  162. if (!this.zshShell) {
  163. completions.push(dashes + key);
  164. }
  165. else {
  166. const aliasKey = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key].find(alias => {
  167. const desc = descs[alias];
  168. return typeof desc === 'string' && desc.length > 0;
  169. });
  170. const descFromAlias = aliasKey ? descs[aliasKey] : undefined;
  171. const desc = (_c = (_b = descs[key]) !== null && _b !== void 0 ? _b : descFromAlias) !== null && _c !== void 0 ? _c : '';
  172. completions.push(dashes +
  173. `${key.replace(/:/g, '\\:')}:${desc
  174. .replace('__yargsString__:', '')
  175. .replace(/(\r\n|\n|\r)/gm, ' ')}`);
  176. }
  177. }
  178. customCompletion(args, argv, current, done) {
  179. assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
  180. if (isSyncCompletionFunction(this.customCompletionFunction)) {
  181. const result = this.customCompletionFunction(current, argv);
  182. if (isPromise(result)) {
  183. return result
  184. .then(list => {
  185. this.shim.process.nextTick(() => {
  186. done(null, list);
  187. });
  188. })
  189. .catch(err => {
  190. this.shim.process.nextTick(() => {
  191. done(err, undefined);
  192. });
  193. });
  194. }
  195. return done(null, result);
  196. }
  197. else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
  198. return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => {
  199. done(null, completions);
  200. });
  201. }
  202. else {
  203. return this.customCompletionFunction(current, argv, completions => {
  204. done(null, completions);
  205. });
  206. }
  207. }
  208. getCompletion(args, done) {
  209. const current = args.length ? args[args.length - 1] : '';
  210. const argv = this.yargs.parse(args, true);
  211. const completionFunction = this.customCompletionFunction
  212. ? (argv) => this.customCompletion(args, argv, current, done)
  213. : (argv) => this.defaultCompletion(args, argv, current, done);
  214. return isPromise(argv)
  215. ? argv.then(completionFunction)
  216. : completionFunction(argv);
  217. }
  218. generateCompletionScript($0, cmd) {
  219. let script = this.zshShell
  220. ? templates.completionZshTemplate
  221. : templates.completionShTemplate;
  222. const name = this.shim.path.basename($0);
  223. if ($0.match(/\.js$/))
  224. $0 = `./${$0}`;
  225. script = script.replace(/{{app_name}}/g, name);
  226. script = script.replace(/{{completion_command}}/g, cmd);
  227. return script.replace(/{{app_path}}/g, $0);
  228. }
  229. registerFunction(fn) {
  230. this.customCompletionFunction = fn;
  231. }
  232. setParsed(parsed) {
  233. this.aliases = parsed.aliases;
  234. }
  235. }
  236. export function completion(yargs, usage, command, shim) {
  237. return new Completion(yargs, usage, command, shim);
  238. }
  239. function isSyncCompletionFunction(completionFunction) {
  240. return completionFunction.length < 3;
  241. }
  242. function isFallbackCompletionFunction(completionFunction) {
  243. return completionFunction.length > 3;
  244. }