microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
4f8669f9862e5f7db84d8d4f84b7c0d2006d7bb6

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/ios/iOSPlatform.ts

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