UNPKG

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