cli.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. /**
  3. * This is where we finally parse and handle arguments passed to the `mocha` executable.
  4. * Option parsing is handled by {@link https://npm.im/yargs yargs}.
  5. * If executed via `node`, this module will run {@linkcode module:lib/cli/cli.main main()}.
  6. *
  7. * @private
  8. * @module
  9. */
  10. const debug = require('debug')('mocha:cli:cli');
  11. const symbols = require('log-symbols');
  12. const yargs = require('yargs');
  13. const path = require('path');
  14. const {loadOptions} = require('./options');
  15. const commands = require('./commands');
  16. const ansi = require('ansi-colors');
  17. const {repository, homepage, version, gitter} = require('../../package.json');
  18. /**
  19. * - Accepts an `Array` of arguments
  20. * - Modifies {@link https://nodejs.org/api/modules.html#modules_module_paths Node.js' search path} for easy loading of consumer modules
  21. * - Sets {@linkcode https://nodejs.org/api/errors.html#errors_error_stacktracelimit Error.stackTraceLimit} to `Infinity`
  22. * @summary Mocha's main entry point from the command-line.
  23. * @param {string[]} argv - Array of arguments to parse, or by default the lovely `process.argv.slice(2)`
  24. */
  25. exports.main = (argv = process.argv.slice(2)) => {
  26. debug('entered main with raw args', argv);
  27. // ensure we can require() from current working directory
  28. module.paths.push(process.cwd(), path.resolve('node_modules'));
  29. Error.stackTraceLimit = Infinity; // configurable via --stack-trace-limit?
  30. yargs
  31. .scriptName('mocha')
  32. .command(commands.run)
  33. .command(commands.init)
  34. .updateStrings({
  35. 'Positionals:': 'Positional Arguments',
  36. 'Options:': 'Other Options',
  37. 'Commands:': 'Commands'
  38. })
  39. .fail((msg, err, yargs) => {
  40. debug(err);
  41. yargs.showHelp();
  42. console.error(`\n${symbols.error} ${ansi.red('ERROR:')} ${msg}`);
  43. process.exit(1);
  44. })
  45. .help('help', 'Show usage information & exit')
  46. .alias('help', 'h')
  47. .version('version', 'Show version number & exit', version)
  48. .alias('version', 'V')
  49. .wrap(process.stdout.columns ? Math.min(process.stdout.columns, 80) : 80)
  50. .epilog(
  51. `Mocha Resources
  52. Chat: ${ansi.magenta(gitter)}
  53. GitHub: ${ansi.blue(repository.url)}
  54. Docs: ${ansi.yellow(homepage)}
  55. `
  56. )
  57. .parse(argv, loadOptions(argv));
  58. };
  59. // allow direct execution
  60. if (require.main === module) {
  61. exports.main();
  62. }