UNPKG

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