microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
ce5e88eec6f7cd03403994764507be96c6af4624

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/extension/ios/iOSPlatform.ts

268lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import * as path from "path";
5import * as semver from "semver";
6
7import {ChildProcess} from "../../common/node/childProcess";
8import {CommandExecutor} from "../../common/commandExecutor";
9import {GeneralMobilePlatform, MobilePlatformDeps, TargetType} from "../generalMobilePlatform";
10import {IIOSRunOptions} from "../launchArgs";
11import {PlistBuddy} from "./plistBuddy";
12import {IOSDebugModeManager} from "./iOSDebugModeManager";
13import {OutputVerifier, PatternToFailure} from "../../common/outputVerifier";
14import {TelemetryHelper} from "../../common/telemetryHelper";
15import { InternalErrorCode } from "../../common/error/internalErrorCode";
16import * as nls from "vscode-nls";
17import { AppLauncher } from "../appLauncher";
18nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
19const localize = nls.loadMessageBundle();
20
21export class IOSPlatform extends GeneralMobilePlatform {
22 public static DEFAULT_IOS_PROJECT_RELATIVE_PATH = "ios";
23
24 private plistBuddy = new PlistBuddy();
25 private targetType: TargetType = "simulator";
26 private iosProjectRoot: string;
27 private iosDebugModeManager: IOSDebugModeManager;
28
29 private defaultConfiguration: string = "Debug";
30 private configurationArgumentName: string = "--configuration";
31
32 // We should add the common iOS build/run errors we find to this list
33 private static RUN_IOS_FAILURE_PATTERNS: PatternToFailure[] = [{
34 pattern: "No devices are booted",
35 errorCode: InternalErrorCode.IOSSimulatorNotLaunchable,
36 }, {
37 pattern: "FBSOpenApplicationErrorDomain",
38 errorCode: InternalErrorCode.IOSSimulatorNotLaunchable,
39 }, {
40 pattern: "ios-deploy",
41 errorCode: InternalErrorCode.IOSDeployNotFound,
42 }];
43
44 private static readonly RUN_IOS_SUCCESS_PATTERNS = ["BUILD SUCCEEDED"];
45
46 public showDevMenu(appLauncher: AppLauncher): Promise<void> {
47 const worker = appLauncher.getAppWorker();
48 if (worker) {
49 worker.showDevMenuCommand();
50 }
51
52 return Promise.resolve();
53 }
54
55 public reloadApp(appLauncher: AppLauncher): Promise<void> {
56 const worker = appLauncher.getAppWorker();
57 if (worker) {
58 worker.reloadAppCommand();
59 }
60 return Promise.resolve();
61 }
62
63 constructor(protected runOptions: IIOSRunOptions, platformDeps: MobilePlatformDeps = {}) {
64 super(runOptions, platformDeps);
65
66 this.runOptions.configuration = this.getConfiguration();
67
68 if (this.runOptions.iosRelativeProjectPath) { // Deprecated option
69 this.logger.warning(localize("iosRelativeProjectPathOptionIsDeprecatedUseRunArgumentsInstead", "'iosRelativeProjectPath' option is deprecated. Please use 'runArguments' instead."));
70 }
71
72 const iosProjectFolderPath = IOSPlatform.getOptFromRunArgs(this.runArguments, "--project-path", false);
73 this.iosProjectRoot = path.join(this.projectPath, iosProjectFolderPath || this.runOptions.iosRelativeProjectPath || IOSPlatform.DEFAULT_IOS_PROJECT_RELATIVE_PATH);
74 const schemeFromArgs = IOSPlatform.getOptFromRunArgs(this.runArguments, "--scheme", false);
75 this.iosDebugModeManager = new IOSDebugModeManager(this.iosProjectRoot, this.projectPath, schemeFromArgs ? schemeFromArgs : this.runOptions.scheme);
76
77 if (this.runArguments && this.runArguments.length > 0) {
78 this.targetType = (this.runArguments.indexOf(`--${IOSPlatform.deviceString}`) >= 0) ?
79 IOSPlatform.deviceString : IOSPlatform.simulatorString;
80 return;
81 }
82
83 if (this.runOptions.target && (this.runOptions.target !== IOSPlatform.simulatorString &&
84 this.runOptions.target !== IOSPlatform.deviceString)) {
85
86 this.targetType = IOSPlatform.simulatorString;
87 return;
88 }
89
90 this.targetType = this.runOptions.target || IOSPlatform.simulatorString;
91 }
92
93 public runApp(): Promise<void> {
94 let extProps = {
95 platform: {
96 value: "ios",
97 isPii: false,
98 },
99 };
100
101 extProps = TelemetryHelper.addPropertyToTelemetryProperties(this.runOptions.reactNativeVersions.reactNativeVersion, "reactNativeVersion", extProps);
102
103 return TelemetryHelper.generate("iOSPlatform.runApp", extProps, () => {
104 // Compile, deploy, and launch the app on either a simulator or a device
105 const env = GeneralMobilePlatform.getEnvArgument(process.env, this.runOptions.env, this.runOptions.envFile);
106
107 if (!semver.valid(this.runOptions.reactNativeVersions.reactNativeVersion) /*Custom RN implementations should support this flag*/ || semver.gte(this.runOptions.reactNativeVersions.reactNativeVersion, IOSPlatform.NO_PACKAGER_VERSION)) {
108 this.runArguments.push("--no-packager");
109 }
110 // Since @react-native-community/cli@2.1.0 build output are hidden by default
111 // we are using `--verbose` to show it as it contains `BUILD SUCCESSFUL` and other patterns
112 if (semver.gte(this.runOptions.reactNativeVersions.reactNativeVersion, "0.60.0")) {
113 this.runArguments.push("--verbose");
114 }
115 const runIosSpawn = new CommandExecutor(this.projectPath, this.logger).spawnReactCommand("run-ios", this.runArguments, {env});
116 return new OutputVerifier(
117 () =>
118 this.generateSuccessPatterns(this.runOptions.reactNativeVersions.reactNativeVersion),
119 () =>
120 Promise.resolve(IOSPlatform.RUN_IOS_FAILURE_PATTERNS), "ios")
121 .process(runIosSpawn);
122 });
123 }
124
125 public enableJSDebuggingMode(): Promise<void> {
126 // Configure the app for debugging
127 if (this.targetType === IOSPlatform.deviceString) {
128 // Note that currently we cannot automatically switch the device into debug mode.
129 this.logger.info("Application is running on a device, please shake device and select 'Debug JS Remotely' to enable debugging.");
130 return Promise.resolve();
131 }
132
133 // Wait until the configuration file exists, and check to see if debugging is enabled
134 return Promise.all<boolean | string>([
135 this.iosDebugModeManager.getSimulatorRemoteDebuggingSetting(this.runOptions.configuration, this.runOptions.productName),
136 this.getBundleId(),
137 ])
138 .then(([debugModeEnabled, bundleId]) => {
139 if (debugModeEnabled) {
140 return Promise.resolve();
141 }
142
143 // Debugging must still be enabled
144 // We enable debugging by writing to a plist file that backs a NSUserDefaults object,
145 // but that file is written to by the app on occasion. To avoid races, we shut the app
146 // down before writing to the file.
147 const childProcess = new ChildProcess();
148
149 return childProcess.execToString("xcrun simctl spawn booted launchctl list")
150 .then((output: string) => {
151 // Try to find an entry that looks like UIKitApplication:com.example.myApp[0x4f37]
152 const regex = new RegExp(`(\\S+${bundleId}\\S+)`);
153 const match = regex.exec(output);
154
155 // If we don't find a match, the app must not be running and so we do not need to close it
156 return match ? childProcess.exec(`xcrun simctl spawn booted launchctl stop ${match[1]}`) : null;
157 })
158 .then(() => {
159 // Write to the settings file while the app is not running to avoid races
160 return this.iosDebugModeManager.setSimulatorRemoteDebuggingSetting(/*enable=*/ true, this.runOptions.configuration, this.runOptions.productName);
161 })
162 .then(() => {
163 // Relaunch the app
164 return this.runApp();
165 });
166 });
167 }
168
169 public disableJSDebuggingMode(): Promise<void> {
170 return this.iosDebugModeManager.setSimulatorRemoteDebuggingSetting(/*enable=*/ false, this.runOptions.configuration, this.runOptions.productName);
171 }
172
173 public prewarmBundleCache(): Promise<void> {
174 return this.packager.prewarmBundleCache("ios");
175 }
176
177 public getRunArguments(): string[] {
178 let runArguments: string[] = [];
179
180 if (this.runOptions.runArguments && this.runOptions.runArguments.length > 0) {
181 runArguments = this.runOptions.runArguments;
182 if (this.runOptions.scheme) {
183 const schemeFromArgs = IOSPlatform.getOptFromRunArgs(runArguments, "--scheme", false);
184 if (!schemeFromArgs) {
185 runArguments.push("--scheme", this.runOptions.scheme);
186 } else {
187 this.logger.warning(localize("iosSchemeParameterAlreadySetInRunArguments", "'--scheme' is set as 'runArguments' configuration parameter value, 'scheme' configuration parameter value will be omitted"));
188 }
189 }
190 } else {
191 if (this.runOptions.target) {
192 runArguments.push(...this.handleTargetArg(this.runOptions.target));
193 }
194
195 if (this.runOptions.iosRelativeProjectPath) {
196 runArguments.push("--project-path", this.runOptions.iosRelativeProjectPath);
197 }
198
199 // provide any defined scheme
200 if (this.runOptions.scheme) {
201 runArguments.push("--scheme", this.runOptions.scheme);
202 }
203 }
204
205 return runArguments;
206 }
207
208 private handleTargetArg(target: string): string[] {
209 if (target === IOSPlatform.deviceString ||
210 target === IOSPlatform.simulatorString) {
211 return [`--${this.runOptions.target}`];
212 } else {
213 if (target.indexOf(IOSPlatform.deviceString) !== -1) {
214 const deviceArgs = target.split("=");
215 return deviceArgs[1] ? [`--${IOSPlatform.deviceString}`, deviceArgs[1]] : [`--${IOSPlatform.deviceString}`];
216 } else {
217 return [`--${IOSPlatform.simulatorString}`, `${this.runOptions.target}`];
218 }
219 }
220 }
221
222 private generateSuccessPatterns(version: string): Promise<string[]> {
223 // Clone RUN_IOS_SUCCESS_PATTERNS to avoid its runtime mutation
224 let successPatterns = [...IOSPlatform.RUN_IOS_SUCCESS_PATTERNS];
225 if (this.targetType === IOSPlatform.deviceString) {
226 if (semver.gte(version, "0.60.0")) {
227 successPatterns.push("success Installed the app on the device");
228 } else {
229 successPatterns.push("INSTALLATION SUCCEEDED");
230 }
231 return Promise.resolve(successPatterns);
232 } else {
233 return this.getBundleId()
234 .then(bundleId => {
235 if (semver.gte(version, "0.60.0")) {
236 successPatterns.push(`Launching "${bundleId}"\nsuccess Successfully launched the app `);
237 } else {
238 successPatterns.push(`Launching ${bundleId}\n${bundleId}: `);
239 }
240 return successPatterns;
241 });
242 }
243
244 }
245
246 private getConfiguration(): string {
247 return IOSPlatform.getOptFromRunArgs(this.runArguments, this.configurationArgumentName) || this.defaultConfiguration;
248 }
249
250 private getBundleId(): Promise<string> {
251 let scheme = this.runOptions.scheme;
252 if (!scheme) {
253 const schemeFromArgs = IOSPlatform.getOptFromRunArgs(this.runArguments, "--scheme", false);
254 if (schemeFromArgs) {
255 scheme = schemeFromArgs;
256 }
257 }
258 return this.plistBuddy.getBundleId(this.iosProjectRoot, this.projectPath, true, this.runOptions.configuration, this.runOptions.productName, scheme);
259 }
260
261 /*private static remote(fsPath: string): RemoteExtension { // TODO replace with a new implementation from appLauncher
262 if (this.remoteExtension) {
263 return this.remoteExtension;
264 } else {
265 return this.remoteExtension = RemoteExtension.atProjectRootPath(SettingsHelper.getReactNativeProjectRoot(fsPath));
266 }
267 }*/
268}
269