microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.15.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/ios/iOSPlatform.ts

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