-
Notifications
You must be signed in to change notification settings - Fork 682
Expand file tree
/
Copy pathrun.ts
More file actions
374 lines (308 loc) · 14.7 KB
/
run.ts
File metadata and controls
374 lines (308 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import { Footnote, MetadataGroup, validators } from '@ionic/cli-framework';
import { onBeforeExit, sleepForever } from '@ionic/utils-process';
import * as Debug from 'debug';
import * as lodash from 'lodash';
import { CommandInstanceInfo, CommandLineInputs, CommandLineOptions, CommandMetadata, CommandMetadataOption, CommandPreRun, IShellRunOptions, ServeDetails } from '../../definitions';
import { COMMON_BUILD_COMMAND_OPTIONS } from '../../lib/build';
import { input, strong, weak } from '../../lib/color';
import { FatalException, RunnerException } from '../../lib/errors';
import { getPackagePath, getPackagePathCordova } from '../../lib/integrations/cordova/project';
import { filterArgumentsForCordova, generateOptionsForCordovaBuild } from '../../lib/integrations/cordova/utils';
import { SUPPORTED_PLATFORMS, checkNativeRun, createNativeRunArgs, createNativeRunListArgs, getNativeTargets, runNativeRun } from '../../lib/native-run';
import { COMMON_SERVE_COMMAND_OPTIONS, LOCAL_ADDRESSES } from '../../lib/serve';
import { createPrefixedWriteStream } from '../../lib/utils/logger';
import { CORDOVA_BUILD_EXAMPLE_COMMANDS, CORDOVA_RUN_OPTIONS, CordovaCommand } from './base';
const debug = Debug('ionic:commands:run');
const NATIVE_RUN_OPTIONS: readonly CommandMetadataOption[] = [
{
name: 'native-run',
summary: `Do not use ${input('native-run')} to run the app; use Cordova instead`,
type: Boolean,
default: true,
groups: ['native-run'],
hint: weak('[native-run]'),
},
{
name: 'connect',
summary: 'Tie the running app to the process',
type: Boolean,
groups: ['native-run'],
hint: weak('[native-run] (--livereload)'),
},
{
name: 'json',
summary: `Output targets in JSON`,
type: Boolean,
groups: [MetadataGroup.ADVANCED, 'native-run'],
hint: weak('[native-run] (--list)'),
},
];
export class RunCommand extends CordovaCommand implements CommandPreRun {
async getMetadata(): Promise<CommandMetadata> {
const groups: string[] = [];
const exampleCommands = [
...CORDOVA_BUILD_EXAMPLE_COMMANDS,
'android -l',
'ios --livereload --external',
'ios --livereload-url=http://localhost:8100',
].sort();
let options: CommandMetadataOption[] = [
{
name: 'list',
summary: 'List all available targets',
type: Boolean,
groups: ['cordova', 'cordova-cli', 'native-run'],
},
// Build Options
{
name: 'build',
summary: 'Do not invoke Ionic build',
type: Boolean,
default: true,
},
...COMMON_BUILD_COMMAND_OPTIONS.filter(o => !['engine', 'platform'].includes(o.name)),
// Serve Options
...COMMON_SERVE_COMMAND_OPTIONS.filter(o => !['livereload'].includes(o.name)).map(o => ({ ...o, hint: weak('(--livereload)') })),
{
name: 'livereload',
summary: 'Spin up dev server to live-reload www files',
type: Boolean,
aliases: ['l'],
},
{
name: 'livereload-url',
summary: 'Provide a custom URL to the dev server',
spec: { value: 'url' },
},
];
const footnotes: Footnote[] = [
{
id: 'remote-debugging-docs',
url: 'https://ionicframework.com/docs/developer-resources/developer-tips',
shortUrl: 'https://ion.link/remote-debugging-docs',
},
{
id: 'livereload-docs',
url: 'https://ionicframework.com/docs/cli/livereload',
shortUrl: 'https://ion.link/livereload-docs',
},
{
id: 'native-run-repo',
url: 'https://github.com/ionic-team/native-run',
},
];
const serveRunner = this.project && await this.project.getServeRunner();
const buildRunner = this.project && await this.project.getBuildRunner();
if (buildRunner) {
const libmetadata = await buildRunner.getCommandMetadata();
groups.push(...libmetadata.groups || []);
options.push(...(libmetadata.options || []).filter(o => o.groups && o.groups.includes('cordova')));
footnotes.push(...libmetadata.footnotes || []);
}
if (serveRunner) {
const libmetadata = await serveRunner.getCommandMetadata();
const existingOpts = options.map(o => o.name);
groups.push(...libmetadata.groups || []);
const runnerOpts = (libmetadata.options || [])
.filter(o => !existingOpts.includes(o.name) && o.groups && o.groups.includes('cordova'))
.map(o => ({ ...o, hint: `${o.hint ? `${o.hint} ` : ''}${weak('(--livereload)')}` }));
options = lodash.uniqWith([...runnerOpts, ...options], (optionA, optionB) => optionA.name === optionB.name);
footnotes.push(...libmetadata.footnotes || []);
}
// Cordova Options
options.push(...CORDOVA_RUN_OPTIONS);
// `native-run` Options
options.push(...NATIVE_RUN_OPTIONS);
return {
name: 'run',
type: 'project',
summary: 'Run an Ionic project on a connected device',
description: `
Build your app and deploy it to devices and emulators using this command. Optionally specify the ${input('--livereload')} option to use the dev server from ${input('ionic serve')} for livereload functionality.
This command will first use ${input('ionic build')} to build web assets (or ${input('ionic serve')} with the ${input('--livereload')} option). Then, ${input('cordova build')} is used to compile and prepare your app. Finally, the ${input('native-run')} utility[^native-run-repo] is used to run your app on a device. To use Cordova for this process instead, use the ${input('--no-native-run')} option.
If you have multiple devices and emulators, you can target a specific one with the ${input('--target')} option. You can list targets with ${input('--list')}.
For Android and iOS, you can setup Remote Debugging on your device with browser development tools using these docs[^remote-debugging-docs].
When using ${input('--livereload')} with hardware devices, remember that livereload needs an active connection between device and computer. In some scenarios, you may need to host the dev server on an external address using the ${input('--external')} option. See these docs[^livereload-docs] for more information.
Just like with ${input('ionic cordova build')}, you can pass additional options to the Cordova CLI using the ${input('--')} separator. To pass additional options to the dev server, consider using ${input('ionic serve')} separately and using the ${input('--livereload-url')} option.
`,
footnotes,
exampleCommands,
inputs: [
{
name: 'platform',
summary: `The platform to run (e.g. ${['android', 'ios'].map(v => input(v)).join(', ')})`,
validators: [validators.required],
},
],
options,
groups,
};
}
async preRun(inputs: CommandLineInputs, options: CommandLineOptions, runinfo: CommandInstanceInfo): Promise<void> {
if (options['native-run']) {
await this.checkNativeRun();
}
await this.preRunChecks(runinfo);
const metadata = await this.getMetadata();
if (options['noproxy']) {
this.env.log.warn(`The ${input('--noproxy')} option has been deprecated. Please use ${input('--no-proxy')}.`);
options['proxy'] = false;
}
if (options['x']) {
options['proxy'] = false;
}
if (options['livereload-url']) {
options['livereload'] = true;
}
if (!options['build'] && options['livereload']) {
this.env.log.warn(`No livereload with ${input('--no-build')}.`);
options['livereload'] = false;
}
// If we're using the emulate command, and if --device and --emulator are
// not used, we should set the --emulator flag to mark intent.
if (!options['device'] && !options['emulator'] && metadata.name === 'emulate') {
options['emulator'] = true;
}
if (options['list']) {
if (options['native-run']) {
const args = createNativeRunListArgs(inputs, options);
await this.runNativeRun(args);
} else {
const args = filterArgumentsForCordova(metadata, options);
await this.runCordova(['run', ...args.slice(1)], {});
}
throw new FatalException('', 0);
}
if (!inputs[0]) {
const p = await this.env.prompt({
type: 'input',
name: 'platform',
message: `What platform would you like to run (${['android', 'ios'].map(v => input(v)).join(', ')}):`,
});
inputs[0] = p.trim();
}
const [ platform ] = inputs;
if (platform && options['native-run'] && !SUPPORTED_PLATFORMS.includes(platform)) {
this.env.log.warn(`${input(platform)} is not supported by ${input('native-run')}. Using Cordova to run the app.`);
options['native-run'] = false;
}
// If we're using native-run, and if --device and --emulator are not used,
// we can detect if hardware devices are plugged in and prefer them over
// any virtual devices the host has.
if (options['native-run'] && !options['device'] && !options['emulator'] && platform) {
const platformTargets = await getNativeTargets(this.env, platform);
const { devices } = platformTargets;
debug(`Native platform devices: %O`, devices);
if (devices.length > 0) {
this.env.log.info(`Hardware device(s) found for ${input(platform)}. Using ${input('--device')}.`);
options['device'] = true;
}
}
await this.checkForPlatformInstallation(platform);
}
async run(inputs: CommandLineInputs, options: CommandLineOptions): Promise<void> {
try {
if (options['livereload']) {
await this.runServeDeploy(inputs, options);
} else {
await this.runBuildDeploy(inputs, options);
}
} catch (e: any) {
if (e instanceof RunnerException) {
throw new FatalException(e.message);
}
throw e;
}
}
protected async runServeDeploy(inputs: CommandLineInputs, options: CommandLineOptions): Promise<void> {
const { loadCordovaConfig } = await import('../../lib/integrations/cordova/config');
const metadata = await this.getMetadata();
if (!this.project) {
throw new FatalException(`Cannot run ${input(`ionic cordova ${metadata.name}`)} outside a project directory.`);
}
const runner = await this.project.requireServeRunner();
const runnerOpts = runner.createOptionsFromCommandLine(inputs, generateOptionsForCordovaBuild(metadata, inputs, options));
/**
* With the --livereload-url option, this command won't perform a serve. If
* this is the case, details will be undefined.
*/
let details: ServeDetails | undefined;
let serverUrl = options['livereload-url'] ? String(options['livereload-url']) : undefined;
if (!serverUrl) {
details = await runner.run(runnerOpts);
if (details.externallyAccessible === false && !options['native-run']) {
const extra = LOCAL_ADDRESSES.includes(details.externalAddress) ? '\nEnsure you have proper port forwarding setup from your device to your computer.' : '';
this.env.log.warn(`Your device or emulator may not be able to access ${strong(details.externalAddress)}.${extra}\n\n`);
}
serverUrl = `${details.protocol || 'http'}://${details.externalAddress}:${details.port}`;
}
const conf = await loadCordovaConfig(this.integration);
onBeforeExit(async () => {
conf.resetContentSrc();
await conf.save();
});
conf.writeContentSrc(serverUrl);
await conf.save();
const cordovalogws = createPrefixedWriteStream(this.env.log, weak(`[cordova]`));
const buildOpts: IShellRunOptions = { stream: cordovalogws };
// ignore very verbose compiler output on stdout unless --verbose
buildOpts.stdio = options['verbose'] ? 'inherit' : ['pipe', 'ignore', 'pipe'];
if (options['native-run']) {
const [ platform ] = inputs;
await this.runCordova(filterArgumentsForCordova({ ...metadata, name: 'build' }, options), buildOpts);
const [ pkg ] = await this.project.getPackageJson(`cordova-${platform}`);
let packagePath = await getPackagePath(this.integration.root, conf.getProjectInfo().name, platform, { emulator: !options['device'], release: !!options['release'] });
if (pkg) {
const platformVersion = pkg.version;
packagePath = await getPackagePathCordova(this.integration.root, conf.getProjectInfo().name, platform, platformVersion, { emulator: !options['device'], release: !!options['release'] });
}
const forwardedPorts = details ? runner.getUsedPorts(runnerOpts, details) : [];
await this.runNativeRun(createNativeRunArgs({ packagePath, platform, forwardedPorts }, options));
} else {
await this.runCordova(filterArgumentsForCordova(metadata, options), buildOpts);
await sleepForever();
}
}
protected async runBuildDeploy(inputs: CommandLineInputs, options: CommandLineOptions): Promise<void> {
const { loadCordovaConfig } = await import('../../lib/integrations/cordova/config');
const metadata = await this.getMetadata();
if (!this.project) {
throw new FatalException(`Cannot run ${input(`ionic cordova ${metadata.name}`)} outside a project directory.`);
}
if (options.build) {
try {
const runner = await this.project.requireBuildRunner();
const runnerOpts = runner.createOptionsFromCommandLine(inputs, generateOptionsForCordovaBuild(metadata, inputs, options));
await runner.run(runnerOpts);
} catch (e: any) {
if (e instanceof RunnerException) {
throw new FatalException(e.message);
}
throw e;
}
}
if (options['native-run']) {
const conf = await loadCordovaConfig(this.integration);
const [ platform ] = inputs;
await this.runCordova(filterArgumentsForCordova({ ...metadata, name: 'build' }, options), { stdio: 'inherit' });
const [ pkg ] = await this.project.getPackageJson(`cordova-${platform}`);
let packagePath = await getPackagePath(this.integration.root, conf.getProjectInfo().name, platform, { emulator: !options['device'], release: !!options['release'] });
if (pkg) {
const platformVersion = pkg.version;
packagePath = await getPackagePathCordova(this.integration.root, conf.getProjectInfo().name, platform, platformVersion, { emulator: !options['device'], release: !!options['release'] });
}
await this.runNativeRun(createNativeRunArgs({ packagePath, platform }, { ...options, connect: false }));
} else {
await this.runCordova(filterArgumentsForCordova(metadata, options), { stdio: 'inherit' });
}
}
protected async checkNativeRun(): Promise<void> {
await checkNativeRun(this.env);
}
protected async runNativeRun(args: readonly string[]): Promise<void> {
if (!this.project) {
throw new FatalException(`Cannot run ${input('ionic cordova run/emulate')} outside a project directory.`);
}
await runNativeRun(this.env, args, { cwd: this.integration.root });
}
}