UNPKG

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