forked from microsoft/code-push
-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathreact-native-utils.ts
More file actions
670 lines (591 loc) · 24.9 KB
/
react-native-utils.ts
File metadata and controls
670 lines (591 loc) · 24.9 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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
import fs from 'fs';
import path from 'path';
import xml2js from 'xml2js';
import { out } from '../util/interaction';
import { isValidVersion, isLowVersion } from './validation-utils';
import { fileDoesNotExistOrIsDirectory } from './file-utils';
import chalk from 'chalk';
import * as cli from '../definitions/cli';
import { coerce, compare } from 'semver';
const plist = require('plist');
const g2js = require('gradle-to-js/lib/parser');
const properties = require('properties');
const childProcess = require('child_process');
export const spawn = childProcess.spawn;
export function getReactNativeProjectAppVersion(
command: cli.IReleaseReactCommand,
projectName: string,
): Promise<string> {
const fileExists = (file: string): boolean => {
try {
return fs.statSync(file).isFile();
} catch (e) {
return false;
}
};
out.text(chalk.cyan(`Detecting ${command.platform} app version:\n`));
if (command.platform === 'ios') {
let resolvedPlistFile: string = command.plistFile;
if (resolvedPlistFile) {
// If a plist file path is explicitly provided, then we don't
// need to attempt to "resolve" it within the well-known locations.
if (!fileExists(resolvedPlistFile)) {
throw new Error(
"The specified plist file doesn't exist. Please check that the provided path is correct.",
);
}
} else {
// Allow the plist prefix to be specified with or without a trailing
// separator character, but prescribe the use of a hyphen when omitted,
// since this is the most commonly used convetion for plist files.
if (command.plistFilePrefix && /.+[^-.]$/.test(command.plistFilePrefix)) {
command.plistFilePrefix += '-';
}
const iOSDirectory: string = 'ios';
const plistFileName = `${command.plistFilePrefix || ''}Info.plist`;
const knownLocations = [
path.join(iOSDirectory, projectName, plistFileName),
path.join(iOSDirectory, plistFileName),
];
resolvedPlistFile = (<any>knownLocations).find(fileExists);
if (!resolvedPlistFile) {
throw new Error(
`Unable to find either of the following plist files in order to infer your app's binary version: "${knownLocations.join(
'", "',
)}". If your plist has a different name, or is located in a different directory, consider using either the "--plistFile" or "--plistFilePrefix" parameters to help inform the CLI how to find it.`,
);
}
}
const plistContents = fs.readFileSync(resolvedPlistFile).toString();
try {
var parsedPlist = plist.parse(plistContents);
} catch (e) {
throw new Error(
`Unable to parse "${resolvedPlistFile}". Please ensure it is a well-formed plist file.`,
);
}
if (parsedPlist && parsedPlist.CFBundleShortVersionString) {
if (/MARKETING_VERSION/i.test(parsedPlist.CFBundleShortVersionString)) {
try {
const xcodeProjectConfig =
path.resolve(resolvedPlistFile, '../') + '.xcodeproj/project.pbxproj';
out.text(
'Using xcodeProjectConfig version, file path "'.concat(
xcodeProjectConfig,
'".\n',
),
);
const xcodeContents = fs.readFileSync(xcodeProjectConfig).toString();
const xcodeVersionRegex = /Release[\s\S]*MARKETING_VERSION = (\d+\.\d+\.\d+)/gm;
let xcodeVersion;
let match;
while ((match = xcodeVersionRegex.exec(xcodeContents)) !== null) {
// 这个循环将重复执行,直到没有更多匹配项
// match[1] 将包含第一个捕获组的值,即版本号
xcodeVersion = match[1];
break; // 因为我们只需要第一个匹配项,所以找到后就可以退出循环
}
out.text(
'Using xcodeProjectConfig version, version "'.concat(xcodeVersion, '".\n'),
);
parsedPlist.CFBundleShortVersionString = xcodeVersion;
} catch (error) {}
}
if (isValidVersion(parsedPlist.CFBundleShortVersionString)) {
out.text(
`Using the target binary version value "${parsedPlist.CFBundleShortVersionString}" from "${resolvedPlistFile}".\n`,
);
return Promise.resolve(parsedPlist.CFBundleShortVersionString);
} else {
throw new Error(
`The "CFBundleShortVersionString" key in the "${resolvedPlistFile}" file needs to specify a valid semver string, containing both a major and minor version (e.g. 1.3.2, 1.1).`,
);
}
} else {
throw new Error(
`The "CFBundleShortVersionString" key doesn't exist within the "${resolvedPlistFile}" file.`,
);
}
} else if (command.platform === 'android') {
let buildGradlePath: string = path.join('android', 'app');
if (command.gradleFile) {
buildGradlePath = command.gradleFile;
}
if (fs.lstatSync(buildGradlePath).isDirectory()) {
buildGradlePath = path.join(buildGradlePath, 'build.gradle');
}
if (fileDoesNotExistOrIsDirectory(buildGradlePath)) {
throw new Error(`Unable to find gradle file "${buildGradlePath}".`);
}
return g2js
.parseFile(buildGradlePath)
.catch(() => {
throw new Error(
`Unable to parse the "${buildGradlePath}" file. Please ensure it is a well-formed Gradle file.`,
);
})
.then((buildGradle: any) => {
let versionName: string = null;
if (
buildGradle.android &&
buildGradle.android.defaultConfig &&
buildGradle.android.defaultConfig.versionName
) {
versionName = buildGradle.android.defaultConfig.versionName;
} else {
throw new Error(
`The "${buildGradlePath}" file doesn't specify a value for the "android.defaultConfig.versionName" property.`,
);
}
if (typeof versionName !== 'string') {
throw new Error(
`The "android.defaultConfig.versionName" property value in "${buildGradlePath}" is not a valid string. If this is expected, consider using the --targetBinaryVersion option to specify the value manually.`,
);
}
let appVersion: string = versionName.replace(/"/g, '').trim();
if (isValidVersion(appVersion)) {
// The versionName property is a valid semver string,
// so we can safely use that and move on.
out.text(
`Using the target binary version value "${appVersion}" from "${buildGradlePath}".\n`,
);
return appVersion;
} else if (/^\d.*/.test(appVersion)) {
// The versionName property isn't a valid semver string,
// but it starts with a number, and therefore, it can't
// be a valid Gradle property reference.
throw new Error(
`The "android.defaultConfig.versionName" property in the "${buildGradlePath}" file needs to specify a valid semver string, containing both a major and minor version (e.g. 1.3.2, 1.1).`,
);
}
// The version property isn't a valid semver string
// so we assume it is a reference to a property variable.
const propertyName = appVersion.replace('project.', '');
const propertiesFileName = 'gradle.properties';
const knownLocations = [
path.join('android', 'app', propertiesFileName),
path.join('android', propertiesFileName),
];
// Search for gradle properties across all `gradle.properties` files
var propertiesFile: string = null;
for (var i = 0; i < knownLocations.length; i++) {
propertiesFile = knownLocations[i];
if (fileExists(propertiesFile)) {
const propertiesContent: string = fs
.readFileSync(propertiesFile)
.toString();
try {
const parsedProperties: any = properties.parse(propertiesContent);
appVersion = parsedProperties[propertyName];
if (appVersion) {
break;
}
} catch (e) {
throw new Error(
`Unable to parse "${propertiesFile}". Please ensure it is a well-formed properties file.`,
);
}
}
}
if (!appVersion) {
throw new Error(
`No property named "${propertyName}" exists in the "${propertiesFile}" file.`,
);
}
if (!isValidVersion(appVersion)) {
throw new Error(
`The "${propertyName}" property in the "${propertiesFile}" file needs to specify a valid semver string, containing both a major and minor version (e.g. 1.3.2, 1.1).`,
);
}
out.text(
`Using the target binary version value "${appVersion}" from the "${propertyName}" key in the "${propertiesFile}" file.\n`,
);
return appVersion.toString();
});
} else {
var appxManifestFileName: string = 'Package.appxmanifest';
try {
var appxManifestContainingFolder: string = path.join('windows', projectName);
var appxManifestContents: string = fs
.readFileSync(path.join(appxManifestContainingFolder, 'Package.appxmanifest'))
.toString();
} catch (err) {
throw new Error(
`Unable to find or read "${appxManifestFileName}" in the "${path.join(
'windows',
projectName,
)}" folder.`,
);
}
return new Promise<string>((resolve, reject) => {
xml2js.parseString(appxManifestContents, (err: Error, parsedAppxManifest: any) => {
if (err) {
reject(
new Error(
`Unable to parse the "${path.join(
appxManifestContainingFolder,
appxManifestFileName,
)}" file, it could be malformed.`,
),
);
return;
}
try {
const appVersion: string =
parsedAppxManifest.Package.Identity[0]['$'].Version.match(
/^\d+\.\d+\.\d+/,
)[0];
out.text(
`Using the target binary version value "${appVersion}" from the "Identity" key in the "${appxManifestFileName}" file.\n`,
);
return resolve(appVersion);
} catch (e) {
reject(
new Error(
`Unable to parse the package version from the "${path.join(
appxManifestContainingFolder,
appxManifestFileName,
)}" file.`,
),
);
return;
}
});
});
}
}
// https://github.com/microsoft/appcenter-cli/blob/master/src/commands/codepush/release-react.ts#L201
// https://github.com/microsoft/appcenter-cli/blob/13495af812558bd952d8aeb9dc01b5be089cd1fc/src/commands/codepush/lib/react-native-utils.ts#L277
function getCliPath(): string {
if (process.platform === 'win32') {
const reactNativeVersion = coerce(getReactNativeVersion()).version;
const isVersion75OrAbove = compare(reactNativeVersion, '0.75.0') >= 0;
return isVersion75OrAbove
? path.join(getReactNativePackagePath(), 'cli.js')
: path.join(getReactNativePackagePath(), 'local-cli', 'cli.js');
}
return path.join('node_modules', '.bin', 'react-native');
}
function directoryExistsSync(dirname: string): boolean {
try {
return fs.statSync(dirname).isDirectory();
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
return false;
}
function getReactNativePackagePath(): string {
const result = childProcess.spawnSync('node', [
'--print',
"require.resolve('react-native/package.json')",
]);
const packagePath = path.dirname(result.stdout.toString());
if (result.status === 0 && directoryExistsSync(packagePath)) {
return packagePath;
}
return path.join('node_modules', 'react-native');
}
export function runReactNativeBundleCommand(
bundleName: string,
development: boolean,
entryFile: string,
outputFolder: string,
platform: string,
sourcemapOutput: string,
config: string,
extraBundlerOptions?: string[],
): Promise<void> {
let reactNativeBundleArgs: string[] = [];
let envNodeArgs: string = process.env.CODE_PUSH_NODE_ARGS;
if (typeof envNodeArgs !== 'undefined') {
Array.prototype.push.apply(reactNativeBundleArgs, envNodeArgs.trim().split(/\s+/));
}
Array.prototype.push.apply(reactNativeBundleArgs, [
getCliPath(),
'bundle',
'--assets-dest',
outputFolder,
'--bundle-output',
path.join(outputFolder, bundleName),
'--dev',
development,
'--entry-file',
entryFile,
'--platform',
platform,
...extraBundlerOptions,
]);
if (sourcemapOutput) {
reactNativeBundleArgs.push('--sourcemap-output', sourcemapOutput);
}
if (config) {
reactNativeBundleArgs.push('--config', config);
}
out.text(chalk.cyan('Running "react-native bundle" command:\n'));
var reactNativeBundleProcess = spawn('node', reactNativeBundleArgs);
out.text(`node ${reactNativeBundleArgs.join(' ')}`);
return new Promise<void>((resolve, reject) => {
reactNativeBundleProcess.stdout.on('data', (data: Buffer) => {
out.text(data.toString().trim());
});
reactNativeBundleProcess.stderr.on('data', (data: Buffer) => {
console.error(data.toString().trim());
});
reactNativeBundleProcess.on('close', (exitCode: number) => {
if (exitCode) {
reject(new Error(`"react-native bundle" command exited with code ${exitCode}.`));
}
resolve(<void>null);
});
});
}
export function runHermesEmitBinaryCommand(
bundleName: string,
outputFolder: string,
sourcemapOutput: string,
extraHermesFlags: string[],
): Promise<void> {
const hermesArgs: string[] = [];
const envNodeArgs: string = process.env.CODE_PUSH_NODE_ARGS;
out.text(chalk.cyan('Converting JS bundle to byte code via Hermes, running command:\n'));
if (typeof envNodeArgs !== 'undefined') {
Array.prototype.push.apply(hermesArgs, envNodeArgs.trim().split(/\s+/));
}
Array.prototype.push.apply(hermesArgs, [
'-emit-binary',
'-out',
path.join(outputFolder, bundleName + '.hbc'),
path.join(outputFolder, bundleName),
...extraHermesFlags,
]);
if (sourcemapOutput) {
hermesArgs.push('-output-source-map');
}
/*
if (!isDebug()) {
hermesArgs.push("-w");
}
*/
out.text(chalk.cyan('Converting JS bundle to byte code via Hermes, running command:\n'));
const hermesCommand = getHermesCommand();
const hermesProcess = spawn(hermesCommand, hermesArgs);
out.text(`${hermesCommand} ${hermesArgs.join(' ')}`);
return new Promise<void>((resolve, reject) => {
hermesProcess.stdout.on('data', (data: Buffer) => {
out.text(data.toString().trim());
});
hermesProcess.stderr.on('data', (data: Buffer) => {
console.error(data.toString().trim());
});
hermesProcess.on('close', (exitCode: number) => {
if (exitCode) {
reject(new Error(`"hermes" command exited with code ${exitCode}.`));
}
// Copy HBC bundle to overwrite JS bundle
const source = path.join(outputFolder, bundleName + '.hbc');
const destination = path.join(outputFolder, bundleName);
fs.copyFile(source, destination, (err) => {
if (err) {
console.error(err);
reject(
new Error(
`Copying file ${source} to ${destination} failed. "hermes" previously exited with code ${exitCode}.`,
),
);
}
fs.unlink(source, (err) => {
if (err) {
console.error(err);
reject(err);
}
resolve(null as void);
});
});
});
}).then(() => {
if (!sourcemapOutput) {
// skip source map compose if source map is not enabled
return;
}
const composeSourceMapsPath = getComposeSourceMapsPath();
if (!composeSourceMapsPath) {
throw new Error('react-native compose-source-maps.js scripts is not found');
}
const jsCompilerSourceMapFile = path.join(outputFolder, bundleName + '.hbc' + '.map');
if (!fs.existsSync(jsCompilerSourceMapFile)) {
throw new Error(`sourcemap file ${jsCompilerSourceMapFile} is not found`);
}
return new Promise((resolve, reject) => {
const composeSourceMapsArgs = [
sourcemapOutput,
jsCompilerSourceMapFile,
'-o',
sourcemapOutput,
];
// https://github.com/facebook/react-native/blob/master/react.gradle#L211
// index.android.bundle.packager.map + index.android.bundle.compiler.map = index.android.bundle.map
const composeSourceMapsProcess = spawn(composeSourceMapsPath, composeSourceMapsArgs);
out.text(`${composeSourceMapsPath} ${composeSourceMapsArgs.join(' ')}`);
composeSourceMapsProcess.stdout.on('data', (data: Buffer) => {
out.text(data.toString().trim());
});
composeSourceMapsProcess.stderr.on('data', (data: Buffer) => {
console.error(data.toString().trim());
});
composeSourceMapsProcess.on('close', (exitCode: number) => {
if (exitCode) {
reject(
new Error(`"compose-source-maps" command exited with code ${exitCode}.`),
);
}
// Delete the HBC sourceMap, otherwise it will be included in 'code-push' bundle as well
fs.unlink(jsCompilerSourceMapFile, (err) => {
if (err) {
console.error(err);
reject(err);
}
resolve(null);
});
});
});
});
}
export async function getHermesEnabled(gradleFile?: string): Promise<boolean> {
let buildGradlePath = gradleFile ?? path.join('android', 'app');
if (await fileDoesNotExistOrIsDirectory(buildGradlePath)) {
buildGradlePath = path.join(buildGradlePath, 'build.gradle');
}
if (await fileDoesNotExistOrIsDirectory(buildGradlePath)) {
throw new Error(`Unable to find gradle file "${buildGradlePath}".`);
}
let gradlePropertyPath: string = path.join('android', 'gradle.properties');
if (await fileDoesNotExistOrIsDirectory(gradlePropertyPath)) {
throw new Error(`Unable to find gradle file "${gradlePropertyPath}".`);
}
try {
const buildGradle = await g2js.parseFile(buildGradlePath);
const buildProperty = await g2js.parseFile(gradlePropertyPath);
const hermesPropertyEnabled = buildProperty.hermesEnabled ?? false;
let hermesBuildEnabled = false;
// 如果buildGradle["project.ext.react"]是一个数组,则继续处理
if (Array.isArray(buildGradle['project.ext.react'])) {
const reactSettings: string[] = buildGradle['project.ext.react'];
hermesBuildEnabled = reactSettings.some((line) =>
/^enableHermes\s*:\s*true/.test(line),
);
}
return hermesPropertyEnabled || hermesBuildEnabled;
} catch (error) {
// error.message 可能需要根据实际在 try 块中发生的错误进行调整
throw new Error(`An error occurred while processing the Gradle files: ${error.message}`);
}
}
export function getiOSHermesEnabled(podFile: string): Promise<boolean> {
let podPath = path.join('ios', 'Podfile');
if (podFile) {
podPath = podFile;
}
if (fileDoesNotExistOrIsDirectory(podPath)) {
throw new Error(`Unable to find Podfile file "${podPath}".`);
}
return new Promise((resolve, reject) => {
fs.readFile(podPath, { encoding: 'utf8' }, (error, res) => {
if (error) {
reject(error);
return;
}
resolve(/:hermes_enabled(\s+|\n+)?=>(\s+|\n+)?true/.test(res));
});
});
}
function getHermesOSBin(): string {
switch (process.platform) {
case 'win32':
return 'win64-bin';
case 'darwin':
return 'osx-bin';
case 'freebsd':
case 'linux':
case 'sunos':
default:
return 'linux64-bin';
}
}
function getHermesOSExe(): string {
const hermesExecutableName = isLowVersion(getReactNativeVersion(), '0.63.0')
? 'hermes'
: 'hermesc';
switch (process.platform) {
case 'win32':
return hermesExecutableName + '.exe';
default:
return hermesExecutableName;
}
}
function getHermesCommand(): string {
const fileExists = (file: string): boolean => {
try {
return fs.statSync(file).isFile();
} catch (e) {
return false;
}
};
// assume if hermes-engine exists it should be used instead of hermesvm
const hermesEngineNew = path.join(
'node_modules',
'react-native',
'sdks',
'hermesc',
getHermesOSBin(),
getHermesOSExe(),
);
if (fileExists(hermesEngineNew)) {
return hermesEngineNew;
}
const hermesEngine = path.join(
'node_modules',
'hermes-engine',
getHermesOSBin(),
getHermesOSExe(),
);
if (fileExists(hermesEngine)) {
return hermesEngine;
}
return path.join('node_modules', 'hermesvm', getHermesOSBin(), 'hermes');
}
function getComposeSourceMapsPath(): string {
// detect if compose-source-maps.js script exists
const composeSourceMaps = path.join(
'node_modules',
'react-native',
'scripts',
'compose-source-maps.js',
);
if (fs.existsSync(composeSourceMaps)) {
return composeSourceMaps;
}
return null;
}
export function getReactNativeVersion(): string {
try {
// eslint-disable-next-line security/detect-non-literal-require
const projectPackageJson: any = require(path.join(process.cwd(), 'package.json'));
const projectName: string = projectPackageJson.name;
if (!projectName) {
throw new Error(
`The "package.json" file in the CWD does not have the "name" field set.`,
);
}
return (
projectPackageJson.dependencies['react-native'] ||
(projectPackageJson.devDependencies &&
projectPackageJson.devDependencies['react-native'])
);
} catch (error) {
throw new Error(
`Unable to find or read "package.json" in the CWD. The "release-react" command must be executed in a React Native project folder.`,
);
}
}