@teambit/cli 0.0.0-00805bd6ead01ffad26e598a8de15824e876ee5a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/.npmignore +18 -0
  2. package/cli-output-style-guide.md +132 -0
  3. package/cli.composition.tsx +7 -0
  4. package/cli.docs.mdx +12 -0
  5. package/dist/cli-output-style-guide.md +132 -0
  6. package/dist/cli-parser.d.ts +38 -0
  7. package/dist/cli-parser.js +388 -0
  8. package/dist/cli-parser.js.map +1 -0
  9. package/dist/cli-parser.spec.d.ts +1 -0
  10. package/dist/cli-parser.spec.js +113 -0
  11. package/dist/cli-parser.spec.js.map +1 -0
  12. package/dist/cli.aspect.d.ts +4 -0
  13. package/dist/cli.aspect.js +22 -0
  14. package/dist/cli.aspect.js.map +1 -0
  15. package/dist/cli.cmd.d.ts +34 -0
  16. package/dist/cli.cmd.js +163 -0
  17. package/dist/cli.cmd.js.map +1 -0
  18. package/dist/cli.composition.d.ts +2 -0
  19. package/dist/cli.composition.js +29 -0
  20. package/dist/cli.composition.js.map +1 -0
  21. package/dist/cli.docs.mdx +12 -0
  22. package/dist/cli.main.runtime.d.ts +86 -0
  23. package/dist/cli.main.runtime.js +270 -0
  24. package/dist/cli.main.runtime.js.map +1 -0
  25. package/dist/command-groups.d.ts +31 -0
  26. package/dist/command-groups.js +44 -0
  27. package/dist/command-groups.js.map +1 -0
  28. package/dist/command-helper.d.ts +25 -0
  29. package/dist/command-helper.js +59 -0
  30. package/dist/command-helper.js.map +1 -0
  31. package/dist/command-runner.d.ts +38 -0
  32. package/dist/command-runner.js +227 -0
  33. package/dist/command-runner.js.map +1 -0
  34. package/dist/command.d.ts +145 -0
  35. package/dist/command.js +3 -0
  36. package/dist/command.js.map +1 -0
  37. package/dist/completion.cmd.d.ts +9 -0
  38. package/dist/completion.cmd.js +22 -0
  39. package/dist/completion.cmd.js.map +1 -0
  40. package/dist/default-error-handler.d.ts +12 -0
  41. package/dist/default-error-handler.js +80 -0
  42. package/dist/default-error-handler.js.map +1 -0
  43. package/dist/details.cmd.d.ts +12 -0
  44. package/dist/details.cmd.js +78 -0
  45. package/dist/details.cmd.js.map +1 -0
  46. package/dist/esm.mjs +17 -0
  47. package/dist/exceptions/already-exists.d.ts +4 -0
  48. package/dist/exceptions/already-exists.js +21 -0
  49. package/dist/exceptions/already-exists.js.map +1 -0
  50. package/dist/exceptions/command-not-found.d.ts +7 -0
  51. package/dist/exceptions/command-not-found.js +44 -0
  52. package/dist/exceptions/command-not-found.js.map +1 -0
  53. package/dist/exceptions/index.d.ts +2 -0
  54. package/dist/exceptions/index.js +33 -0
  55. package/dist/exceptions/index.js.map +1 -0
  56. package/dist/exceptions/yargs-exit-workaround.d.ts +6 -0
  57. package/dist/exceptions/yargs-exit-workaround.js +23 -0
  58. package/dist/exceptions/yargs-exit-workaround.js.map +1 -0
  59. package/dist/generate-doc-md.d.ts +39 -0
  60. package/dist/generate-doc-md.js +266 -0
  61. package/dist/generate-doc-md.js.map +1 -0
  62. package/dist/get-command-id.d.ts +1 -0
  63. package/dist/get-command-id.js +11 -0
  64. package/dist/get-command-id.js.map +1 -0
  65. package/dist/global-flags.d.ts +7 -0
  66. package/dist/global-flags.js +24 -0
  67. package/dist/global-flags.js.map +1 -0
  68. package/dist/handle-errors.d.ts +3 -0
  69. package/dist/handle-errors.js +78 -0
  70. package/dist/handle-errors.js.map +1 -0
  71. package/dist/help.cmd.d.ts +16 -0
  72. package/dist/help.cmd.js +37 -0
  73. package/dist/help.cmd.js.map +1 -0
  74. package/dist/help.d.ts +3 -0
  75. package/dist/help.js +88 -0
  76. package/dist/help.js.map +1 -0
  77. package/dist/index.d.ts +14 -0
  78. package/dist/index.js +245 -0
  79. package/dist/index.js.map +1 -0
  80. package/dist/output-formatter.d.ts +40 -0
  81. package/dist/output-formatter.js +115 -0
  82. package/dist/output-formatter.js.map +1 -0
  83. package/dist/pager.d.ts +35 -0
  84. package/dist/pager.js +178 -0
  85. package/dist/pager.js.map +1 -0
  86. package/dist/preview-1787076242549.js +7 -0
  87. package/dist/version.cmd.d.ts +13 -0
  88. package/dist/version.cmd.js +39 -0
  89. package/dist/version.cmd.js.map +1 -0
  90. package/dist/yargs-adapter.d.ts +22 -0
  91. package/dist/yargs-adapter.js +133 -0
  92. package/dist/yargs-adapter.js.map +1 -0
  93. package/esm.mjs +17 -0
  94. package/exceptions/already-exists.ts +7 -0
  95. package/exceptions/command-not-found.ts +22 -0
  96. package/exceptions/index.ts +2 -0
  97. package/exceptions/yargs-exit-workaround.ts +10 -0
  98. package/package.json +74 -0
  99. package/types/asset.d.ts +41 -0
  100. package/types/style.d.ts +46 -0
