-
Notifications
You must be signed in to change notification settings - Fork 682
Expand file tree
/
Copy pathbase.ts
More file actions
329 lines (252 loc) · 11 KB
/
base.ts
File metadata and controls
329 lines (252 loc) · 11 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
import { pathExists } from '@ionic/utils-fs';
import { onBeforeExit } from '@ionic/utils-process';
import { ERROR_COMMAND_NOT_FOUND, SubprocessError } from '@ionic/utils-subprocess';
import * as lodash from 'lodash';
import * as path from 'path';
import * as semver from 'semver';
import { CommandInstanceInfo, CommandLineInputs, CommandLineOptions, IonicCapacitorOptions, ProjectIntegration } from '../../definitions';
import { input, weak } from '../../lib/color';
import { Command } from '../../lib/command';
import { FatalException, RunnerException } from '../../lib/errors';
import { runCommand } from '../../lib/executor';
import type { CapacitorCLIConfig, Integration as CapacitorIntegration } from '../../lib/integrations/capacitor'
import { ANDROID_MANIFEST_FILE, CapacitorAndroidManifest } from '../../lib/integrations/capacitor/android';
import { CAPACITOR_CONFIG_JSON_FILE, CapacitorJSONConfig, CapacitorConfig } from '../../lib/integrations/capacitor/config';
import { CapacitorIosInfo, IOS_INFO_FILE } from '../../lib/integrations/capacitor/ios';
import { generateOptionsForCapacitorBuild } from '../../lib/integrations/capacitor/utils';
import { createPrefixedWriteStream } from '../../lib/utils/logger';
import { pkgManagerArgs } from '../../lib/utils/npm';
export abstract class CapacitorCommand extends Command {
private _integration?: Required<ProjectIntegration>;
get integration(): Required<ProjectIntegration> {
if (!this.project) {
throw new FatalException(`Cannot use Capacitor outside a project directory.`);
}
if (!this._integration) {
this._integration = this.project.requireIntegration('capacitor');
}
return this._integration;
}
async getGeneratedConfig(platform: string): Promise<CapacitorJSONConfig> {
if (!this.project) {
throw new FatalException(`Cannot use Capacitor outside a project directory.`);
}
const p = await this.getGeneratedConfigPath(platform);
return new CapacitorJSONConfig(p);
}
async getGeneratedConfigPath(platform: string): Promise<string> {
if (!this.project) {
throw new FatalException(`Cannot use Capacitor outside a project directory.`);
}
const p = await this.getGeneratedConfigDir(platform);
return path.resolve(this.integration.root, p, CAPACITOR_CONFIG_JSON_FILE);
}
async getAndroidManifest(): Promise<CapacitorAndroidManifest> {
const p = await this.getAndroidManifestPath();
return CapacitorAndroidManifest.load(p);
}
async getAndroidManifestPath(): Promise<string> {
const cli = await this.getCapacitorCLIConfig();
const srcDir = cli?.android.srcMainDirAbs ?? 'android/app/src/main';
return path.resolve(this.integration.root, srcDir, ANDROID_MANIFEST_FILE);
}
async getiOSAppInfo(): Promise<CapacitorIosInfo> {
const p = await this.getiOSAppInfoPath();
return CapacitorIosInfo.load(p);
}
async getiOSAppInfoPath(): Promise<string> {
const cli = await this.getCapacitorCLIConfig();
const srcDir = cli?.ios.nativeTargetDirAbs ?? 'ios/App/App';
return path.resolve(this.integration.root, srcDir, IOS_INFO_FILE);
}
async getGeneratedConfigDir(platform: string): Promise<string> {
const cli = await this.getCapacitorCLIConfig();
switch (platform) {
case 'android':
return cli?.android.assetsDirAbs ?? 'android/app/src/main/assets';
case 'ios':
return cli?.ios.nativeTargetDirAbs ?? 'ios/App/App';
}
throw new FatalException(`Could not determine generated Capacitor config path for ${input(platform)} platform.`);
}
async getCapacitorCLIConfig(): Promise<CapacitorCLIConfig | undefined> {
const capacitor = await this.getCapacitorIntegration();
return capacitor.getCapacitorCLIConfig();
}
async getCapacitorConfig(): Promise<CapacitorConfig | undefined> {
const capacitor = await this.getCapacitorIntegration();
return capacitor.getCapacitorConfig();
}
getCapacitorIntegration = lodash.memoize(async (): Promise<CapacitorIntegration> => {
if (!this.project) {
throw new FatalException(`Cannot use Capacitor outside a project directory.`);
}
return this.project.createIntegration('capacitor');
});
getCapacitorVersion = lodash.memoize(async (): Promise<semver.SemVer> => {
try {
const proc = await this.env.shell.createSubprocess('capacitor', ['--version'], { cwd: this.integration.root });
const version = semver.parse((await proc.output()).trim());
if (!version) {
throw new FatalException('Error while parsing Capacitor CLI version.');
}
return version;
} catch (e: any) {
if (e instanceof SubprocessError) {
if (e.code === ERROR_COMMAND_NOT_FOUND) {
throw new FatalException('Error while getting Capacitor CLI version. Is Capacitor installed?');
}
throw new FatalException('Error while getting Capacitor CLI version.\n' + (e.output ? e.output : e.code));
}
throw e;
}
});
isCorePlatform(platform: string): boolean {
const platforms = ['android', 'ios'];
return platforms.includes(platform);
}
async getInstalledPlatforms(): Promise<string[]> {
const cli = await this.getCapacitorCLIConfig();
const androidPlatformDirAbs = cli?.android.platformDirAbs ?? path.resolve(this.integration.root, 'android');
const iosPlatformDirAbs = cli?.ios.platformDirAbs ?? path.resolve(this.integration.root, 'ios');
const platforms: string[] = [];
if (await pathExists(androidPlatformDirAbs)) {
platforms.push('android');
}
if (await pathExists(iosPlatformDirAbs)) {
platforms.push('ios');
}
if (await pathExists(path.resolve(this.integration.root, 'electron'))) {
platforms.push('electron');
}
return platforms;
}
async isPlatformInstalled(platform: string): Promise<boolean> {
const platforms = await this.getInstalledPlatforms();
return platforms.includes(platform);
}
async checkCapacitor(runinfo: CommandInstanceInfo) {
if (!this.project) {
throw new FatalException(`Cannot use Capacitor outside a project directory.`);
}
const capacitor = this.project.getIntegration('capacitor');
if (!capacitor) {
await runCommand(runinfo, ['integrations', 'enable', 'capacitor']);
}
}
async preRunChecks(runinfo: CommandInstanceInfo) {
await this.checkCapacitor(runinfo);
}
async runCapacitor(argList: string[]) {
if (!this.project) {
throw new FatalException(`Cannot use Capacitor outside a project directory.`);
}
const stream = createPrefixedWriteStream(this.env.log, weak(`[capacitor]`));
await this.env.shell.run('capacitor', argList, { stream, fatalOnNotFound: false, truncateErrorOutput: 5000, cwd: this.integration.root });
}
async runBuild(inputs: CommandLineInputs, options: CommandLineOptions): Promise<void> {
if (!this.project) {
throw new FatalException(`Cannot use Capacitor outside a project directory.`);
}
const conf = await this.getCapacitorConfig();
if (conf?.server?.url) {
this.env.log.warn(
`Capacitor server URL is in use.\n` +
`This may result in unexpected behavior for this build, where an external server is used in the Web View instead of your app. This likely occurred because of ${input('--livereload')} usage in the past and the CLI improperly exiting without cleaning up.\n\n` +
`Delete the ${input('server')} key in the Capacitor config file if you did not intend to use an external server.`
);
this.env.log.nl();
}
if (options['build']) {
try {
const runner = await this.project.requireBuildRunner();
const runnerOpts = runner.createOptionsFromCommandLine(inputs, generateOptionsForCapacitorBuild(inputs, options));
await runner.run(runnerOpts);
} catch (e: any) {
if (e instanceof RunnerException) {
throw new FatalException(e.message);
}
throw e;
}
}
}
async runServe(inputs: CommandLineInputs, options: CommandLineOptions): Promise<void> {
if (!this.project) {
throw new FatalException(`Cannot run ${input('ionic capacitor run')} outside a project directory.`);
}
const [ platform ] = inputs;
try {
const runner = await this.project.requireServeRunner();
const runnerOpts = runner.createOptionsFromCommandLine(inputs, generateOptionsForCapacitorBuild(inputs, options));
let serverUrl = options['livereload-url'] ? String(options['livereload-url']) : undefined;
const details = await runner.run(runnerOpts);
if (!serverUrl) {
serverUrl = `${details.protocol || 'http'}://${details.externalAddress}:${details.port}`;
}
const conf = await this.getGeneratedConfig(platform);
onBeforeExit(async () => {
conf.resetServerUrl();
});
conf.setServerUrl(serverUrl);
if (platform === 'android') {
const manifest = await this.getAndroidManifest();
onBeforeExit(async () => {
await manifest.reset();
});
manifest.enableCleartextTraffic();
await manifest.save();
}
if (platform === 'ios' && !options['external']) {
const appInfo = await this.getiOSAppInfo();
onBeforeExit(async () => {
await appInfo.reset();
})
appInfo.disableAppTransportSecurity();
await appInfo.save();
}
} catch (e: any) {
if (e instanceof RunnerException) {
throw new FatalException(e.message);
}
throw e;
}
}
async checkForPlatformInstallation(platform: string) {
if (!this.project) {
throw new FatalException('Cannot use Capacitor outside a project directory.');
}
if (platform) {
const capacitor = this.project.getIntegration('capacitor');
if (!capacitor) {
throw new FatalException('Cannot check platform installations--Capacitor not yet integrated.');
}
if (!(await this.isPlatformInstalled(platform))) {
await this.installPlatform(platform);
}
}
}
async installPlatform(platform: string): Promise<void> {
const version = await this.getCapacitorVersion();
const installedPlatforms = await this.getInstalledPlatforms();
if (installedPlatforms.includes(platform)) {
throw new FatalException(`The ${input(platform)} platform is already installed!`);
}
if (semver.gte(version, '3.0.0-alpha.1')) {
if (this.isCorePlatform(platform)) {
const [ manager, ...managerArgs ] = await pkgManagerArgs(this.env.config.get('npmClient'), { command: 'install', pkg: `@capacitor/${platform}@${version}`, saveDev: false });
await this.env.shell.run(manager, managerArgs, { cwd: this.integration.root });
}
}
await this.runCapacitor(['add', platform]);
}
protected async createOptionsFromCommandLine(inputs: CommandLineInputs, options: CommandLineOptions): Promise<IonicCapacitorOptions> {
const separatedArgs = options['--'];
const verbose = !!options['verbose'];
const conf = await this.getCapacitorConfig();
return {
'--': separatedArgs ? separatedArgs : [],
verbose,
...conf,
};
}
}