microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2af998b74554389d49b275377a9f4283eb757deb

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/common/android/androidPlatform.ts

204lines · 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";
5
6import {GeneralMobilePlatform, MobilePlatformDeps } from "../generalMobilePlatform";
7import {Packager} from "../packager";
8import {IAndroidRunOptions} from "../launchArgs";
9import {Log} from "../log/log";
10import {IAdb, Adb, AndroidAPILevel, IDevice, DeviceType} from "./adb";
11import {Package} from "../node/package";
12import {PromiseUtil} from "../node/promise";
13import {PackageNameResolver} from "./packageNameResolver";
14import {OutputVerifier, PatternToFailure} from "../outputVerifier";
15import {TelemetryHelper} from "../telemetryHelper";
16import {CommandExecutor} from "../../common/commandExecutor";
17
18export interface AndroidPlatformDeps extends MobilePlatformDeps {
19 adb?: IAdb;
20}
21/**
22 * Android specific platform implementation for debugging RN applications.
23 */
24export class AndroidPlatform extends GeneralMobilePlatform {
25 private static MULTIPLE_DEVICES_ERROR = "error: more than one device/emulator";
26
27 // We should add the common Android build/run erros we find to this list
28 private static RUN_ANDROID_FAILURE_PATTERNS: PatternToFailure[] = [{
29 pattern: "Failed to install on any devices",
30 message: "Could not install the app on any available device. Make sure you have a correctly"
31 + " configured device or emulator running. See https://facebook.github.io/react-native/docs/android-setup.html",
32 }, {
33 pattern: "com.android.ddmlib.ShellCommandUnresponsiveException",
34 message: "An Android shell command timed-out. Please retry the operation.",
35 }, {
36 pattern: "Android project not found",
37 message: "Android project not found.",
38
39 }, {
40 pattern: "error: more than one device/emulator",
41 message: AndroidPlatform.MULTIPLE_DEVICES_ERROR,
42 }, {
43 pattern: /^Error: Activity class \{.*\} does not exist\.$/m,
44 message: "Failed to launch the specified activity. Try running application manually and "
45 + "start debugging using 'Attach to packager' launch configuration.",
46 }];
47
48 private static RUN_ANDROID_SUCCESS_PATTERNS: string[] = ["BUILD SUCCESSFUL", "Starting the app", "Starting: Intent"];
49
50 private debugTarget: IDevice;
51 private devices: IDevice[];
52 private packageName: string;
53 private adb: IAdb;
54
55 private needsToLaunchApps: boolean = false;
56
57 // We set remoteExtension = null so that if there is an instance of androidPlatform that wants to have it's custom remoteExtension it can. This is specifically useful for tests.
58 constructor(protected runOptions: IAndroidRunOptions, {
59 remoteExtension,
60 adb = <IAdb>new Adb(),
61 }: AndroidPlatformDeps = {}) {
62 super(runOptions, { remoteExtension: remoteExtension });
63 this.adb = adb;
64 }
65
66 public runApp(shouldLaunchInAllDevices: boolean = false): Q.Promise<void> {
67 return TelemetryHelper.generate("AndroidPlatform.runApp", () => {
68 const runArguments = this.getRunArgument();
69 const runAndroidSpawn = new CommandExecutor(this.projectPath).spawnReactCommand("run-android", runArguments);
70
71 const output = new OutputVerifier(
72 () =>
73 Q(AndroidPlatform.RUN_ANDROID_SUCCESS_PATTERNS),
74 () =>
75 Q(AndroidPlatform.RUN_ANDROID_FAILURE_PATTERNS)).process(runAndroidSpawn);
76
77 return output
78 .finally(() => {
79 return this.initializeTargetDevicesAndPackageName();
80 }).then(() => [this.debugTarget], reason => {
81 if (reason.message === AndroidPlatform.MULTIPLE_DEVICES_ERROR && this.devices.length > 1 && this.debugTarget) {
82 /* If it failed due to multiple devices, we'll apply this workaround to make it work anyways */
83 this.needsToLaunchApps = true;
84 return shouldLaunchInAllDevices
85 ? this.adb.getOnlineDevices()
86 : Q([this.debugTarget]);
87 } else {
88 return Q.reject<IDevice[]>(reason);
89 }
90 }).then(devices => {
91 return new PromiseUtil().forEach(devices, device => {
92 return this.launchAppWithADBReverseAndLogCat(device);
93 });
94 });
95 });
96 }
97
98 public enableJSDebuggingMode(): Q.Promise<void> {
99 return this.adb.reloadAppInDebugMode(this.runOptions.projectRoot, this.packageName, this.debugTarget.id);
100 }
101
102 public prewarmBundleCache(): Q.Promise<void> {
103 return this.remoteExtension.prewarmBundleCache(this.platformName);
104 }
105
106 public getRunArgument(): string[] {
107 let runArguments: string[] = [];
108
109 if (this.runOptions.runArguments && this.runOptions.runArguments.length > 0) {
110 runArguments = this.runOptions.runArguments;
111 } else {
112 if (this.runOptions.variant) {
113 runArguments.push("--variant", this.runOptions.variant);
114 }
115 if (this.runOptions.target) {
116 runArguments.push("--deviceId", this.runOptions.target);
117 }
118 }
119
120 return runArguments;
121 }
122
123 private initializeTargetDevicesAndPackageName(): Q.Promise<void> {
124 return this.adb.getConnectedDevices().then(devices => {
125 this.devices = devices;
126 this.debugTarget = this.getTargetEmulator(devices);
127 return this.getPackageName().then(packageName => {
128 this.packageName = packageName;
129 });
130 });
131 }
132
133 private launchAppWithADBReverseAndLogCat(device: IDevice): Q.Promise<void> {
134 return Q({})
135 .then(() => {
136 return this.configureADBReverseWhenApplicable(device);
137 }).then(() => {
138 return this.needsToLaunchApps
139 ? this.adb.launchApp(this.runOptions.projectRoot, this.packageName, device.id)
140 : Q<void>(void 0);
141 }).then(() => {
142 return this.startMonitoringLogCat(device, this.runOptions.logCatArguments).catch(error => // The LogCatMonitor failing won't stop the debugging experience
143 Log.logWarning("Couldn't start LogCat monitor", error));
144 });
145 }
146
147 private configureADBReverseWhenApplicable(device: IDevice): Q.Promise<void> {
148 if (device.type !== DeviceType.AndroidSdkEmulator) {
149 return Q({}) // For other emulators and devices we try to enable adb reverse
150 .then(() => this.adb.apiVersion(device.id))
151 .then(apiVersion => {
152 if (apiVersion >= AndroidAPILevel.LOLLIPOP) { // If we support adb reverse
153 return this.adb.reverseAdd(device.id, Packager.DEFAULT_PORT.toString(), this.runOptions.packagerPort);
154 } else {
155 Log.logWarning(`Device ${device.id} supports only API Level ${apiVersion}. `
156 + `Level ${AndroidAPILevel.LOLLIPOP} is needed to support port forwarding via adb reverse. `
157 + "For debugging to work you'll need <Shake or press menu button> for the dev menu, "
158 + "go into <Dev Settings> and configure <Debug Server host & port for Device> to be "
159 + "an IP address of your computer that the Device can reach. More info at: "
160 + "https://facebook.github.io/react-native/docs/debugging.html#debugging-react-native-apps");
161 return void 0;
162 }
163 });
164 } else {
165 return Q<void>(void 0); // Android SDK emulators can connect directly to 10.0.0.2, so they don't need port forwarding
166 }
167 }
168
169 private getPackageName(): Q.Promise<string> {
170 return new Package(this.runOptions.projectRoot).name().then(appName =>
171 new PackageNameResolver(appName).resolvePackageName(this.runOptions.projectRoot));
172 }
173
174 /**
175 * Returns the target emulator, using the following logic:
176 * * If an emulator is specified and it is connected, use that one.
177 * * Otherwise, use the first one in the list.
178 */
179 private getTargetEmulator(devices: IDevice[]): IDevice {
180 let activeFilterFunction = (device: IDevice) => {
181 return device.isOnline;
182 };
183
184 let targetFilterFunction = (device: IDevice) => {
185 return device.id === this.runOptions.target && activeFilterFunction(device);
186 };
187
188 if (this.runOptions && this.runOptions.target && devices) {
189 /* check if the specified target is active */
190 const targetDevice = devices.find(targetFilterFunction);
191 if (targetDevice) {
192 return targetDevice;
193 }
194 }
195
196 /* return the first active device in the list */
197 let activeDevices = devices && devices.filter(activeFilterFunction);
198 return activeDevices && activeDevices[0];
199 }
200
201 private startMonitoringLogCat(device: IDevice, logCatArguments: string): Q.Promise<void> {
202 return this.remoteExtension.startMonitoringLogcat(device.id, logCatArguments);
203 }
204}
205