@@ -0,0 +1,388 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.CLIParser = void 0;
7
+ exports.findCommandByArgv = findCommandByArgv;
8
+ function _didyoumean() {
9
+ const data = _interopRequireDefault(require("didyoumean"));
10
+ _didyoumean = function () {
11
+ return data;
12
+ };
13
+ return data;
14
+ }
15
+ function _yargs() {
16
+ const data = _interopRequireDefault(require("yargs"));
17
+ _yargs = function () {
18
+ return data;
19
+ };
20
+ return data;
21
+ }
22
+ function _lodash() {
23
+ const data = require("lodash");
24
+ _lodash = function () {
25
+ return data;
26
+ };
27
+ return data;
28
+ }
29
+ function _legacy() {
30
+ const data = require("@teambit/legacy.consumer");
31
+ _legacy = function () {
32
+ return data;
33
+ };
34
+ return data;
35
+ }
36
+ function _legacy2() {
37
+ const data = require("@teambit/legacy.logger");
38
+ _legacy2 = function () {
39
+ return data;
40
+ };
41
+ return data;
42
+ }
43
+ function _legacy3() {
44
+ const data = require("@teambit/legacy.loader");
45
+ _legacy3 = function () {
46
+ return data;
47
+ };
48
+ return data;
49
+ }
50
+ function _chalk() {
51
+ const data = _interopRequireDefault(require("chalk"));
52
+ _chalk = function () {
53
+ return data;
54
+ };
55
+ return data;
56
+ }
57
+ function _getCommandId() {
58
+ const data = require("./get-command-id");
59
+ _getCommandId = function () {
60
+ return data;
61
+ };
62
+ return data;
63
+ }
64
+ function _help() {
65
+ const data = require("./help");
66
+ _help = function () {
67
+ return data;
68
+ };
69
+ return data;
70
+ }
71
+ function _yargsAdapter() {
72
+ const data = require("./yargs-adapter");
73
+ _yargsAdapter = function () {
74
+ return data;
75
+ };
76
+ return data;
77
+ }
78
+ function _commandNotFound() {
79
+ const data = require("./exceptions/command-not-found");
80
+ _commandNotFound = function () {
81
+ return data;
82
+ };
83
+ return data;
84
+ }
85
+ function _yargsExitWorkaround() {
86
+ const data = require("./exceptions/yargs-exit-workaround");
87
+ _yargsExitWorkaround = function () {
88
+ return data;
89
+ };
90
+ return data;
91
+ }
92
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
93
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
94
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
95
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
96
+ class CLIParser {
97
+ constructor(commands, groups, onCommandStartSlot) {
98
+ this.commands = commands;
99
+ this.groups = groups;
100
+ this.onCommandStartSlot = onCommandStartSlot;
101
+ _defineProperty(this, "parser", _yargs().default);
102
+ _defineProperty(this, "yargsCommands", []);
103
+ }
104
+ async parse(args = process.argv.slice(2)) {
105
+ this.throwForNonExistsCommand(args[0]);
106
+ _legacy2().logger.debug(`[+] CLI-INPUT: ${args.join(' ')}`);
107
+ _legacy2().logger.writeCommandHistoryStart();
108
+ (0, _yargs().default)(args);
109
+ _yargs().default.help(false);
110
+ this.configureParser();
111
+ this.commands.forEach(command => {
112
+ if (command.commands && command.commands.length) {
113
+ this.parseCommandWithSubCommands(command);
114
+ } else {
115
+ const yargsCommand = this.getYargsCommand(command);
116
+ this.addYargsCommand(yargsCommand);
117
+ }
118
+ });
119
+ this.configureGlobalFlags();
120
+ this.setHelpMiddleware();
121
+ this.handleCommandFailure();
122
+ this.configureCompletion();
123
+ // yargs.showHelpOnFail(false); // doesn't help. it still shows the help on failure.
124
+ _yargs().default.strict(); // don't allow non-exist flags and non-exist commands
125
+
126
+ _yargs().default
127
+ // .recommendCommands() // don't use it, it brings the global help of yargs, we have a custom one
128
+ .wrap(null);
129
+ await _yargs().default.parse();
130
+ const currentYargsCommand = this.yargsCommands.find(y => y.commandRunner);
131
+ if (!currentYargsCommand) {
132
+ // this happens when the args/flags are wrong. in this case, it prints the help of the command and in most cases
133
+ // exits the process before reaching this line. however, in case logger.isDaemon is true, which is for bit-cli-server,
134
+ // it doesn't exits the process, so we need to return undefined here.
135
+ throw new Error(`yargs failed to parse the command "${args.join(' ')}" and also failed to catch it properly`);
136
+ }
137
+ return currentYargsCommand.commandRunner;
138
+ }
139
+ addYargsCommand(yargsCommand) {
140
+ this.yargsCommands.push(yargsCommand);
141
+ _yargs().default.command(yargsCommand);
142
+ }
143
+ setHelpMiddleware() {
144
+ _yargs().default.middleware(argv => {
145
+ if (argv._.length === 0 && argv.help) {
146
+ const shouldShowInternalCommands = Boolean(argv.internal);
147
+ // this is the main help page
148
+ this.printHelp(shouldShowInternalCommands);
149
+ process.exit(0);
150
+ }
151
+ if (argv.help) {
152
+ _legacy3().loader.off(); // stop the "loading bit..." before showing help if needed
153
+ // this is a command help page
154
+ _yargs().default.showHelp(this.logCommandHelp.bind(this));
155
+ process.exit(0);
156
+ }
157
+ }, true);
158
+ }
159
+ handleCommandFailure() {
160
+ _yargs().default.fail((msg, err) => {
161
+ _legacy3().loader.stop();
162
+ if (err) {
163
+ throw err;
164
+ }
165
+ const args = process.argv.slice(2);
166
+ const isHelpFlagEntered = args.includes('--help') || args.includes('-h');
167
+ let msgForDaemon = '';
168
+ try {
169
+ _yargs().default.showHelp(this.logCommandHelp.bind(this));
170
+ } catch (error) {
171
+ if (error instanceof _yargsExitWorkaround().YargsExitWorkaround) {
172
+ msgForDaemon = error.helpMsg;
173
+ } else {
174
+ throw error;
175
+ }
176
+ }
177
+ const isMsgAboutMissingArgs = msg.startsWith('Not enough non-option arguments');
178
+ // avoid showing the "Not enough non-option arguments" message when the user is trying to get the command help
179
+ if (!isMsgAboutMissingArgs || !isHelpFlagEntered) {
180
+ // eslint-disable-next-line no-console
181
+ console.log(`\n${_chalk().default.yellow(msg)}`);
182
+ msgForDaemon += `\n${_chalk().default.yellow(msg)}`;
183
+ }
184
+ if (_legacy2().logger.isDaemon) throw new (_yargsExitWorkaround().YargsExitWorkaround)(1, msgForDaemon);
185
+ process.exit(1);
186
+ });
187
+ }
188
+ configureCompletion() {
189
+ const commandsToShowComponentIdsForCompletion = ['show', 'diff', 'tag', 'export', 'env', 'envs', 'compile', 'build', 'test', 'lint', 'log', 'dependents', 'dependencies'];
190
+ // @ts-ignore
191
+ _yargs().default.completion('completion', async function (current, argv, completionFilter, done) {
192
+ if (!current.startsWith('-') && commandsToShowComponentIdsForCompletion.includes(argv._[1])) {
193
+ const consumer = await (0, _legacy().loadConsumerIfExist)();
194
+ done(consumer?.bitmapIdsFromCurrentLane.map(id => id.toStringWithoutVersion()));
195
+ } else {
196
+ completionFilter();
197
+ }
198
+ });
199
+ }
200
+ printHelp(shouldShowInternalCommands = false) {
201
+ const help = (0, _help().formatHelp)(this.commands, this.groups, shouldShowInternalCommands);
202
+ if (_legacy2().logger.isDaemon) throw new (_yargsExitWorkaround().YargsExitWorkaround)(0, help);else console.log(help); // eslint-disable-line no-console
203
+ }
204
+ configureParser() {
205
+ _yargs().default.parserConfiguration({
206
+ // 'strip-dashed': true, // we can't enable it, otherwise, the completion doesn't work
207
+ 'strip-aliased': true,
208
+ 'boolean-negation': false,
209
+ 'populate--': true
210
+ });
211
+ }
212
+ parseCommandWithSubCommands(command) {
213
+ const yarnCommand = this.getYargsCommand(command);
214
+ // registering the sub-commands has to happen from a builder, which replaces the adapter's own
215
+ // builder. that one registers this command's flags, positionals and examples, so without
216
+ // delegating to it, running the parent with any of its own flags fails as an unknown argument.
217
+ const registerOwnOptions = yarnCommand.builder;
218
+ const builderFunc = yargsInstance => {
219
+ command.commands?.forEach(cmd => {
220
+ const subCommand = this.getYargsCommand(cmd);
221
+ this.addYargsCommand(subCommand);
222
+ });
223
+ return registerOwnOptions(yargsInstance);
224
+ };
225
+ yarnCommand.builder = builderFunc;
226
+ this.addYargsCommand(yarnCommand);
227
+ }
228
+ getYargsCommand(command) {
229
+ const yargsCommand = new (_yargsAdapter().YargsAdapter)(command, this.onCommandStartSlot);
230
+ yargsCommand.builder = yargsCommand.builder.bind(yargsCommand);
231
+ yargsCommand.handler = yargsCommand.handler.bind(yargsCommand);
232
+ return yargsCommand;
233
+ }
234
+ configureGlobalFlags() {
235
+ _yargs().default.option('help', {
236
+ alias: 'h',
237
+ describe: 'show help',
238
+ group: _yargsAdapter().GLOBAL_GROUP
239
+ }).option('version', {
240
+ global: false,
241
+ alias: 'v',
242
+ describe: 'show version',
243
+ group: _yargsAdapter().GLOBAL_GROUP
244
+ });
245
+ }
246
+ throwForNonExistsCommand(commandName) {
247
+ if (!commandName || commandName.startsWith('-')) {
248
+ return;
249
+ }
250
+ const commandsNames = this.commands.map(c => (0, _getCommandId().getCommandId)(c.name));
251
+ const aliases = this.commands.map(c => c.alias).filter(a => a);
252
+ const existingGlobalFlags = ['-V', '--version'];
253
+ const validCommands = [...commandsNames, ...aliases, ...existingGlobalFlags];
254
+ const commandExist = validCommands.includes(commandName);
255
+ if (!commandExist) {
256
+ _didyoumean().default.returnFirstMatch = true;
257
+ const suggestions = (0, _didyoumean().default)(commandName, this.commands.filter(c => !c.private).map(c => (0, _getCommandId().getCommandId)(c.name)));
258
+ const suggestion = suggestions && Array.isArray(suggestions) ? suggestions[0] : suggestions;
259
+ throw new (_commandNotFound().CommandNotFound)(commandName, suggestion);
260
+ }
261
+ }
262
+
263
+ /**
264
+ * manipulate the command help output. there is no API from Yarn to do any of this, so it needs to be done manually.
265
+ * see https://github.com/yargs/yargs/issues/1956
266
+ *
267
+ * the original order of the output:
268
+ * description
269
+ * Options
270
+ * Commands
271
+ * Global
272
+ * Positionals
273
+ * Examples
274
+ */
275
+ logCommandHelp(help) {
276
+ const command = findCommandByArgv(this.commands);
277
+ const lines = help.split('\n');
278
+ const linesWithoutEmpty = (0, _lodash().compact)(lines);
279
+ let cmdLine = linesWithoutEmpty[0];
280
+ if (command?.alias) {
281
+ const enteredCommand = process.argv[2];
282
+ if (enteredCommand === command.alias) {
283
+ const commandId = (0, _getCommandId().getCommandId)(command.name);
284
+ cmdLine = cmdLine.replace(commandId, command.alias);
285
+ }
286
+ }
287
+ const description = [];
288
+ const options = [];
289
+ const globalOptions = [];
290
+ const subCommands = [];
291
+ const args = [];
292
+ const examples = [];
293
+ let optionsStarted = false;
294
+ let globalStarted = false;
295
+ let subCommandsStarted = false;
296
+ let positionalsStarted = false;
297
+ let examplesStarted = false;
298
+ for (let i = 1; i < linesWithoutEmpty.length; i += 1) {
299
+ const currentLine = linesWithoutEmpty[i];
300
+ if (currentLine === _yargsAdapter().STANDARD_GROUP) {
301
+ optionsStarted = true;
302
+ } else if (currentLine === _yargsAdapter().GLOBAL_GROUP) {
303
+ globalStarted = true;
304
+ } else if (currentLine === 'Commands:') {
305
+ subCommandsStarted = true;
306
+ } else if (currentLine === 'Positionals:') {
307
+ positionalsStarted = true;
308
+ } else if (currentLine === 'Examples:') {
309
+ examplesStarted = true;
310
+ } else if (examplesStarted) {
311
+ examples.push(currentLine);
312
+ } else if (positionalsStarted) {
313
+ args.push(currentLine);
314
+ } else if (globalStarted) {
315
+ globalOptions.push(currentLine);
316
+ } else if (optionsStarted) {
317
+ options.push(currentLine);
318
+ } else if (subCommandsStarted) {
319
+ subCommands.push(currentLine);
320
+ } else {
321
+ description.push(currentLine);
322
+ }
323
+ }
324
+
325
+ // show the flags in green
326
+ const optionsColored = options.map(optLine => {
327
+ const match = optLine.match(/^(\s*)(.+?)(\s{2,}.*)/);
328
+ if (match) {
329
+ const leadingSpaces = match[1];
330
+ const optionPart = match[2];
331
+ const rest = match[3];
332
+ const coloredOptionPart = optionPart.replace(/(^|[^a-zA-Z0-9])(--?[a-zA-Z][a-zA-Z-]*)/g, (m, p1, p2) => p1 + _chalk().default.green(p2));
333
+ return leadingSpaces + coloredOptionPart + rest;
334
+ } else {
335
+ return optLine;
336
+ }
337
+ });
338
+ const argsColored = args.map(arg => arg.replace(/^ {2}\S+/, argName => _chalk().default.green(argName))); // regex: two spaces then the first word until a white space
339
+ const optionsStr = options.length ? `\n${_yargsAdapter().STANDARD_GROUP}\n${optionsColored.join('\n')}\n` : '';
340
+ const argumentsStr = args.length ? `\nArguments:\n${argsColored.join('\n')}\n` : '';
341
+ const examplesStr = examples.length ? `\nExamples:\n${examples.join('\n')}\n` : '';
342
+ const subCommandsStr = subCommands.length ? `\n${'Commands:'}\n${subCommands.join('\n')}\n` : '';
343
+ // show the description in bold
344
+ const descriptionColored = description.map(desc => _chalk().default.bold(desc));
345
+ if (command?.extendedDescription) {
346
+ descriptionColored.push(command?.extendedDescription);
347
+ }
348
+ if (command?.helpUrl) {
349
+ descriptionColored.push(`for more info, visit: ${_chalk().default.underline(command.helpUrl)}`);
350
+ }
351
+ const descriptionStr = descriptionColored.join('\n');
352
+ const globalOptionsStr = globalOptions.join('\n');
353
+ const finalOutput = `${cmdLine}
354
+
355
+ ${descriptionStr}
356
+ ${argumentsStr}${subCommandsStr}${optionsStr}${examplesStr}
357
+ ${_yargsAdapter().GLOBAL_GROUP}
358
+ ${globalOptionsStr}`;
359
+ if (_legacy2().logger.isDaemon) throw new (_yargsExitWorkaround().YargsExitWorkaround)(0, finalOutput);else console.log(finalOutput); // eslint-disable-line no-console
360
+ }
361
+ }
362
+ exports.CLIParser = CLIParser;
363
+ function findCommandByArgv(commands) {
364
+ const args = process.argv.slice(2);
365
+ const enteredCommand = args[0];
366
+ const enteredSubCommand = args[1];
367
+ if (!enteredCommand) {
368
+ return undefined;
369
+ }
370
+ const isCommandMatch = (cmd, str) => {
371
+ return cmd.name.startsWith(`${str} `) ||
372
+ // e.g. "tag <id>".startsWith("tag ")
373
+ cmd.name === str ||
374
+ // e.g. "globals" === "globals"
375
+ cmd.alias === str; // e.g. "t" === "t"
376
+ };
377
+ const command = commands.find(cmd => isCommandMatch(cmd, enteredCommand));
378
+ if (!command) {
379
+ return undefined;
380
+ }
381
+ if (!command.commands || !enteredSubCommand) {
382
+ return command; // no sub-commands.
383
+ }
384
+ const subCommand = command.commands.find(cmd => isCommandMatch(cmd, enteredSubCommand));
385
+ return subCommand || command;
386
+ }
387
+
388
+ //# sourceMappingURL=cli-parser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["_didyoumean","data","_interopRequireDefault","require","_yargs","_lodash","_legacy","_legacy2","_legacy3","_chalk","_getCommandId","_help","_yargsAdapter","_commandNotFound","_yargsExitWorkaround","e","__esModule","default","_defineProperty","r","t","_toPropertyKey","Object","defineProperty","value","enumerable","configurable","writable","i","_toPrimitive","Symbol","toPrimitive","call","TypeError","String","Number","CLIParser","constructor","commands","groups","onCommandStartSlot","yargs","parse","args","process","argv","slice","throwForNonExistsCommand","logger","debug","join","writeCommandHistoryStart","help","configureParser","forEach","command","length","parseCommandWithSubCommands","yargsCommand","getYargsCommand","addYargsCommand","configureGlobalFlags","setHelpMiddleware","handleCommandFailure","configureCompletion","strict","wrap","currentYargsCommand","yargsCommands","find","y","commandRunner","Error","push","middleware","_","shouldShowInternalCommands","Boolean","internal","printHelp","exit","loader","off","showHelp","logCommandHelp","bind","fail","msg","err","stop","isHelpFlagEntered","includes","msgForDaemon","error","YargsExitWorkaround","helpMsg","isMsgAboutMissingArgs","startsWith","console","log","chalk","yellow","isDaemon","commandsToShowComponentIdsForCompletion","completion","current","completionFilter","done","consumer","loadConsumerIfExist","bitmapIdsFromCurrentLane","map","id","toStringWithoutVersion","formatHelp","parserConfiguration","yarnCommand","registerOwnOptions","builder","builderFunc","yargsInstance","cmd","subCommand","YargsAdapter","handler","option","alias","describe","group","GLOBAL_GROUP","global","commandName","commandsNames","c","getCommandId","name","aliases","filter","a","existingGlobalFlags","validCommands","commandExist","didYouMean","returnFirstMatch","suggestions","private","suggestion","Array","isArray","CommandNotFound","findCommandByArgv","lines","split","linesWithoutEmpty","compact","cmdLine","enteredCommand","commandId","replace","description","options","globalOptions","subCommands","examples","optionsStarted","globalStarted","subCommandsStarted","positionalsStarted","examplesStarted","currentLine","STANDARD_GROUP","optionsColored","optLine","match","leadingSpaces","optionPart","rest","coloredOptionPart","m","p1","p2","green","argsColored","arg","argName","optionsStr","argumentsStr","examplesStr","subCommandsStr","descriptionColored","desc","bold","extendedDescription","helpUrl","underline","descriptionStr","globalOptionsStr","finalOutput","exports","enteredSubCommand","undefined","isCommandMatch","str"],"sources":["cli-parser.ts"],"sourcesContent":["import didYouMean from 'didyoumean';\nimport yargs from 'yargs';\nimport type { Command } from './command';\nimport type { GroupsType } from './command-groups';\nimport { compact } from 'lodash';\nimport { loadConsumerIfExist } from '@teambit/legacy.consumer';\nimport { logger } from '@teambit/legacy.logger';\nimport { loader } from '@teambit/legacy.loader';\nimport chalk from 'chalk';\nimport { getCommandId } from './get-command-id';\nimport { formatHelp } from './help';\nimport { GLOBAL_GROUP, STANDARD_GROUP, YargsAdapter } from './yargs-adapter';\nimport { CommandNotFound } from './exceptions/command-not-found';\nimport type { OnCommandStartSlot } from './cli.main.runtime';\nimport type { CommandRunner } from './command-runner';\nimport { YargsExitWorkaround } from './exceptions/yargs-exit-workaround';\n\nexport class CLIParser {\n public parser = yargs;\n private yargsCommands: YargsAdapter[] = [];\n constructor(\n private commands: Command[],\n private groups: GroupsType,\n private onCommandStartSlot: OnCommandStartSlot\n ) {}\n\n async parse(args = process.argv.slice(2)): Promise<CommandRunner> {\n this.throwForNonExistsCommand(args[0]);\n logger.debug(`[+] CLI-INPUT: ${args.join(' ')}`);\n logger.writeCommandHistoryStart();\n yargs(args);\n yargs.help(false);\n this.configureParser();\n this.commands.forEach((command: Command) => {\n if (command.commands && command.commands.length) {\n this.parseCommandWithSubCommands(command);\n } else {\n const yargsCommand = this.getYargsCommand(command);\n this.addYargsCommand(yargsCommand);\n }\n });\n this.configureGlobalFlags();\n this.setHelpMiddleware();\n this.handleCommandFailure();\n this.configureCompletion();\n // yargs.showHelpOnFail(false); // doesn't help. it still shows the help on failure.\n yargs.strict(); // don't allow non-exist flags and non-exist commands\n\n yargs\n // .recommendCommands() // don't use it, it brings the global help of yargs, we have a custom one\n .wrap(null);\n\n await yargs.parse();\n\n const currentYargsCommand = this.yargsCommands.find((y) => y.commandRunner);\n if (!currentYargsCommand) {\n // this happens when the args/flags are wrong. in this case, it prints the help of the command and in most cases\n // exits the process before reaching this line. however, in case logger.isDaemon is true, which is for bit-cli-server,\n // it doesn't exits the process, so we need to return undefined here.\n throw new Error(`yargs failed to parse the command \"${args.join(' ')}\" and also failed to catch it properly`);\n }\n return currentYargsCommand.commandRunner as CommandRunner;\n }\n\n private addYargsCommand(yargsCommand: YargsAdapter) {\n this.yargsCommands.push(yargsCommand);\n yargs.command(yargsCommand);\n }\n\n private setHelpMiddleware() {\n yargs.middleware((argv) => {\n if (argv._.length === 0 && argv.help) {\n const shouldShowInternalCommands = Boolean(argv.internal);\n // this is the main help page\n this.printHelp(shouldShowInternalCommands);\n process.exit(0);\n }\n if (argv.help) {\n loader.off(); // stop the \"loading bit...\" before showing help if needed\n // this is a command help page\n yargs.showHelp(this.logCommandHelp.bind(this));\n process.exit(0);\n }\n }, true);\n }\n\n private handleCommandFailure() {\n yargs.fail((msg, err) => {\n loader.stop();\n if (err) {\n throw err;\n }\n const args = process.argv.slice(2);\n const isHelpFlagEntered = args.includes('--help') || args.includes('-h');\n let msgForDaemon = '';\n try {\n yargs.showHelp(this.logCommandHelp.bind(this));\n } catch (error: any) {\n if (error instanceof YargsExitWorkaround) {\n msgForDaemon = error.helpMsg;\n } else {\n throw error;\n }\n }\n const isMsgAboutMissingArgs = msg.startsWith('Not enough non-option arguments');\n // avoid showing the \"Not enough non-option arguments\" message when the user is trying to get the command help\n if (!isMsgAboutMissingArgs || !isHelpFlagEntered) {\n // eslint-disable-next-line no-console\n console.log(`\\n${chalk.yellow(msg)}`);\n msgForDaemon += `\\n${chalk.yellow(msg)}`;\n }\n if (logger.isDaemon) throw new YargsExitWorkaround(1, msgForDaemon);\n process.exit(1);\n });\n }\n\n private configureCompletion() {\n const commandsToShowComponentIdsForCompletion = [\n 'show',\n 'diff',\n 'tag',\n 'export',\n 'env',\n 'envs',\n 'compile',\n 'build',\n 'test',\n 'lint',\n 'log',\n 'dependents',\n 'dependencies',\n ];\n // @ts-ignore\n yargs.completion('completion', async function (current, argv, completionFilter, done) {\n if (!current.startsWith('-') && commandsToShowComponentIdsForCompletion.includes(argv._[1])) {\n const consumer = await loadConsumerIfExist();\n done(consumer?.bitmapIdsFromCurrentLane.map((id) => id.toStringWithoutVersion()));\n } else {\n completionFilter();\n }\n });\n }\n\n private printHelp(shouldShowInternalCommands = false) {\n const help = formatHelp(this.commands, this.groups, shouldShowInternalCommands);\n if (logger.isDaemon) throw new YargsExitWorkaround(0, help);\n else console.log(help); // eslint-disable-line no-console\n }\n\n private configureParser() {\n yargs.parserConfiguration({\n // 'strip-dashed': true, // we can't enable it, otherwise, the completion doesn't work\n 'strip-aliased': true,\n 'boolean-negation': false,\n 'populate--': true,\n });\n }\n\n private parseCommandWithSubCommands(command: Command) {\n const yarnCommand = this.getYargsCommand(command);\n // registering the sub-commands has to happen from a builder, which replaces the adapter's own\n // builder. that one registers this command's flags, positionals and examples, so without\n // delegating to it, running the parent with any of its own flags fails as an unknown argument.\n const registerOwnOptions = yarnCommand.builder as (yargsInstance: typeof yargs) => typeof yargs;\n const builderFunc = (yargsInstance: typeof yargs) => {\n command.commands?.forEach((cmd) => {\n const subCommand = this.getYargsCommand(cmd);\n this.addYargsCommand(subCommand);\n });\n return registerOwnOptions(yargsInstance);\n };\n yarnCommand.builder = builderFunc;\n this.addYargsCommand(yarnCommand);\n }\n\n private getYargsCommand(command: Command): YargsAdapter {\n const yargsCommand = new YargsAdapter(command, this.onCommandStartSlot);\n yargsCommand.builder = yargsCommand.builder.bind(yargsCommand);\n yargsCommand.handler = yargsCommand.handler.bind(yargsCommand);\n\n return yargsCommand;\n }\n\n private configureGlobalFlags() {\n yargs\n .option('help', {\n alias: 'h',\n describe: 'show help',\n group: GLOBAL_GROUP,\n })\n .option('version', {\n global: false,\n alias: 'v',\n describe: 'show version',\n group: GLOBAL_GROUP,\n });\n }\n\n private throwForNonExistsCommand(commandName: string) {\n if (!commandName || commandName.startsWith('-')) {\n return;\n }\n const commandsNames = this.commands.map((c) => getCommandId(c.name));\n const aliases = this.commands.map((c) => c.alias).filter((a) => a);\n const existingGlobalFlags = ['-V', '--version'];\n const validCommands = [...commandsNames, ...aliases, ...existingGlobalFlags];\n const commandExist = validCommands.includes(commandName);\n\n if (!commandExist) {\n didYouMean.returnFirstMatch = true;\n const suggestions = didYouMean(\n commandName,\n this.commands.filter((c) => !c.private).map((c) => getCommandId(c.name))\n );\n const suggestion = suggestions && Array.isArray(suggestions) ? suggestions[0] : suggestions;\n\n throw new CommandNotFound(commandName, suggestion as string);\n }\n }\n\n /**\n * manipulate the command help output. there is no API from Yarn to do any of this, so it needs to be done manually.\n * see https://github.com/yargs/yargs/issues/1956\n *\n * the original order of the output:\n * description\n * Options\n * Commands\n * Global\n * Positionals\n * Examples\n */\n private logCommandHelp(help: string) {\n const command = findCommandByArgv(this.commands);\n\n const lines = help.split('\\n');\n const linesWithoutEmpty = compact(lines);\n let cmdLine = linesWithoutEmpty[0];\n if (command?.alias) {\n const enteredCommand = process.argv[2];\n if (enteredCommand === command.alias) {\n const commandId = getCommandId(command.name);\n cmdLine = cmdLine.replace(commandId, command.alias);\n }\n }\n const description: string[] = [];\n const options: string[] = [];\n const globalOptions: string[] = [];\n const subCommands: string[] = [];\n const args: string[] = [];\n const examples: string[] = [];\n\n let optionsStarted = false;\n let globalStarted = false;\n let subCommandsStarted = false;\n let positionalsStarted = false;\n let examplesStarted = false;\n for (let i = 1; i < linesWithoutEmpty.length; i += 1) {\n const currentLine = linesWithoutEmpty[i];\n if (currentLine === STANDARD_GROUP) {\n optionsStarted = true;\n } else if (currentLine === GLOBAL_GROUP) {\n globalStarted = true;\n } else if (currentLine === 'Commands:') {\n subCommandsStarted = true;\n } else if (currentLine === 'Positionals:') {\n positionalsStarted = true;\n } else if (currentLine === 'Examples:') {\n examplesStarted = true;\n } else if (examplesStarted) {\n examples.push(currentLine);\n } else if (positionalsStarted) {\n args.push(currentLine);\n } else if (globalStarted) {\n globalOptions.push(currentLine);\n } else if (optionsStarted) {\n options.push(currentLine);\n } else if (subCommandsStarted) {\n subCommands.push(currentLine);\n } else {\n description.push(currentLine);\n }\n }\n\n // show the flags in green\n const optionsColored = options.map((optLine) => {\n const match = optLine.match(/^(\\s*)(.+?)(\\s{2,}.*)/);\n if (match) {\n const leadingSpaces = match[1];\n const optionPart = match[2];\n const rest = match[3];\n const coloredOptionPart = optionPart.replace(\n /(^|[^a-zA-Z0-9])(--?[a-zA-Z][a-zA-Z-]*)/g,\n (m, p1, p2) => p1 + chalk.green(p2)\n );\n return leadingSpaces + coloredOptionPart + rest;\n } else {\n return optLine;\n }\n });\n const argsColored = args.map((arg) => arg.replace(/^ {2}\\S+/, (argName) => chalk.green(argName))); // regex: two spaces then the first word until a white space\n const optionsStr = options.length ? `\\n${STANDARD_GROUP}\\n${optionsColored.join('\\n')}\\n` : '';\n const argumentsStr = args.length ? `\\nArguments:\\n${argsColored.join('\\n')}\\n` : '';\n const examplesStr = examples.length ? `\\nExamples:\\n${examples.join('\\n')}\\n` : '';\n const subCommandsStr = subCommands.length ? `\\n${'Commands:'}\\n${subCommands.join('\\n')}\\n` : '';\n // show the description in bold\n const descriptionColored = description.map((desc) => chalk.bold(desc));\n if (command?.extendedDescription) {\n descriptionColored.push(command?.extendedDescription);\n }\n if (command?.helpUrl) {\n descriptionColored.push(`for more info, visit: ${chalk.underline(command.helpUrl)}`);\n }\n const descriptionStr = descriptionColored.join('\\n');\n const globalOptionsStr = globalOptions.join('\\n');\n\n const finalOutput = `${cmdLine}\n\n${descriptionStr}\n${argumentsStr}${subCommandsStr}${optionsStr}${examplesStr}\n${GLOBAL_GROUP}\n${globalOptionsStr}`;\n\n if (logger.isDaemon) throw new YargsExitWorkaround(0, finalOutput);\n else console.log(finalOutput); // eslint-disable-line no-console\n }\n}\n\nexport function findCommandByArgv(commands: Command[]): Command | undefined {\n const args = process.argv.slice(2);\n const enteredCommand = args[0];\n const enteredSubCommand = args[1];\n if (!enteredCommand) {\n return undefined;\n }\n const isCommandMatch = (cmd: Command, str: string) => {\n return (\n cmd.name.startsWith(`${str} `) || // e.g. \"tag <id>\".startsWith(\"tag \")\n cmd.name === str || // e.g. \"globals\" === \"globals\"\n cmd.alias === str\n ); // e.g. \"t\" === \"t\"\n };\n const command = commands.find((cmd) => isCommandMatch(cmd, enteredCommand));\n if (!command) {\n return undefined;\n }\n if (!command.commands || !enteredSubCommand) {\n return command; // no sub-commands.\n }\n const subCommand = command.commands.find((cmd) => isCommandMatch(cmd, enteredSubCommand));\n return subCommand || command;\n}\n"],"mappings":";;;;;;;AAAA,SAAAA,YAAA;EAAA,MAAAC,IAAA,GAAAC,sBAAA,CAAAC,OAAA;EAAAH,WAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,OAAA;EAAA,MAAAH,IAAA,GAAAC,sBAAA,CAAAC,OAAA;EAAAC,MAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAGA,SAAAI,QAAA;EAAA,MAAAJ,IAAA,GAAAE,OAAA;EAAAE,OAAA,YAAAA,CAAA;IAAA,OA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CAAC;EAC9B,MAAM4J,iBAAiB,GAAG5J,IAAI,CAAC,CAAC,CAAC;EACjC,IAAI,CAACiH,cAAc,EAAE;IACnB,OAAO4C,SAAS;EAClB;EACA,MAAMC,cAAc,GAAGA,CAAChF,GAAY,EAAEiF,GAAW,KAAK;IACpD,OACEjF,GAAG,CAACc,IAAI,CAACtC,UAAU,CAAC,GAAGyG,GAAG,GAAG,CAAC;IAAI;IAClCjF,GAAG,CAACc,IAAI,KAAKmE,GAAG;IAAI;IACpBjF,GAAG,CAACK,KAAK,KAAK4E,GAAG,CACjB,CAAC;EACL,CAAC;EACD,MAAMnJ,OAAO,GAAGjB,QAAQ,CAAC+B,IAAI,CAAEoD,GAAG,IAAKgF,cAAc,CAAChF,GAAG,EAAEmC,cAAc,CAAC,CAAC;EAC3E,IAAI,CAACrG,OAAO,EAAE;IACZ,OAAOiJ,SAAS;EAClB;EACA,IAAI,CAACjJ,OAAO,CAACjB,QAAQ,IAAI,CAACiK,iBAAiB,EAAE;IAC3C,OAAOhJ,OAAO,CAAC,CAAC;EAClB;EACA,MAAMmE,UAAU,GAAGnE,OAAO,CAACjB,QAAQ,CAAC+B,IAAI,CAAEoD,GAAG,IAAKgF,cAAc,CAAChF,GAAG,EAAE8E,iBAAiB,CAAC,CAAC;EACzF,OAAO7E,UAAU,IAAInE,OAAO;AAC9B","ignoreList":[]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+
3
+ function _chai() {
4
+ const data = require("chai");
5
+ _chai = function () {
6
+ return data;
7
+ };
8
+ return data;
9
+ }
10
+ function _legacy() {
11
+ const data = require("@teambit/legacy.logger");
12
+ _legacy = function () {
13
+ return data;
14
+ };
15
+ return data;
16
+ }
17
+ function _cliParser() {
18
+ const data = require("./cli-parser");
19
+ _cliParser = function () {
20
+ return data;
21
+ };
22
+ return data;
23
+ }
24
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
25
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
26
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
27
+ class SubCmd {
28
+ constructor() {
29
+ _defineProperty(this, "name", 'sub <arg>');
30
+ _defineProperty(this, "description", 'a sub command');
31
+ _defineProperty(this, "options", [['f', 'force', 'force it'],
32
+ // the parent declares "remote" as a flag that takes a value. this one is a boolean, so the
33
+ // parent's must not reach here, otherwise yargs demands a value that was never meant to exist.
34
+ ['r', 'remote', 'a boolean here, unlike the parent']]);
35
+ _defineProperty(this, "group", 'general');
36
+ }
37
+ async report() {
38
+ return '';
39
+ }
40
+ }
41
+ class ParentCmd {
42
+ constructor() {
43
+ _defineProperty(this, "name", 'parent [pattern]');
44
+ _defineProperty(this, "description", 'a command that also has sub commands');
45
+ _defineProperty(this, "options", [['j', 'json', 'return the output in json format'], ['d', 'details', 'show more details'], ['r', 'remote <scope-name>', 'a flag that takes a value']]);
46
+ _defineProperty(this, "group", 'general');
47
+ _defineProperty(this, "commands", [new SubCmd()]);
48
+ }
49
+ async report() {
50
+ return '';
51
+ }
52
+ }
53
+ function parse(args) {
54
+ const parser = new (_cliParser().CLIParser)([new ParentCmd()], {}, {
55
+ values: () => []
56
+ });
57
+ return parser.parse(args);
58
+ }
59
+ function flagsOf(runner) {
60
+ return runner.flags;
61
+ }
62
+ function argsOf(runner) {
63
+ return runner.args;
64
+ }
65
+ describe('CLIParser', () => {
66
+ let isDaemon;
67
+ before(() => {
68
+ // a parse failure exits the process unless the logger is in daemon mode, in which case it
69
+ // throws instead. without this, a regression here would kill the test run rather than fail it.
70
+ isDaemon = _legacy().logger.isDaemon;
71
+ _legacy().logger.isDaemon = true;
72
+ });
73
+ after(() => {
74
+ _legacy().logger.isDaemon = isDaemon;
75
+ });
76
+ describe('a command that has sub-commands', () => {
77
+ it('accepts the parent command own flags', async () => {
78
+ // registering sub-commands replaces the builder that declares the parent's own flags. when
79
+ // that is not accounted for, yargs strict mode rejects them as unknown arguments.
80
+ const runner = await parse(['parent', 'some-pattern', '--json']);
81
+ (0, _chai().expect)(flagsOf(runner).json).to.be.true;
82
+ (0, _chai().expect)(argsOf(runner)[0]).to.equal('some-pattern');
83
+ });
84
+ it('accepts the parent command own flags by their alias', async () => {
85
+ const runner = await parse(['parent', '-d']);
86
+ (0, _chai().expect)(flagsOf(runner).details).to.be.true;
87
+ });
88
+ it('still routes to a sub-command and accepts its flags', async () => {
89
+ const runner = await parse(['parent', 'sub', 'some-arg', '--force']);
90
+ (0, _chai().expect)(flagsOf(runner).force).to.be.true;
91
+ (0, _chai().expect)(argsOf(runner)[0]).to.equal('some-arg');
92
+ });
93
+ it('keeps the global flags available on the parent command', async () => {
94
+ const runner = await parse(['parent', '--log=error']);
95
+ (0, _chai().expect)(flagsOf(runner).log).to.equal('error');
96
+ });
97
+ it('accepts a value for a parent flag that takes one', async () => {
98
+ const runner = await parse(['parent', '--remote', 'my-scope']);
99
+ (0, _chai().expect)(flagsOf(runner).remote).to.equal('my-scope');
100
+ });
101
+ it('does not leak the parent flags into a sub-command that declares the same name', async () => {
102
+ // the parent's "remote" takes a value while the sub-command's is a boolean. if the parent's
103
+ // is registered globally it shadows the sub-command's, and yargs rejects the next token as a
104
+ // missing value: `Not enough arguments following: remote`.
105
+ const runner = await parse(['parent', 'sub', 'some-arg', '--remote', '--force']);
106
+ (0, _chai().expect)(flagsOf(runner).remote).to.be.true;
107
+ (0, _chai().expect)(flagsOf(runner).force).to.be.true;
108
+ (0, _chai().expect)(argsOf(runner)[0]).to.equal('some-arg');
109
+ });
110
+ });
111
+ });
112
+
113
+ //# sourceMappingURL=cli-parser.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["_chai","data","require","_legacy","_cliParser","_defineProperty","e","r","t","_toPropertyKey","Object","defineProperty","value","enumerable","configurable","writable","i","_toPrimitive","Symbol","toPrimitive","call","TypeError","String","Number","SubCmd","constructor","report","ParentCmd","parse","args","parser","CLIParser","values","flagsOf","runner","flags","argsOf","describe","isDaemon","before","logger","after","it","expect","json","to","be","true","equal","details","force","log","remote"],"sources":["cli-parser.spec.ts"],"sourcesContent":["import { expect } from 'chai';\nimport { logger } from '@teambit/legacy.logger';\nimport type { Command, CommandOptions } from './command';\nimport { CLIParser } from './cli-parser';\n\nclass SubCmd implements Command {\n name = 'sub <arg>';\n description = 'a sub command';\n options = [\n ['f', 'force', 'force it'],\n // the parent declares \"remote\" as a flag that takes a value. this one is a boolean, so the\n // parent's must not reach here, otherwise yargs demands a value that was never meant to exist.\n ['r', 'remote', 'a boolean here, unlike the parent'],\n ] as CommandOptions;\n group = 'general';\n async report() {\n return '';\n }\n}\n\nclass ParentCmd implements Command {\n name = 'parent [pattern]';\n description = 'a command that also has sub commands';\n options = [\n ['j', 'json', 'return the output in json format'],\n ['d', 'details', 'show more details'],\n ['r', 'remote <scope-name>', 'a flag that takes a value'],\n ] as CommandOptions;\n group = 'general';\n commands: Command[] = [new SubCmd()];\n async report() {\n return '';\n }\n}\n\nfunction parse(args: string[]) {\n const parser = new CLIParser([new ParentCmd()], {} as any, { values: () => [] } as any);\n return parser.parse(args);\n}\n\nfunction flagsOf(runner: any): Record<string, any> {\n return runner.flags;\n}\n\nfunction argsOf(runner: any): any[] {\n return runner.args;\n}\n\ndescribe('CLIParser', () => {\n let isDaemon: boolean;\n before(() => {\n // a parse failure exits the process unless the logger is in daemon mode, in which case it\n // throws instead. without this, a regression here would kill the test run rather than fail it.\n isDaemon = logger.isDaemon;\n logger.isDaemon = true;\n });\n after(() => {\n logger.isDaemon = isDaemon;\n });\n\n describe('a command that has sub-commands', () => {\n it('accepts the parent command own flags', async () => {\n // registering sub-commands replaces the builder that declares the parent's own flags. when\n // that is not accounted for, yargs strict mode rejects them as unknown arguments.\n const runner = await parse(['parent', 'some-pattern', '--json']);\n\n expect(flagsOf(runner).json).to.be.true;\n expect(argsOf(runner)[0]).to.equal('some-pattern');\n });\n\n it('accepts the parent command own flags by their alias', async () => {\n const runner = await parse(['parent', '-d']);\n\n expect(flagsOf(runner).details).to.be.true;\n });\n\n it('still routes to a sub-command and accepts its flags', async () => {\n const runner = await parse(['parent', 'sub', 'some-arg', '--force']);\n\n expect(flagsOf(runner).force).to.be.true;\n expect(argsOf(runner)[0]).to.equal('some-arg');\n });\n\n it('keeps the global flags available on the parent command', async () => {\n const runner = await parse(['parent', '--log=error']);\n\n expect(flagsOf(runner).log).to.equal('error');\n });\n\n it('accepts a value for a parent flag that takes one', async () => {\n const runner = await parse(['parent', '--remote', 'my-scope']);\n\n expect(flagsOf(runner).remote).to.equal('my-scope');\n });\n\n it('does not leak the parent flags into a sub-command that declares the same name', async () => {\n // the parent's \"remote\" takes a value while the sub-command's is a boolean. if the parent's\n // is registered globally it shadows the sub-command's, and yargs rejects the next token as a\n // missing value: `Not enough arguments following: remote`.\n const runner = await parse(['parent', 'sub', 'some-arg', '--remote', '--force']);\n\n expect(flagsOf(runner).remote).to.be.true;\n expect(flagsOf(runner).force).to.be.true;\n expect(argsOf(runner)[0]).to.equal('some-arg');\n });\n });\n});\n"],"mappings":";;AAAA,SAAAA,MAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,KAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,QAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,OAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,SAAAG,WAAA;EAAA,MAAAH,IAAA,GAAAC,OAAA;EAAAE,UAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;A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,CAAC;IAEFN,EAAE,CAAC,+EAA+E,EAAE,YAAY;MAC9F;MACA;MACA;MACA,MAAMR,MAAM,GAAG,MAAMN,KAAK,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;MAEhF,IAAAe,cAAM,EAACV,OAAO,CAACC,MAAM,CAAC,CAACkB,MAAM,CAAC,CAACP,EAAE,CAACC,EAAE,CAACC,IAAI;MACzC,IAAAJ,cAAM,EAACV,OAAO,CAACC,MAAM,CAAC,CAACgB,KAAK,CAAC,CAACL,EAAE,CAACC,EAAE,CAACC,IAAI;MACxC,IAAAJ,cAAM,EAACP,MAAM,CAACF,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAACW,EAAE,CAACG,KAAK,CAAC,UAAU,CAAC;IAChD,CAAC,CAAC;EACJ,CAAC,CAAC;AACJ,CAAC,CAAC","ignoreList":[]}
@@ -0,0 +1,4 @@
1
+ import { Aspect, RuntimeDefinition } from '@teambit/harmony';
2
+ export declare const MainRuntime: RuntimeDefinition;
3
+ export declare const CLIAspect: Aspect;
4
+ export default CLIAspect;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = exports.MainRuntime = exports.CLIAspect = void 0;
7
+ function _harmony() {
8
+ const data = require("@teambit/harmony");
9
+ _harmony = function () {
10
+ return data;
11
+ };
12
+ return data;
13
+ }
14
+ const MainRuntime = exports.MainRuntime = new (_harmony().RuntimeDefinition)('main');
15
+ const CLIAspect = exports.CLIAspect = _harmony().Aspect.create({
16
+ id: 'teambit.harmony/cli',
17
+ dependencies: [],
18
+ declareRuntime: MainRuntime
19
+ });
20
+ var _default = exports.default = CLIAspect;
21
+
22
+ //# sourceMappingURL=cli.aspect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["_harmony","data","require","MainRuntime","exports","RuntimeDefinition","CLIAspect","Aspect","create","id","dependencies","declareRuntime","_default","default"],"sources":["cli.aspect.ts"],"sourcesContent":["import { Aspect, RuntimeDefinition } from '@teambit/harmony';\n\nexport const MainRuntime = new RuntimeDefinition('main');\n\nexport const CLIAspect = Aspect.create({\n id: 'teambit.harmony/cli',\n dependencies: [],\n declareRuntime: MainRuntime,\n});\n\nexport default CLIAspect;\n"],"mappings":";;;;;;AAAA,SAAAA,SAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,QAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEO,MAAME,WAAW,GAAAC,OAAA,CAAAD,WAAA,GAAG,KAAIE,4BAAiB,EAAC,MAAM,CAAC;AAEjD,MAAMC,SAAS,GAAAF,OAAA,CAAAE,SAAA,GAAGC,iBAAM,CAACC,MAAM,CAAC;EACrCC,EAAE,EAAE,qBAAqB;EACzBC,YAAY,EAAE,EAAE;EAChBC,cAAc,EAAER;AAClB,CAAC,CAAC;AAAC,IAAAS,QAAA,GAAAR,OAAA,CAAAS,OAAA,GAEYP,SAAS","ignoreList":[]}
@@ -0,0 +1,34 @@
1
+ import type { Command, CommandOptions } from './command';
2
+ import type { CLIMain } from './cli.main.runtime';
3
+ import type { GenerateOpts } from './generate-doc-md';
4
+ export declare class CliGenerateCmd implements Command {
5
+ private cliMain;
6
+ name: string;
7
+ description: string;
8
+ alias: string;
9
+ loader: boolean;
10
+ group: string;
11
+ options: CommandOptions;
12
+ private: boolean;
13
+ constructor(cliMain: CLIMain);
14
+ report(args: any, { metadata, docs, skill }: GenerateOpts & {
15
+ docs?: boolean;
16
+ skill?: string;
17
+ }): Promise<string>;
18
+ json(): Promise<(Partial<Command> & {
19
+ commands?: any;
20
+ })[]>;
21
+ }
22
+ export declare class CliCmd implements Command {
23
+ private cliMain;
24
+ name: string;
25
+ description: string;
26
+ alias: string;
27
+ commands: Command[];
28
+ loader: boolean;
29
+ group: string;
30
+ options: CommandOptions;
31
+ private: boolean;
32
+ constructor(cliMain: CLIMain);
33
+ report(): Promise<string>;
34
+ }