index.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.run = run;
  6. Object.defineProperty(exports, "init", {
  7. enumerable: true,
  8. get: function () {
  9. return _initCompat.default;
  10. }
  11. });
  12. exports.bin = void 0;
  13. function _chalk() {
  14. const data = _interopRequireDefault(require("chalk"));
  15. _chalk = function () {
  16. return data;
  17. };
  18. return data;
  19. }
  20. function _child_process() {
  21. const data = _interopRequireDefault(require("child_process"));
  22. _child_process = function () {
  23. return data;
  24. };
  25. return data;
  26. }
  27. function _commander() {
  28. const data = _interopRequireDefault(require("commander"));
  29. _commander = function () {
  30. return data;
  31. };
  32. return data;
  33. }
  34. function _leven() {
  35. const data = _interopRequireDefault(require("leven"));
  36. _leven = function () {
  37. return data;
  38. };
  39. return data;
  40. }
  41. function _path() {
  42. const data = _interopRequireDefault(require("path"));
  43. _path = function () {
  44. return data;
  45. };
  46. return data;
  47. }
  48. function _cliTools() {
  49. const data = require("@react-native-community/cli-tools");
  50. _cliTools = function () {
  51. return data;
  52. };
  53. return data;
  54. }
  55. var _commands = require("./commands");
  56. var _initCompat = _interopRequireDefault(require("./commands/init/initCompat"));
  57. var _assertRequiredOptions = _interopRequireDefault(require("./tools/assertRequiredOptions"));
  58. var _config = _interopRequireDefault(require("./tools/config"));
  59. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  60. const pkgJson = require("../package.json");
  61. _commander().default.usage('<command> [options]').option('--version', 'Print CLI version').option('--verbose', 'Increase logging verbosity');
  62. _commander().default.arguments('<command>').action(cmd => {
  63. printUnknownCommand(cmd);
  64. process.exit(1);
  65. });
  66. const handleError = err => {
  67. if (_commander().default.verbose) {
  68. _cliTools().logger.error(err.message);
  69. } else {
  70. // Some error messages (esp. custom ones) might have `.` at the end already.
  71. const message = err.message.replace(/\.$/, '');
  72. _cliTools().logger.error(`${message}. ${_chalk().default.dim(`Run CLI with ${_chalk().default.reset('--verbose')} ${_chalk().default.dim('flag for more details.')}`)}`);
  73. }
  74. if (err.stack) {
  75. _cliTools().logger.log(_chalk().default.dim(err.stack));
  76. }
  77. process.exit(1);
  78. };
  79. /**
  80. * Custom printHelpInformation command inspired by internal Commander.js
  81. * one modified to suit our needs
  82. */
  83. function printHelpInformation(examples, pkg) {
  84. let cmdName = this._name;
  85. const argsList = this._args.map(arg => arg.required ? `<${arg.name}>` : `[${arg.name}]`).join(' ');
  86. if (this._alias) {
  87. cmdName = `${cmdName}|${this._alias}`;
  88. }
  89. const sourceInformation = pkg ? [`${_chalk().default.bold('Source:')} ${pkg.name}@${pkg.version}`, ''] : [];
  90. let output = [_chalk().default.bold(`react-native ${cmdName} ${argsList}`), this._description ? `\n${this._description}\n` : '', ...sourceInformation, `${_chalk().default.bold('Options:')}`, this.optionHelp().replace(/^/gm, ' ')];
  91. if (examples && examples.length > 0) {
  92. const formattedUsage = examples.map(example => ` ${example.desc}: \n ${_chalk().default.cyan(example.cmd)}`).join('\n\n');
  93. output = output.concat([_chalk().default.bold('\nExample usage:'), formattedUsage]);
  94. }
  95. return output.join('\n').concat('\n');
  96. }
  97. function printUnknownCommand(cmdName) {
  98. const availableCommands = _commander().default.commands.map(cmd => cmd._name);
  99. const suggestion = availableCommands.find(cmd => {
  100. return (0, _leven().default)(cmd, cmdName) < cmd.length * 0.4;
  101. });
  102. let errorMsg = `Unrecognized command "${_chalk().default.bold(cmdName)}".`;
  103. if (suggestion) {
  104. errorMsg += ` Did you mean "${suggestion}"?`;
  105. }
  106. if (cmdName) {
  107. _cliTools().logger.error(errorMsg);
  108. _cliTools().logger.info(`Run ${_chalk().default.bold('"react-native --help"')} to see a list of all available commands.`);
  109. } else {
  110. _commander().default.outputHelp();
  111. }
  112. }
  113. /**
  114. * Custom type assertion needed for the `makeCommand` conditional
  115. * types to be properly resolved.
  116. */
  117. const isDetachedCommand = command => {
  118. return command.detached === true;
  119. };
  120. /**
  121. * Attaches a new command onto global `commander` instance.
  122. *
  123. * Note that this function takes additional argument of `Config` type in case
  124. * passed `command` needs it for its execution.
  125. */
  126. function attachCommand(command, ...rest) {
  127. const options = command.options || [];
  128. const cmd = _commander().default.command(command.name).action(async function handleAction(...args) {
  129. const passedOptions = this.opts();
  130. const argv = Array.from(args).slice(0, -1);
  131. try {
  132. (0, _assertRequiredOptions.default)(options, passedOptions);
  133. if (isDetachedCommand(command)) {
  134. await command.func(argv, passedOptions);
  135. } else {
  136. await command.func(argv, rest[0], passedOptions);
  137. }
  138. } catch (error) {
  139. handleError(error);
  140. }
  141. });
  142. if (command.description) {
  143. cmd.description(command.description);
  144. }
  145. cmd.helpInformation = printHelpInformation.bind(cmd, command.examples, command.pkg);
  146. for (const opt of command.options || []) {
  147. cmd.option(opt.name, opt.description, opt.parse || (val => val), typeof opt.default === 'function' ? opt.default(rest[0]) : opt.default);
  148. }
  149. }
  150. async function run() {
  151. try {
  152. await setupAndRun();
  153. } catch (e) {
  154. handleError(e);
  155. }
  156. }
  157. async function setupAndRun() {
  158. // Commander is not available yet
  159. // when we run `config`, we don't want to output anything to the console. We
  160. // expect it to return valid JSON
  161. if (process.argv.includes('config')) {
  162. _cliTools().logger.disable();
  163. }
  164. _cliTools().logger.setVerbose(process.argv.includes('--verbose')); // We only have a setup script for UNIX envs currently
  165. if (process.platform !== 'win32') {
  166. const scriptName = 'setup_env.sh';
  167. const absolutePath = _path().default.join(__dirname, '..', scriptName);
  168. try {
  169. _child_process().default.execFileSync(absolutePath, {
  170. stdio: 'pipe'
  171. });
  172. } catch (error) {
  173. _cliTools().logger.warn(`Failed to run environment setup script "${scriptName}"\n\n${_chalk().default.red(error)}`);
  174. _cliTools().logger.info(`React Native CLI will continue to run if your local environment matches what React Native expects. If it does fail, check out "${absolutePath}" and adjust your environment to match it.`);
  175. }
  176. }
  177. for (const command of _commands.detachedCommands) {
  178. attachCommand(command);
  179. }
  180. try {
  181. const config = (0, _config.default)();
  182. _cliTools().logger.enable();
  183. for (const command of [..._commands.projectCommands, ...config.commands]) {
  184. attachCommand(command, config);
  185. }
  186. } catch (error) {
  187. /**
  188. * When there is no `package.json` found, the CLI will enter `detached` mode and a subset
  189. * of commands will be available. That's why we don't throw on such kind of error.
  190. */
  191. if (error.message.includes("We couldn't find a package.json")) {
  192. _cliTools().logger.enable();
  193. _cliTools().logger.debug(error.message);
  194. _cliTools().logger.debug('Failed to load configuration of your project. Only a subset of commands will be available.');
  195. } else {
  196. throw new (_cliTools().CLIError)('Failed to load configuration of your project.', error);
  197. }
  198. }
  199. _commander().default.parse(process.argv);
  200. if (_commander().default.rawArgs.length === 2) {
  201. _commander().default.outputHelp();
  202. } // We handle --version as a special case like this because both `commander`
  203. // and `yargs` append it to every command and we don't want to do that.
  204. // E.g. outside command `init` has --version flag and we want to preserve it.
  205. if (_commander().default.args.length === 0 && _commander().default.rawArgs.includes('--version')) {
  206. console.log(pkgJson.version);
  207. }
  208. }
  209. const bin = require.resolve("./bin");
  210. exports.bin = bin;
  211. //# sourceMappingURL=index.js.map