-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathdeploy.ts
More file actions
538 lines (485 loc) · 15.6 KB
/
deploy.ts
File metadata and controls
538 lines (485 loc) · 15.6 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
/**
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
* @format
*/
import {spawn, execSync, SpawnOptions} from 'child_process';
import fs from '@react-native-windows/fs';
import http from 'http';
import path from 'path';
import glob from 'glob';
import parse from 'xml-parser';
import WinAppDeployTool from './winappdeploytool';
import {
newInfo,
newSuccess,
newError,
newWarn,
newSpinner,
commandWithProgress,
runPowerShellScriptFunction,
} from './commandWithProgress';
import {findPowerShell} from '@react-native-windows/find-dotnet-tools';
import * as build from './build';
import {
BuildConfig,
RunWindowsOptions,
} from '../commands/runWindows/runWindowsOptions';
import MSBuildTools from './msbuildtools';
import type {Config} from '@react-native-community/cli-types';
import * as configUtils from '../commands/config/configUtils';
import type {WindowsProjectConfig} from '../commands/config/projectConfig';
import {CodedError} from '@react-native-windows/telemetry';
import Version from './version';
function pushd(pathArg: string): () => void {
const cwd = process.cwd();
process.chdir(pathArg);
return () => process.chdir(cwd);
}
export function getBuildConfiguration(options: RunWindowsOptions): BuildConfig {
return options.release
? options.bundle
? 'ReleaseBundle'
: 'Release'
: options.bundle
? 'DebugBundle'
: 'Debug';
}
function shouldDeployByPackage(
options: RunWindowsOptions,
config: Config,
): boolean {
if (options.deployFromLayout) {
// Force deploy by layout
return false;
}
let hasAppxSigningEnabled: boolean | null = null;
let hasPackageCertificateKeyFile: boolean | null = null;
// TODO: These two properties should really be determined by
// getting the actual values msbuild used during the build,
// but for now we'll try to get them manually
// Check passed in msbuild property overrides
if (options.msbuildprops) {
const msbuildprops = build.parseMsBuildProps(options);
if ('AppxSigningEnabled' in msbuildprops) {
hasAppxSigningEnabled =
msbuildprops.AppxSigningEnabled.toLowerCase() === 'true';
}
if ('PackageCertificateKeyFile' in msbuildprops) {
hasPackageCertificateKeyFile = true;
}
}
// If at least one override wasn't set, we need to parse the project file
if (hasAppxSigningEnabled === null || hasPackageCertificateKeyFile === null) {
const projectFile = build.getAppProjectFile(options, config);
if (projectFile) {
const projectContents = configUtils.readProjectFile(projectFile);
// Find AppxSigningEnabled
if (hasAppxSigningEnabled === null) {
const appxSigningEnabled = configUtils.tryFindPropertyValue(
projectContents,
'AppxSigningEnabled',
);
if (appxSigningEnabled !== null) {
hasAppxSigningEnabled = appxSigningEnabled.toLowerCase() === 'true';
}
}
// Find PackageCertificateKeyFile
if (hasPackageCertificateKeyFile === null) {
const packageCertificateKeyFile = configUtils.tryFindPropertyValue(
projectContents,
'PackageCertificateKeyFile',
);
if (packageCertificateKeyFile !== null) {
hasPackageCertificateKeyFile = true;
}
}
}
}
return (
hasAppxSigningEnabled === true && hasPackageCertificateKeyFile === true
);
}
function shouldLaunchApp(options: RunWindowsOptions): boolean {
return options.launch === true;
}
function getAppPackage(
options: RunWindowsOptions,
projectName?: string,
): string {
const configuration = getBuildConfiguration(options);
const packageFolder =
options.arch === 'x86'
? `{*_x86_${configuration}_*,*_Win32_${configuration}_*}`
: `*_${options.arch}_${configuration}_*`;
const appPackageGlob = `${options.root}/windows/{*/AppPackages,AppPackages/*}/${packageFolder}`;
const appPackageCandidates = glob.sync(appPackageGlob);
let appPackage;
if (appPackageCandidates.length === 1 || !projectName) {
appPackage = appPackageCandidates[0];
} else if (appPackageCandidates.length > 1) {
const filteredAppPackageCandidates = appPackageCandidates.filter(x =>
x.includes(projectName),
);
if (filteredAppPackageCandidates.length >= 1) {
appPackage = filteredAppPackageCandidates[0];
}
}
if (!appPackage && options.release) {
// in the latest vs, Release is removed
newWarn(
'No package found in *_Release_* folder, removing the _Release_ prefix and checking again',
);
const rootGlob = `${options.root}/windows/{*/AppPackages,AppPackages/*}`;
const newGlob = `${rootGlob}/*_${
options.arch === 'x86' ? '{Win32,x86}' : options.arch
}_Test`;
const result = glob.sync(newGlob);
if (result.length > 1 && projectName) {
const newFilteredGlobs = result.filter(x => x.includes(projectName));
if (newFilteredGlobs.length >= 1) {
newWarn(`More than one app package found: ${result}`);
}
appPackage = newFilteredGlobs[0];
} else if (result.length === 1) {
// we're good
appPackage = result[0];
}
}
if (!appPackage) {
throw new CodedError(
'NoAppPackage',
`Unable to find app package using search path: "${appPackageGlob}"`,
);
}
return appPackage;
}
function getWindowsStoreAppUtils(options: RunWindowsOptions) {
const popd = pushd(options.root);
const windowsStoreAppUtilsPath = path.resolve(
__dirname,
'..',
'..',
'src',
'powershell',
'WindowsStoreAppUtils.psm1',
);
const powershell = findPowerShell();
execSync(
`"${powershell}" -NoProfile -Command { Unblock-File '${windowsStoreAppUtilsPath}' }`,
);
popd();
return windowsStoreAppUtilsPath;
}
function getAppxManifestPath(
options: RunWindowsOptions,
projectName?: string,
): string {
const configuration = getBuildConfiguration(options);
// C++ x86 manifest would go under windows/Debug whereas x64 goes under windows/x64/Debug
// If we've built both, this causes us to end up with two matches, so we have to carefully select the right folder
let archFolder;
if (options.arch !== 'x86') {
archFolder = `${options.arch}/${configuration}`;
} else {
archFolder = `${configuration}`;
}
const appxManifestGlob = `windows/{*/bin/${options.arch}/${configuration},${archFolder}/*,target/${options.arch}/${configuration}}/AppxManifest.xml`;
const globs = glob.sync(path.join(options.root, appxManifestGlob));
let appxPath: string;
if (globs.length === 1 || !projectName) {
appxPath = globs[0];
} else {
const filteredGlobs = globs.filter(x => x.includes(projectName));
appxPath = filteredGlobs[0];
if (filteredGlobs.length > 1) {
newWarn(
`More than one appxmanifest for ${projectName}: ${filteredGlobs.join(
',',
)}`,
);
newWarn(`Choosing ${appxPath}`);
}
}
if (!appxPath) {
throw new CodedError(
'NoAppxManifest',
`Unable to find AppxManifest from "${options.root}", using search path: "${appxManifestGlob}" `,
);
}
return appxPath;
}
function getAppxRecipePath(
options: RunWindowsOptions,
projectName?: string,
): string {
const appxManifestPath = path.dirname(
getAppxManifestPath(options, projectName),
);
const appxRecipeGlob = `*.build.appxrecipe`;
const globs = glob.sync(path.join(appxManifestPath, appxRecipeGlob));
let appxRecipePath: string;
if (globs.length === 1 || !projectName) {
appxRecipePath = globs[0];
} else {
const filteredGlobs = globs.filter(x => x.includes(projectName));
appxRecipePath = filteredGlobs[0];
if (filteredGlobs.length > 1) {
newWarn(
`More than one appxrecipe for ${projectName}: ${filteredGlobs.join(
',',
)}`,
);
newWarn(`Choosing ${appxRecipePath}`);
}
}
if (!appxRecipePath) {
throw new CodedError(
'DeployRecipeFailure',
`Unable to find AppxRecipe from "${appxManifestPath}", using search path: "${appxRecipeGlob}" `,
);
}
return appxRecipePath;
}
function parseAppxManifest(appxManifestPath: string): parse.Document {
return parse(fs.readFileSync(appxManifestPath, 'utf8'));
}
function getAppxManifest(
options: RunWindowsOptions,
projectName?: string,
): parse.Document {
return parseAppxManifest(getAppxManifestPath(options, projectName));
}
function handleResponseError(e: Error): never {
if (e.message.indexOf('Error code -2146233088')) {
throw new CodedError(
'NoDevice',
`No Windows Mobile device was detected: ${e.message}`,
);
} else {
throw new CodedError(
'AppDidNotDeploy',
`Unexpected error deploying app: ${e.message}`,
);
}
}
// Errors: 0x80073d10 - bad architecture
export async function deployToDevice(
options: RunWindowsOptions,
verbose: boolean,
config: Config,
) {
const windowsConfig: Partial<WindowsProjectConfig> | undefined =
config.project.windows;
const projectName =
windowsConfig && windowsConfig.project && windowsConfig.project.projectName
? windowsConfig.project.projectName
: path.parse(options.proj!).name;
const appPackageFolder = getAppPackage(options);
const deployTarget = options.target
? options.target
: options.emulator
? 'emulator'
: 'device';
const deployTool = new WinAppDeployTool();
const appxManifest = getAppxManifest(options, projectName);
const shouldLaunch = shouldLaunchApp(options);
const identity = appxManifest.root.children.filter(x => {
return x.name === 'mp:PhoneIdentity';
})[0];
const appName = identity.attributes.PhoneProductId;
const device = deployTool.findDevice(deployTarget);
try {
await deployTool.uninstallAppPackage(appName, device, verbose);
} catch (e) {
newWarn('Failed to uninstall app from ' + device.name);
}
const appxFile = glob.sync(path.join(appPackageFolder, '*.appx'))[0];
try {
await deployTool.installAppPackage(
appxFile,
device,
shouldLaunch,
false,
verbose,
);
} catch (e) {
if ((e as Error).message.includes('Error code 2148734208 for command')) {
await deployTool.installAppPackage(
appxFile,
device,
shouldLaunch,
true,
verbose,
);
} else {
handleResponseError(e as Error);
}
}
}
export async function deployToDesktop(
options: RunWindowsOptions,
verbose: boolean,
config: Config,
buildTools: MSBuildTools,
) {
const useAppxCompatibility = !!process.env.TF_BUILD;
const windowsConfig: Partial<WindowsProjectConfig> | undefined =
config.project.windows;
const slnFile =
windowsConfig && windowsConfig.solutionFile && windowsConfig.sourceDir
? path.join(windowsConfig.sourceDir, windowsConfig.solutionFile)
: options.sln!;
const projectName =
windowsConfig && windowsConfig.project && windowsConfig.project.projectName
? windowsConfig.project.projectName
: path.parse(options.proj!).name;
const windowsStoreAppUtils = getWindowsStoreAppUtils(options);
const appxManifestPath = getAppxManifestPath(options, projectName);
const appxManifest = parseAppxManifest(appxManifestPath);
const identity = appxManifest.root.children.filter(x => {
return x.name === 'Identity';
})[0];
const appName = identity.attributes.Name;
const vsVersion = Version.fromString(buildTools.installationVersion);
const args = [];
if (options.directDebugging) {
args.push('--direct-debugging', options.directDebugging.toString());
}
await runPowerShellScriptFunction(
'Enabling Developer Mode',
windowsStoreAppUtils,
'EnableDevMode',
verbose,
'EnableDevModeFailure',
useAppxCompatibility,
);
const appPackageFolder = getAppPackage(options, projectName);
if (shouldDeployByPackage(options, config)) {
// Deploy by package
await runPowerShellScriptFunction(
'Removing old version of the app',
windowsStoreAppUtils,
`Uninstall-App ${appName}`,
verbose,
'RemoveOldAppVersionFailure',
useAppxCompatibility,
);
const script = glob.sync(
path.join(appPackageFolder, 'Add-AppDevPackage.ps1'),
)[0];
await runPowerShellScriptFunction(
'Installing new version of the app',
windowsStoreAppUtils,
`Install-App "${script}" -Force`,
verbose,
'InstallAppFailure',
useAppxCompatibility,
);
} else {
// Deploy from layout
// If we have DeployAppRecipe.exe, use it (start in 16.8.4, earlier 16.8 versions have bugs)
const appxRecipe = getAppxRecipePath(options, projectName);
const ideFolder = `${buildTools.installationPath}\\Common7\\IDE`;
const deployAppxRecipeExePath = `${ideFolder}\\DeployAppRecipe.exe`;
if (
vsVersion.gte(Version.fromString('16.8.30906.45')) &&
fs.existsSync(deployAppxRecipeExePath)
) {
await commandWithProgress(
newSpinner('Deploying'),
`Deploying ${appxRecipe}`,
deployAppxRecipeExePath,
[appxRecipe],
verbose,
'DeployRecipeFailure',
);
} else {
// Install the app package's dependencies before attempting to deploy.
await runPowerShellScriptFunction(
'Installing dependent framework packages',
windowsStoreAppUtils,
`Install-AppDependencies ${appxManifestPath} ${appPackageFolder} ${options.arch}`,
verbose,
'InstallAppDependenciesFailure',
useAppxCompatibility,
);
await build.buildSolution(
buildTools,
slnFile,
/* options.release ? 'Release' : */ 'Debug',
options.arch,
{DeployLayout: 'true'},
verbose,
'deploy',
options.buildLogDirectory,
);
}
}
const escapedAppName = appName.replace(/'/g, "''");
const appFamilyNameCommand = useAppxCompatibility
? `& { Import-Module Appx -UseWindowsPowerShell; (Get-AppxPackage -Name '${escapedAppName}').PackageFamilyName }`
: `(Get-AppxPackage -Name '${escapedAppName}').PackageFamilyName`;
const appFamilyName = execSync(
`"${findPowerShell()}" -NoProfile -Command "${appFamilyNameCommand}"`,
)
.toString()
.trim();
if (!appFamilyName) {
throw new CodedError(
'AppDidNotDeploy',
'Fail to check the installed app, maybe developer mode is off on Windows',
);
}
const loopbackText = 'Verifying loopbackExempt';
const loopbackSpinner = newSpinner(loopbackText);
await commandWithProgress(
loopbackSpinner,
loopbackText,
'CheckNetIsolation',
`LoopbackExempt -a -n=${appFamilyName}`.split(' '),
verbose,
'CheckNetIsolationFailure',
);
if (shouldLaunchApp(options)) {
await runPowerShellScriptFunction(
'Starting the app',
windowsStoreAppUtils,
`Start-Locally ${appName} ${args}`,
verbose,
'AppStartupFailure',
useAppxCompatibility,
);
} else {
newInfo('Skip the step to start the app');
}
}
export function startServerInNewWindow(
options: RunWindowsOptions,
verbose: boolean,
): Promise<void> {
return new Promise(resolve => {
http
.get('http://localhost:8081/status', res => {
if (res.statusCode === 200) {
newSuccess('React-Native Server already started');
} else {
newError('React-Native Server not responding');
}
resolve();
})
.on('error', () => {
launchServer(options, verbose);
resolve();
});
});
}
function launchServer(options: RunWindowsOptions, verbose: boolean) {
newSuccess('Starting the React-Native Server');
const opts: SpawnOptions = {
cwd: options.root,
detached: true,
stdio: verbose ? 'inherit' : 'ignore',
};
spawn('cmd.exe', ['/C', 'start npx @react-native-community/cli start'], opts);
}