-
Notifications
You must be signed in to change notification settings - Fork 652
/
index.ts
290 lines (230 loc) · 9.47 KB
/
index.ts
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
import { copy, mkdirp, pathExists, readdirSafe, remove, stat } from '@ionic/utils-fs';
import * as chalk from 'chalk';
import * as Debug from 'debug';
import * as lodash from 'lodash';
import * as os from 'os';
import * as path from 'path';
import { BaseIntegration, IntegrationConfig } from '../';
import { InfoItem, IntegrationAddDetails, IntegrationAddHandlers, IntegrationName, ProjectIntegration, ProjectPersonalizationDetails, ProjectType } from '../../../definitions';
import { FatalException } from '../../../lib/errors';
import { emoji } from '../../../lib/utils/emoji';
import { ancillary, input, strong } from '../../color';
import { prettyProjectName } from '../../project';
import * as configlib from './config';
const debug = Debug('ionic:lib:integrations:cordova');
export const SUPPORTED_PROJECT_TYPES: readonly ProjectType[] = ['custom', 'ionic1', 'ionic-angular', 'angular'];
export class Integration extends BaseIntegration<ProjectIntegration> {
readonly name: IntegrationName = 'cordova';
readonly summary = 'Target native iOS and Android with Apache Cordova';
readonly archiveUrl = 'https://d2ql0qc7j8u4b2.cloudfront.net/integration-cordova.tar.gz';
get config(): IntegrationConfig {
return new IntegrationConfig(this.e.project.filePath, { pathPrefix: [...this.e.project.pathPrefix, 'integrations', this.name] });
}
async add(details: IntegrationAddDetails): Promise<void> {
if (!SUPPORTED_PROJECT_TYPES.includes(this.e.project.type)) {
throw new FatalException(
`Ionic doesn't support using Cordova with ${input(prettyProjectName(this.e.project.type))} projects.\n` +
`We encourage you to try ${emoji('⚡️ ', '')}${strong('Capacitor')}${emoji(' ⚡️', '')} (${strong('https://ion.link/capacitor')})`
);
}
const handlers: IntegrationAddHandlers = {
conflictHandler: async (f, stats) => {
const isDirectory = stats.isDirectory();
const filename = `${path.basename(f)}${isDirectory ? '/' : ''}`;
const type = isDirectory ? 'directory' : 'file';
const confirm = await details.env.prompt({
type: 'confirm',
name: 'confirm',
message: `The ${ancillary(filename)} ${type} exists in project. Overwrite?`,
default: false,
});
return confirm;
},
onFileCreate: f => {
if (!details.quiet) {
details.env.log.msg(`${chalk.green('CREATE')} ${f}`);
}
},
};
const onFileCreate = handlers.onFileCreate ? handlers.onFileCreate : lodash.noop;
const conflictHandler = handlers.conflictHandler ? handlers.conflictHandler : async () => false;
const { createRequest, download } = await import('../../utils/http');
const { tar } = await import('../../utils/archive');
this.e.log.info(`Downloading integration ${input(this.name)}`);
const tmpdir = path.resolve(os.tmpdir(), `ionic-integration-${this.name}`);
// TODO: etag
if (await pathExists(tmpdir)) {
await remove(tmpdir);
}
await mkdirp(tmpdir);
const ws = tar.extract({ cwd: tmpdir });
const { req } = await createRequest('GET', this.archiveUrl, this.e.config.getHTTPConfig());
await download(req, ws, {});
const contents = await readdirSafe(tmpdir);
const blacklist: string[] = [];
debug(`Integration files downloaded to ${strong(tmpdir)} (files: ${contents.map(f => strong(f)).join(', ')})`);
for (const f of contents) {
const projectf = path.resolve(this.e.project.directory, f);
try {
const stats = await stat(projectf);
const overwrite = await conflictHandler(projectf, stats);
if (!overwrite) {
blacklist.push(f);
}
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
}
this.e.log.info(`Copying integrations files to project`);
debug(`Blacklist: ${blacklist.map(f => strong(f)).join(', ')}`);
await mkdirp(details.root);
await copy(tmpdir, details.root, {
filter: f => {
if (f === tmpdir) {
return true;
}
const projectf = f.substring(tmpdir.length + 1);
for (const item of blacklist) {
if (item.slice(-1) === '/' && `${projectf}/` === item) {
return false;
}
if (projectf.startsWith(item)) {
return false;
}
}
onFileCreate(projectf);
return true;
},
});
await super.add(details);
}
async getConfig(): Promise<configlib.CordovaConfig | undefined> {
try {
return await this.requireConfig();
} catch (e) {
// ignore
}
}
async requireConfig(): Promise<configlib.CordovaConfig> {
const { loadCordovaConfig } = await import('./config');
const integration = this.e.project.requireIntegration('cordova');
const conf = await loadCordovaConfig(integration);
return conf;
}
async getInfo(): Promise<InfoItem[]> {
const { getAndroidSdkToolsVersion } = await import('./android');
const [
cordovaVersion,
cordovaPlatforms,
cordovaPlugins,
xcode,
iosDeploy,
iosSim,
androidSdkToolsVersion,
] = await (Promise.all([
this.getCordovaVersion(),
this.getCordovaPlatformVersions(),
this.getCordovaPluginVersions(),
this.getXcodebuildVersion(),
this.getIOSDeployVersion(),
this.getIOSSimVersion(),
getAndroidSdkToolsVersion(),
]) as Promise<[string | undefined, string, string, string | undefined, string | undefined, string | undefined, string | undefined]>); // TODO: https://github.com/microsoft/TypeScript/issues/33752
const info: InfoItem[] = [
{ group: 'cordova', name: 'Cordova CLI', key: 'cordova_version', value: cordovaVersion || 'not installed' },
{ group: 'cordova', name: 'Cordova Platforms', key: 'cordova_platforms', value: cordovaPlatforms },
{ group: 'cordova', name: 'Cordova Plugins', value: cordovaPlugins },
];
if (xcode) {
info.push({ group: 'system', name: 'Xcode', key: 'xcode_version', value: xcode });
}
if (iosDeploy) {
info.push({ group: 'system', name: 'ios-deploy', value: iosDeploy });
}
if (iosSim) {
info.push({ group: 'system', name: 'ios-sim', value: iosSim });
}
if (androidSdkToolsVersion) {
info.push({ group: 'system', name: 'Android SDK Tools', key: 'android_sdk_version', value: androidSdkToolsVersion });
}
const conf = await this.getConfig();
if (conf) {
const bundleId = conf.getBundleId();
info.push({ group: 'cordova', name: 'Bundle ID', key: 'bundle_id', value: bundleId || 'unknown', hidden: true });
}
return info;
}
async personalize({ name, packageId }: ProjectPersonalizationDetails) {
const conf = await this.requireConfig();
conf.setName(name);
if (packageId) {
conf.setBundleId(packageId);
}
await conf.save();
}
async getCordovaVersion(): Promise<string | undefined> {
try {
const integration = this.e.project.requireIntegration('cordova');
return this.e.shell.cmdinfo('cordova', ['-v', '--no-telemetry', '--no-update-notifier'], { cwd: integration.root });
} catch (e) {
debug('Error while getting Cordova version: %O', e);
}
}
async getCordovaPlatformVersions(): Promise<string> {
try {
const integration = this.e.project.requireIntegration('cordova');
const output = await this.e.shell.output('cordova', ['platform', 'ls', '--no-telemetry', '--no-update-notifier'], { cwd: integration.root, showCommand: false });
const platforms = output
.replace('Installed platforms:', '')
.replace(/Available platforms[\s\S]+/, '')
.split('\n')
.map(l => l.trim())
.filter(l => l && !l.startsWith('.'));
if (platforms.length === 0) {
return 'none';
}
return platforms.join(', ');
} catch (e) {
debug('Error while getting Cordova platforms: %O', e);
return 'not available';
}
}
async getCordovaPluginVersions(): Promise<string> {
const whitelist = [
/^cordova-plugin-ionic$/,
/^cordova-plugin-ionic-.+/,
];
try {
const integration = this.e.project.requireIntegration('cordova');
const output = await this.e.shell.output('cordova', ['plugin', 'ls', '--no-telemetry', '--no-update-notifier'], { cwd: integration.root, showCommand: false });
const pluginRe = /^([a-z-]+)\s+(\d\.\d\.\d).+$/;
const plugins = output
.split('\n')
.map(l => l.trim().match(pluginRe))
.filter((l): l is RegExpMatchArray => l !== null)
.map(m => [m[1], m[2]]);
const whitelistedPlugins = plugins
.filter(([ plugin, version ]) => whitelist.some(re => re.test(plugin)))
.map(([ plugin, version ]) => `${plugin} ${version}`);
const count = plugins.length - whitelistedPlugins.length;
if (whitelistedPlugins.length === 0) {
return `no whitelisted plugins (${count} plugins total)`;
}
return `${whitelistedPlugins.join(', ')}${count > 0 ? `, (and ${count} other plugins)` : ''}`;
} catch (e) {
debug('Error while getting Cordova plugins: %O', e);
return 'not available';
}
}
async getXcodebuildVersion(): Promise<string | undefined> {
return this.e.shell.cmdinfo('xcodebuild', ['-version']);
}
async getIOSDeployVersion(): Promise<string | undefined> {
return this.e.shell.cmdinfo('ios-deploy', ['--version']);
}
async getIOSSimVersion(): Promise<string | undefined> {
return this.e.shell.cmdinfo('ios-sim', ['--version']);
}
}