microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
8152571adb22d7628c545490a38bc85153249841

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/android/adb.ts

218lines · 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 { ChildProcess, ISpawnResult } from "../../common/node/childProcess";
7import { CommandExecutor } from "../../common/commandExecutor";
8import * as path from "path";
9import * as fs from "fs";
10import { ILogger } from "../log/LogHelper";
11import * as os from "os";
12import * as nls from "vscode-nls";
13nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
14const localize = nls.loadMessageBundle();
15
16// See android versions usage at: http://developer.android.com/about/dashboards/index.html
17export enum AndroidAPILevel {
18 Marshmallow = 23,
19 LOLLIPOP_MR1 = 22,
20 LOLLIPOP = 21, /* Supports adb reverse */
21 KITKAT = 19,
22 JELLY_BEAN_MR2 = 18,
23 JELLY_BEAN_MR1 = 17,
24 JELLY_BEAN = 16,
25 ICE_CREAM_SANDWICH_MR1 = 15,
26 GINGERBREAD_MR1 = 10,
27}
28
29enum KeyEvents {
30 KEYCODE_BACK = 4,
31 KEYCODE_DPAD_UP = 19,
32 KEYCODE_DPAD_DOWN = 20,
33 KEYCODE_DPAD_CENTER = 23,
34 KEYCODE_MENU = 82,
35}
36
37export enum DeviceType {
38 AndroidSdkEmulator, // These seem to have emulator-<port> ids
39 Other,
40}
41
42export interface IDevice {
43 id: string;
44 isOnline: boolean;
45 type: DeviceType;
46}
47
48const AndroidSDKEmulatorPattern = /^emulator-\d{1,5}$/;
49
50export class AdbHelper {
51 private childProcess: ChildProcess = new ChildProcess();
52 private commandExecutor: CommandExecutor = new CommandExecutor();
53 private adbExecutable: string = "";
54 private launchActivity: string;
55
56 constructor(projectRoot: string, logger?: ILogger, launchActivity: string = "MainActivity") {
57 this.adbExecutable = this.getAdbPath(projectRoot, logger);
58 this.launchActivity = launchActivity;
59 }
60
61 /**
62 * Gets the list of Android connected devices and emulators.
63 */
64 public getConnectedDevices(): Q.Promise<IDevice[]> {
65 return this.childProcess.execToString(`${this.adbExecutable} devices`)
66 .then(output => {
67 return this.parseConnectedDevices(output);
68 });
69 }
70
71 public setLaunchActivity(launchActivity: string): void {
72 this.launchActivity = launchActivity;
73 }
74
75 /**
76 * Broadcasts an intent to reload the application in debug mode.
77 */
78 public switchDebugMode(projectRoot: string, packageName: string, enable: boolean, debugTarget?: string): Q.Promise<void> {
79 let enableDebugCommand = `${this.adbExecutable} ${debugTarget ? "-s " + debugTarget : ""} shell am broadcast -a "${packageName}.RELOAD_APP_ACTION" --ez jsproxy ${enable}`;
80 return new CommandExecutor(projectRoot).execute(enableDebugCommand)
81 .then(() => { // We should stop and start application again after RELOAD_APP_ACTION, otherwise app going to hangs up
82 let deferred = Q.defer();
83 setTimeout(() => {
84 this.stopApp(projectRoot, packageName, debugTarget)
85 .then(() => {
86 return deferred.resolve({});
87 });
88 }, 200); // We need a little delay after broadcast command
89
90 return deferred.promise;
91 })
92 .then(() => {
93 return this.launchApp(projectRoot, packageName, debugTarget);
94 });
95 }
96
97 /**
98 * Sends an intent which launches the main activity of the application.
99 */
100 public launchApp(projectRoot: string, packageName: string, debugTarget?: string): Q.Promise<void> {
101 let launchAppCommand = `${this.adbExecutable} ${debugTarget ? "-s " + debugTarget : ""} shell am start -n ${packageName}/.${this.launchActivity}`;
102 return new CommandExecutor(projectRoot).execute(launchAppCommand);
103 }
104
105 public stopApp(projectRoot: string, packageName: string, debugTarget?: string): Q.Promise<void> {
106 let stopAppCommand = `${this.adbExecutable} ${debugTarget ? "-s " + debugTarget : ""} shell am force-stop ${packageName}`;
107 return new CommandExecutor(projectRoot).execute(stopAppCommand);
108 }
109
110 public apiVersion(deviceId: string): Q.Promise<AndroidAPILevel> {
111 return this.executeQuery(deviceId, "shell getprop ro.build.version.sdk").then(output =>
112 parseInt(output, 10));
113 }
114
115 public reverseAdb(deviceId: string, packagerPort: number): Q.Promise<void> {
116 return this.execute(deviceId, `reverse tcp:${packagerPort} tcp:${packagerPort}`);
117 }
118
119 public showDevMenu(deviceId?: string): Q.Promise<void> {
120 let command = `${this.adbExecutable} ${deviceId ? "-s " + deviceId : ""} shell input keyevent ${KeyEvents.KEYCODE_MENU}`;
121 return this.commandExecutor.execute(command);
122 }
123
124 public reloadApp(deviceId?: string): Q.Promise<void> {
125 let command = `${this.adbExecutable} ${deviceId ? "-s " + deviceId : ""} shell input text "RR"`;
126 return this.commandExecutor.execute(command);
127 }
128
129 public getOnlineDevices(): Q.Promise<IDevice[]> {
130 return this.getConnectedDevices().then(devices => {
131 return devices.filter(device =>
132 device.isOnline);
133 });
134 }
135
136 public startLogCat(adbParameters: string[]): ISpawnResult {
137 return new ChildProcess().spawn(`${this.adbExecutable}`, adbParameters);
138 }
139
140 public parseSdkLocation(fileContent: string, logger?: ILogger) {
141 const matches = fileContent.match(/^sdk\.dir=(.+)$/m);
142 if (!matches || !matches[1]) {
143 if (logger) {
144 logger.info(localize("NoSdkDirFoundInLocalPropertiesFile", "No sdk.dir value found in local.properties file. Using Android SDK location from PATH."));
145 }
146 return null;
147 }
148
149 let sdkLocation = matches[1].trim();
150 if (os.platform() === "win32") {
151 // For Windows we need to unescape files separators and drive letter separators
152 sdkLocation = sdkLocation.replace(/\\\\/g, "\\").replace("\\:", ":");
153 }
154 if (logger) {
155 logger.info(localize("UsindAndroidSDKLocationDefinedInLocalPropertiesFile", "Using Android SDK location defined in android/local.properties file: {0}.", sdkLocation));
156 }
157
158 return sdkLocation;
159 }
160
161 public getAdbPath(projectRoot: string, logger?: ILogger): string {
162 // Trying to read sdk location from local.properties file and if we succueded then
163 // we would run adb from inside it, otherwise we would rely to PATH
164 const sdkLocation = this.getSdkLocationFromLocalPropertiesFile(projectRoot, logger);
165 return sdkLocation ? `"${path.join(sdkLocation, "platform-tools", "adb")}"` : "adb";
166 }
167
168 private parseConnectedDevices(input: string): IDevice[] {
169 let result: IDevice[] = [];
170 let regex = new RegExp("^(\\S+)\\t(\\S+)$", "mg");
171 let match = regex.exec(input);
172 while (match != null) {
173 result.push({ id: match[1], isOnline: match[2] === "device", type: this.extractDeviceType(match[1]) });
174 match = regex.exec(input);
175 }
176 return result;
177 }
178
179 private extractDeviceType(id: string): DeviceType {
180 return id.match(AndroidSDKEmulatorPattern)
181 ? DeviceType.AndroidSdkEmulator
182 : DeviceType.Other;
183 }
184
185 private executeQuery(deviceId: string, command: string): Q.Promise<string> {
186 return this.childProcess.execToString(this.generateCommandForDevice(deviceId, command));
187 }
188
189 private execute(deviceId: string, command: string): Q.Promise<void> {
190 return this.commandExecutor.execute(this.generateCommandForDevice(deviceId, command));
191 }
192
193 private generateCommandForDevice(deviceId: string, adbCommand: string): string {
194 return `${this.adbExecutable} -s "${deviceId}" ${adbCommand}`;
195 }
196
197 private getSdkLocationFromLocalPropertiesFile(projectRoot: string, logger?: ILogger): string | null {
198 const localPropertiesFilePath = path.join(projectRoot, "android", "local.properties");
199 if (!fs.existsSync(localPropertiesFilePath)) {
200 if (logger) {
201 logger.info(localize("LocalPropertiesFileDoesNotExist", "local.properties file doesn't exist. Using Android SDK location from PATH."));
202 }
203 return null;
204 }
205
206 let fileContent: string;
207 try {
208 fileContent = fs.readFileSync(localPropertiesFilePath).toString();
209 } catch (e) {
210 if (logger) {
211 logger.error(localize("CouldNotReadFrom", "Couldn't read from {0}.", localPropertiesFilePath), e, e.stack);
212 logger.info(localize("UsingAndroidSDKLocationFromPATH", "Using Android SDK location from PATH."));
213 }
214 return null;
215 }
216 return this.parseSdkLocation(fileContent, logger);
217 }
218}
219